views:

41

answers:

3

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?

+2  A: 

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.

Nikita Rybak
`params[:settings] ||= []`
theIV
+2  A: 

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.

Alex Bartlow
+1  A: 

You could provide a "None" 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>
macek
That makes for an odd interface - what does it mean if they select None and David? And it still does unexpected things if they don't select anything.
Simon
What "unexpected" things?
macek
if they don't select anything then nothing happens - instead of clearing the association as it should.
Simon