Rails nested form with multiple entries

后端 未结 3 487
死守一世寂寞
死守一世寂寞 2021-01-17 03:34

I have a Sezzion model:

attr_accessible  :description
has_many :session_instructors, :dependent => :destroy
has_many :instructors, :through =         


        
3条回答
  •  天命终不由人
    2021-01-17 04:06

    This is something that seems ridiculously hard in Rails.

    I think something like this might work:

    <%= f.fields_for :session_instructors do |si| %>
      <%= si.collection_select :instructor_ids, current_user.instructors, :id, :name, multiple: true>
    <% end %>
    

    This should create a form element which will set sezzion[session_instructors_attributes][instructor_ids].

    Although I'm not sure if that's actually what you want. I've never tried this using a multi select. If it doesn't work, you could also try getting rid of the fields_for and just using f.collection_select. If you're willing to use a checkbox, I can show you how to do that for sure.

    I hope that helps.

    Edit:

    Here's how I would usually do it with a check_box:

    <%= f.fields_for :session_instructors do |si| %>
      <%= si.hidden_field "instructor_ids[]" %>
      <% current_user.instructors.each do |i| %>
        <%= si.check_box "instructor_ids[]", i.id, i.sezzions.include?(@sezzion), id: "instructor_ids_#{i.id}" %>
        <%= label_tag "instructor_ids_#{i.id}", i.name %>
      <% end %>
    <% end%>
    

    There are a couple "gotchas!" with this method. When editing a model, if you deselect all checkboxes then it won't send the parameter at all. That's why the hidden_field is necessary. Also, you need to make sure each form element has a unique id field. Otherwise only the last entry is sent. That's why I manually set the value myself.

    I copy pasted and then edited. Hopefully I got the syntax close enough where you can get it to work.

    FINAL EDIT:

    Per Sayanee's comment below, the answer was a bit simpler than I thought:

    <%= f.collection_select :instructor_ids, current_user.instructors, :id, :name, {}, {:multiple => true} %>
    

提交回复
热议问题