I have a Sezzion model:
attr_accessible :description
has_many :session_instructors, :dependent => :destroy
has_many :instructors, :through => :session_instructors
accepts_nested_attributes_for :session_instructors
accepts_nested_attributes_for :instructors
Instructor model:
attr_accessible :bio
has_many :sezzions, :through => :session_instructors
has_many :session_instructors, :dependent => :destroy
SessionInstructor model:
attr_accessible :instructor_id, :sezzion_id
belongs_to :sezzion
belongs_to :instructor
Lastly, User model:
has_many :sezzions
has_many :instructors
I’m trying to create a form for Sezzion with nested form for SessionInstructor which has multiple select option for Instructors.
How can I do the following:
- nested form for
SessionInstructor - use multiple select option to get all the selected
Instructor‘sinstructor_id - hidden field to pass in the created/updated
session_idwith each select instructor
I have the following code as of now:
<%= form_for(@sezzion) do |f| %>
<%= f.label :description %>
<%= f.text_area :description %>
<%= f.label :instructors %>
<%= fields_for :session_instructors do |f| %>
<select multiple>
<% current_user.instructors.each do |instructor| %>
<option><%= instructor.name %></option>
<% end %>
</select>
<% end %>
<%= f.submit %>
<% end %>
Thank you so much!
This is something that seems ridiculously hard in Rails.
I think something like this might work:
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_forand just usingf.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: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_fieldis necessary. Also, you need to make sure each form element has a uniqueidfield. 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: