嵌套窗体——如何将现有的嵌套对象添加到父窗体中?

时间:2021-02-18 16:46:44

I've got my models setup for a many-to-many 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

As you can see above, a student can have many workshops and workshop can have many students.

正如你在上面看到的,一个学生可以有许多研讨会和工作坊可以有许多学生。

I've looked at the following Rails casts: here and here. And most of the online sources I stumble across only show how to do nested forms for creating new objects within the parent form.

我已经看过以下Rails强制类型转换:这里和这里。我偶然发现的大多数在线资源只展示了如何在父窗体中创建新对象的嵌套窗体。

I don't want to create a new object. I only want to add an existing object to the parent form. So for example. If I decide to create a new workshop, I'd like to assign existing students to the workshop.

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

One thing I don't understand is, how do I link students into the workshop form? Second, when the params are passed, what should be in the controller method for update/create?

我不明白的一件事是,我如何将学生与研讨会的形式联系起来?其次,当传递params时,在controller方法中应该有什么用于更新/创建?

If anyone can point me to the right direction, I would appreciate it.

如果有人能给我指出正确的方向,我会很感激。

2 个解决方案

#1


5  

The easiest thing to do is:

最简单的事情是:

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

You should not have to do anything in the create action.

您不应该在创建操作中做任何事情。

#2


0  

Ok, for anyone coming across the same issue in the future. The solution I came up with was in def create. I am able to access a POST attribute called student_ids, which comes in the form of an array

好的,对于将来遇到同样问题的人。我想到的解决方案是def create。我可以访问名为student_ids的POST属性,它以数组的形式出现

#1


5  

The easiest thing to do is:

最简单的事情是:

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

You should not have to do anything in the create action.

您不应该在创建操作中做任何事情。

#2


0  

Ok, for anyone coming across the same issue in the future. The solution I came up with was in def create. I am able to access a POST attribute called student_ids, which comes in the form of an array

好的,对于将来遇到同样问题的人。我想到的解决方案是def create。我可以访问名为student_ids的POST属性,它以数组的形式出现