嗨,我正在学习has_many:通过,我有这样的协会。
学生:
has_many :subjects, through: :participations
has_many :participations
主题:
has_many :students, through: :participations
has_many :participations
belongs_to :student
参与:
belongs_to :student
belongs_to :subject
student
主题通过更新视图中的复选框进行更新:
= f.association :subjecs, label_method: :title, value_method: :id, label: 'Subjects', as: :check_boxes
我走了这么远:(我的学生有科目ID,但由于没有参与,所以不能得到他们。
我的更新操作:
def create
student = Student.new(student_params)
if student.save
redirect_to students_path
else
render 'edit'
end
end
我的问题是我应该何时创建参与对象,该函数的适当位置在哪里?
答案 0 :(得分:2)
当你有has_many
关系时,你实际上得到了一堆可以帮助你的方法。
其中一个是association_singular_ids
- 如果您正确填充它,将自动创建您需要的关联数据。
执行此操作的方法是使用以下内容:
#app/views/students/new.html.erb
<%= form_for @student do |f| %>
<%= f.collection_check_boxes :subject_ids, Subject.all, :id, :name %>
<%= f.submit %>
<% end %>
我知道您正在使用f.association
(通过simple_form
构建) - 您将更适合使用collection_check_boxes
(它甚至可以解释一个示例)你遇到什么问题。
您不应该传递参数或任何内容 - 并且因为您的participations
模型充当联接,如果您使用上述代码,则应自动填充。
您可能还希望查看has_and_belongs_to_many
:
#app/models/student.rb
class Student < ActiveRecord::Base
has_and_belongs_to_many :subjects
end
#app/models/subject.rb
class Subject < ActiveRecord::Base
has_and_belongs_to_many :students
end
#join table - students_subjects
这通常优于has_many :through
,因为它需要较少的维护(如上面的链接所述)。
嵌套属性
最后,为了给您提供更多视角,您需要了解Rails的嵌套属性方面。
我原本以为你的回答是你没有使用accepts_nested_attributes_for
,但我现在不这么认为。尽管如此,您仍然可以从了解它中获益。
-
您使用has_many through
的原因之一是使用其他属性填充连接模型。 HABTM不允许这样做;因为has_many :through
有一个连接模型(在你的情况下是participations
),它允许你在其中添加额外的属性。
因此,如果您正在寻找更改这些属性,那么您需要通过各种模式传递它们:
#app/models/student.rb
class Student < ActiveRecord::Base
has_many :participations
has_many :subjects, through: :participations
accepts_nested_attributes_for :participations
end
#app/models/participation.rb
class Participation < ActiveRecord::Base
belongs_to :student
belongs_to :subject
accepts_nested_attributes_for :student
end
#app/models/subject.rb
class Subject< ActiveRecord::Base
has_many :participations
has_many :students, through: :participations
end
这将允许您使用以下内容:
#app/controllers/students_controller.rb
class StudentsController < ApplicationController
def new
@student = Student.new
@student.participations.build
end
def create
@student = Student.new student_params
@student.save
end
private
def student_params
params.require(:student).permit(:student, :params, participations_attributes: [subject_attributes:[]])
end
end
这应该允许您使用以下内容:
#app/views/students/new.html.erb
<%= form_for @student do |f| %>
<%= f.fields_for :participations do |p| %>
<%= p.text_field :name %>
<%= p.collection_check_boxes :subject_id, Subject.all, :id, :name %>
<% end %>
<%= f.submit %>
<% end %>
答案 1 :(得分:0)
我的问题是我没有在学生管理员中提出过chenge od subject_ids:
params.require(:student).permit(:first_name, :last_name, subject_ids: [])