I'm new to Rails and I'm running in circles trying to implement a Select2 input with multiple selections. I've read the solutions on StackOverflow and none of them helped me, which typically means I'm doing something unusually wrong.
When I'm submitting my form it sends my federation_list parameter multiple times with different values (in headers):
event[federation_list]: WDC
event[federation_list]: WDSF
I need all of the values in one Federation parameter seperated by a comma, that I can then split in my controller.
I've tried adding name: "federation_list[]" as it says in the Select2 documentation, but my form_with overwrites it so it loses the brackets.
Updated! I figured out the solution and this is my working code:
select2_initializer.js
$( document ).on('turbolinks:load', function() {
$( "#event_federation_list" ).select2({
theme: "bootstrap",
multiple: true,
placeholder: 'Select Federation(s)',
width: 'style'
}).val('').trigger('change');
});
_form.html.erb
<div class="form-group">
<%= form.label :federation_list, value: "Federations", class: "form-label" %>
<%= form.select :federation_list, options_from_collection_for_select(Federation.all, :id, :name, {:selected => @event.federations.map(&:id)}), {}, { multiple: true } %>
</div>
The :selected makes the selected options appear when the user edits the form.
event.rb
def federation_list
self.federations.map(&:name).join(', ')
end
def federation_list=(names)
self.federations = names.split(',').map do |n|
Federation.where(name: n.strip).first_or_create!
end
end
If it is relevant information my Event has_many: Federations, through: Event_Federations.
I ended up going with Selectize instead of Select2, but the solution still holds true for Select2.
And then I wrote this piece of code in my event.rb:
def federation_list
self.federations.map(&:name).join(', ')
end
def federation_list=(ids)
self.federations = ids.reject!(&:empty?).map do |id|
Federation.where(id: id).first
# Use .first_or_create! to let the user add new objects
end
end
I used SteveTurczyns advise and added federation_list: [] in my strong params.
And that works!
not sure if this is your only problem but a definite problem is that strong parameters require that you explicitly specify if a model parameter is an array.
Instead of
You should have