简体   繁体   English

从控制器到关联模型

[英]Getting from controller to associated model

I can't get along with saving Students with one POST when i"m saving Project. 保存项目时,我无法通过一个POST来保存学生。

My Projects controller looks like: 我的项目控制器看起来像:

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

And a new_project view looks like: 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 %>

And my question is how to save Project and Students (assigned to it) using one form? 我的问题是如何使用一种形式保存“项目和学生”(分配给它)?

First, your project_params method isn't allowing the students' names to be submitted. 首先,您的project_params方法不允许提交学生的姓名。 Try something like this: 尝试这样的事情:

def project_params
  params.require(:project).permit(:name, :lecturer, students_attributes: [ :name ] )
end

Next, in your Project model you'll need the line 接下来,在您的Project模型中,您需要

accepts_nested_attributes_for :students

(You might have put it there already - but if you didn't, you'll need to.) (您可能已经把它放在那里了,但是如果没有,则需要这样做。)

Now that that's done, you shouldn't need these lines in your Project#create method: 既然完成了,您在Project#create方法中就不需要这些行了:

@project.students.each do |student|
  student = Student.new(params[:name])
end

Because your project can now accept nested attributes for students, they should be created automatically with the project when you save it. 由于您的项目现在可以接受学生的嵌套属性,因此在save项目时应与项目一起自动创建它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM