the relevant part of the new form looks like this:
<%= f.fields_for :event_artists do |fea| %>
<%= fea.collection_select :artist_id, Artist.all, "id", "name", {include_blank: true}, {multiple: true} %>
<% end %>
on the log, you can see that the first item of the array is always blank, even if I didn't select the blank field
"event_artists_attributes"=>{"0"=>{"artist_id"=>["", "2", "5"]}}}
is there a way to fix this? perhaps, make it so that if the blank field is selected, then no actual event_artists can be selected in that case, and vice versa?
The empty artist_id
is important. On another form, you may have omitted the artist select altogether, in which case, the artists
association should not be affected.
If the artist select is included, and you de-select all artists, the artists need to be removed from the artists
association. Normal HTML behavior would not include the artist_id
parameter in the PUT at all when nothing is selected. Your controller in that case would think that you do not want to modify the artists
association at all.
To solve this, the collection_select
includes a hidden field with a blank value to let the controller know that the form intends to alter the artists
association. If no artists have been selected, that blank element in the array will ensure all artists are removed from the association.