Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I allow a user to select zero options from a multiple selection box in rails?

I have a settings model with a column options, and set it to serialize with serialize :options. In my view, I have a multiple selection box, using select("settings", "options", ['option1','option2','option3'], {}, :multiple => true) which works fine so long as the user selects at least one option. However, if they don't select any options, no options are submitted and so the options aren't updated.

How do I allow the user to select zero options from a multiple selection box in rails?

like image 332
Simon Avatar asked Jul 29 '10 15:07

Simon


3 Answers

That has nothing to do with rails: html form won't send such parameter to server if nothing is chosen in 'select' element. But you should be able to fix it in controller. Something like this

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

Not sure if there's more elegant solution.

like image 76
Nikita Rybak Avatar answered Oct 05 '22 06:10

Nikita Rybak


Add a hidden field after the select box, that posts an empty value to "settings[options]"

It's same trick that rails uses to make sure unchecked checkboxes get posted as false.

like image 44
Alex Bartlow Avatar answered Oct 05 '22 06:10

Alex Bartlow


I do not like assuming a value is empty if the attribute is not posted. It breaks the way Rails expects to update attributes, and it can present problems if you are using your controller actions also for APIs as well as HTML. My preferred way of handling this is by adding 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 realize this answer is not very timely, but I hope this will help someone with a similar question.

like image 32
Sean McCleary Avatar answered Oct 05 '22 06:10

Sean McCleary