HABTM checkbox in a nested form

≯℡__Kan透↙ 提交于 2019-12-04 08:24:52

the best practice is to prebuild (a few) lesson object on the subject (that is the form.object), then you iterate over them to have per-lesson fields. if you use simple_form or formtastic, collection select via checkboxes is easy:

<% form_for @subject do |form| %>
  ....
  <% form.fields_for :lessons do |lesson_form| %>
    ...
    <% lesson_form.input :group_ids, :as => :check_boxes %>

if you wanna use check_box_tag, you should iterate through lessons with an index and substitute the index in your checkbox name:

<% form_for @subject do |form| %>
  ....
  <% @subject.lessons.each_with_index do |l, i| %>
     <% Group.all.each do |group|%>
        <%= check_box_tag "subject[lessons_attributes[#{i}]][group_ids][]", group.id, l.groups.include?(group) %>
        <%= group.group_index %>
     <% end %>
Olivier Lance

For those working with Rails 4 and having the same question (as I had)

The Group.all.each loop in @Viktor Trón's answer is unnecessary: There's a new FormBuilder method, collection_check_boxes, which has been created just for that!

Your code would be:

<% form_for @subject do |form| %>
  ....
  <% @subject.lessons.each_with_index do |l, i| %>
     <%= form.fields_for :lessons, l do |lesson_fields|%>
        <%= lesson_fields.collection_check_boxes :group_ids, Group.all, :id, :group_index %>
     <% end %>
 <% end %>
<% end %>

You then have to add accepts_nested_attributes_for :lessons to your Subject model, and in your SubjectsController, change the subject_params method to "permit" nested params for lessons:

params.require(:subject).permit(..., lessons_attributes: [:id, group_ids: []])

In your SubjectsController, the create or update actions remain unchanged: @subject = Subject.create(subject_params) for instance, will create the Subject, the associated lessons and update their HABTM relationships to groups correctly (unless I made a mistake somewhere!).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!