当我保存Project.时,我无法用一个POST保存学生
我的项目控制器看起来像:
class ProjectsController < ApplicationController
def index
@projects = Project.all
end
def new
@project = Project.new
3.times do
student = @project.students.build
end
end
def create
@project = Project.new(project_params)
@project.status = "Waiting"
# I'm not sure about these lines
@project.students.each do |student|
student = Student.new(params[:name])
end
@project.save!
redirect_to projects_path
end
private
def project_params
params.require(:project).permit(:name, :lecturer)
end
end
new_project
视图看起来像:
<h1>Creating new project...</h1>
<%= form_for @project, url: projects_path do |f| %>
<p>
<%= f.label :name %>
<%= f.text_field :name %>
</p>
<p>
<%= f.label :lecturer %>
<%= f.text_field :lecturer %>
</p>
<p>
<%= f.fields_for :students do |s| %>
<%= s.label :name %>
<%= s.text_field :name %>
<% end %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
我的问题是如何使用一个表单保存项目和学生(分配给它)
首先,您的project_params
方法不允许提交学生的姓名。试试这样的东西:
def project_params
params.require(:project).permit(:name, :lecturer, students_attributes: [ :name ] )
end
接下来,在您的Project
模型中,您将需要线
accepts_nested_attributes_for :students
(你可能已经把它放在那里了,但如果你没有,你就需要放。)
既然已经完成了,那么在Project#create
方法中就不需要这些行了:
@project.students.each do |student|
student = Student.new(params[:name])
end
因为你的项目现在可以接受学生的嵌套属性,所以当你save
它时,它们应该与项目一起自动创建。