拥有并属于许多添加视图

时间:2011-06-16 19:21:55

标签: ruby-on-rails ruby-on-rails-3 has-and-belongs-to-many

如果我有这种关系,我将如何添加到我的视图中,以便在创建学生时,我会收到一个文本框,我可以为新学生添加多个课程?

class Student < ActiveRecord::Base
  has_and_belongs_to_many :courses
end

class Course < ActiveRecord::Base
  has_and_belongs_to_many :students
end


<%= form_for(@student) do |f| %>

    <%= f.label :name %><br />
    <%= f.text_field :name%><br />

    <%= f.label :description %><br />
    <%= f.text_field :description %><br />

    <%= f.submit %><br />
<% end %>

3 个答案:

答案 0 :(得分:0)

看一下来自Railscasts的精彩Nested Model Form系列。

答案 1 :(得分:0)

我建议您按如下方式重构模型:

class Student < ActiveRecord::Base
  has_many :enrollments
  has_many :courses, :through => :enrollments
end

class Course < ActiveRecord::Base
  has_many :enrollments
  has_many :students, :through => :enrollments
end

class Enrollment < ActiveRecord::Base
  belongs_to :student
  belongs_to :course
end

并使用RyanB的nested_form gem:https://github.com/ryanb/nested_form

答案 2 :(得分:0)

&lt;%= form_for(@student)do | f | %GT;

<%= f.label :name %><br />
<%= f.text_field :name%><br />

<%= f.label :description %><br />
<%= f.text_field :description %><br />
<%= f.fields_for :courses do |cf| %>
   ....course attributes
<% end %>
<%= f.submit %><br />

&lt;%end%&gt;

在您的控制器操作中:   @ student.courses.build 这将创建一门课程

或n次   @ student.courses.build 端

将向学生对象添加n门课程