嵌套表单 - 如何将现有嵌套对象添加到父表单?

Chr*_*ini 4 forms ruby-on-rails relationship

我的模型设置为多对多关系:

class Workshop < ActiveRecord::Base
  has_many :workshop_students
  has_many :students, :through => :student_workshops

  accepts_nested_attributes_for :students
end

class Student < ActiveRecord::Base
  has_many :student_workshops
  has_many :workshops, :through => :student_workshops

  accepts_nested_attributes_for :products
end

class StudentWorkshop < ActiveRecord::Base
  belongs_to :student
  belongs_to :workshop
end
Run Code Online (Sandbox Code Playgroud)

如您所见,学生可以参加许多研讨会,研讨会可以有很多学生.

我看过以下Rails演员:这里这里.我偶然发现的大多数在线资源都只展示了如何在父表单中创建新对象的嵌套表单.

我不想创建一个新对象.我只想将现有对象添加到父窗体.所以举个例子.如果我决定创建一个新的研讨会,我想将现有的学生分配到研讨会.

我不明白的一件事是,我如何将学生链接到研讨会表格?第二,当params通过时,控制器方法中应该有什么更新/创建?

如果有人能指出我正确的方向,我将不胜感激.

Wil*_*elm 5

最简单的方法是:

<%= f.collection_select(:student_ids, Student.all, :id, :name, {:include_blank => true}, {:selected => @workshop.student_ids, :multiple => true} )%>
Run Code Online (Sandbox Code Playgroud)

您不必在创建操作中执行任何操作.