How to allow the user to select zero options from several selection fields in rails?

I have a settings model with the options column, and set it to serialize using serialize :options . In my opinion, I have several selection fields using select("settings", "options", ['option1','option2','option3'], {}, :multiple => true) , which works fine, while the user selects at least one parameter. However, if they do not select any options, the parameters are not displayed, so the parameters are not updated.

How do I allow a user to select null options from multiple selection fields in rails?

+4
source share
4 answers

I do not like if the value is empty, if the attribute is not sent. This breaks the way Rails expects attribute updates, and can be a problem if you use controller actions for the API as well as for the HTML. My preferred way to handle this is to add a hidden input field before multiselects.

 <input type="hidden" value="" name="parent_model[my_attribute_ids][]"> 

If you use jQuery, you can automate the addition of these hidden input fields:

 $('select[multiple="multiple"]').each(function(i){ $(this).before('<input type="hidden" name="'+this.name+'" value="" />') }); 

I understand that this answer is not very timely, but I hope this helps someone with a similar question.

+2
source

This has nothing to do with rails: the html form will not send such a parameter to the server if nothing is selected in the 'select' element. But you should be able to fix this in the controller. Something like that

 if params[:settings] == nil params[:settings] = []; end 

Not sure if there is a more elegant solution.

+4
source

Add a hidden field after the selection field that sends an empty value to "settings [options]"

The same trick that rails use to make sure flags are flagged.

+4
source

You can specify the "No" option.

Example from: http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html

 select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, {:include_blank => 'None'}, {:multiple => true}) 

Would become

 <select name="post[person_id]" multiple="multiple"> <option value="">None</option> <option value="1">David</option> <option value="2" selected="selected">Sam</option> <option value="3">Tobias</option> </select> 
+1
source

All Articles