HABTM checkbox in nested form

I am trying to implement the HABTM flag in a nested form.

I currently have 3 models. Subject, lesson and groups. Associations are as follows: Each subject has many lessons. Each lesson has and belongs to many groups.

Now I am trying to implement them all in one form of creation and editing. Thus, the lesson is embedded in the topic, and for each lesson there is a list of group flags for implementing the HABTM relationship.

I ran into the problem of implementing a HABTM relationship, as there are many lessons in subjects, and I'm not sure how I could distinguish between different lessons.

In order to dwell in more detail, I can get the work of the nested form, but I can not check the HABTM checkboxes to save the necessary lessons. The following code example is my implementation of the HABTM flag.

  <% Group.all.each do |group|%>
      <%= check_box_tag "subject[lessons_attributes[0]][group_ids][]", group.id, f.object.groups.include?(group) %>
      <%= group.group_index %>
  <%end%>

I currently saved it in the first lesson using this line "subject [lessons_attributes [0]] [group_ids] []".

However, the number of lessons is changing, and I'm not too sure how I could define the lesson "number", that is, bold 0 in "subject [lessons_attributes [ 0 ]] [group_ids] []". So that I can save the groups in the right lesson.

Any advice would be appreciated.

+5
source share
2 answers

, () ( form.object), . simple_form formtastic, :

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

check_box_tag, :

<% 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 %>
+5

, Rails 4 ( )

Group.all.each @Viktor TrΓ³n : FormBuilder, collection_check_boxes, !

:

<% 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 %>

accepts_nested_attributes_for :lessons Subject, SubjectsController subject_params "" :

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

SubjectsController create update : , @subject = Subject.create(subject_params), , HABTM ( -!).

+8

All Articles