我正在尝试以嵌套形式实现一个复选框。
我有 3 个模型:主题、课程和小组。A Subjects 有很多课,每课都有并且属于很多组。
换句话说:我将Subjects作为父类,将Lessons作为子类,将Groups作为“孙子”类。
在“主题”表单中,我允许以嵌套形式创建 3 个课程。我之前已经创建了组,现在,我想在每节课中为组创建 HABTM 复选框,但是我在尝试在 Rails 中发送参数时遇到了一些麻烦。
参数的主要区别是目前我正在发送
"lesson"=>{"group_ids"=>["105", "106", "107"]}
在其自己的。但是,我想要的是为该主题的每个单独课程发送 group_ids,如下所示:
"lessons_attributes"=>{"0"=>{"lesson_type"=>"Lecture",
"id"=>"348",
"group_ids"=>["37", "38", "39", "40", "41", "42", "131"]}.
详细地说,这是我发送的完整当前参数:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"7r9g2d4lmiSyNZ60i8uos9m1shxVwb0Ly23Tkrshv8w=", "subject"=>{"subject_code"=>"", "subject_name"=>"",
"lessons_attributes"=>{"0"=>{"lesson_type"=>"Lecture", "id"=>"348"},
"1"=>{"lesson_type"=>"Tutorial","id"=>"349"},
"2"=>{"lesson_type"=>"Laboratory","id"=>"350"}},
"remarks"=>""},
"lesson"=>{"group_ids"=>["105", "106", "107"]}, "commit"=>"Update Subject", "id"=>"166"}
然而,我想发送的参数是这样的:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"7r9g2d4lmiSyNZ60i8uos9m1shxVwb0Ly23Tkrshv8w=", "subject"=>{"subject_code"=>"", "subject_name"=>"",
"lessons_attributes"=>{"0"=>{"lesson_type"=>"Lecture", "id"=>"348","group_ids"=>["37", "38", "39", "40", "41", "42", "131"]},
"1"=>{"lesson_type"=>"Tutorial","id"=>"349",
"group_ids"=>["37", "38", "39", "40", "41", "42", "131"],
"2"=>{"lesson_type"=>"Laboratory","id"=>"350",
"group_ids"=>["37", "38", "39", "40", "41", "42", "131"]}}, "remarks"=>""}, "commit"=>"Update Subject", "id"=>"166"}
我没有正确发送参数,问题在于:`
<%= check_box_tag "lesson[group_ids][]", group.id, f.object.groups.include?(group) , id: "lesson_group_ids_#{group.id}"%>`
特别是对于我的复选框,我正在实施这个:课程[group_ids][]。
我也尝试过 course_attributes[group_ids][]。但同样,我无法保存 HABTM 关系。我不确定我能做些什么来让小组为每节课节省开支。任何帮助,将不胜感激。
这些是相关代码:
<%= form_for(@subject) do |f| %>
<div class="field">
<%= f.label :subject_name %><br />
<%= f.text_field :subject_name %>
</div>
<div>
<%= f.fields_for :lessons do |lesson| %>
<%= render "lesson_fields", :f => lesson %>
<% end %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
在 _lesson_fields.html.erb 中,我有:
<div class="field">
<%= f.label :lesson_type %><br />
<%= f.text_field :lesson_type,:readonly => true %>
</div>
<div>
<% Group.all.each do |group|%>
<div>
<%= check_box_tag "lesson[group_ids][]", group.id, f.object.groups.include?(group) , id: "lesson_group_ids_#{group.id}"%>
<%= group.group_index %>
</div>
<%end%>
</div>
对于模型
相关型号:
class Subject < ActiveRecord::Base
attr_accessible :lessons_attributes
has_many :lessons
end
class Lesson < ActiveRecord::Base
belongs_to :subject
has_and_belongs_to_many :groups
end
class Group < ActiveRecord::Base
has_and_belongs_to_many :lessons
end