Best Way to do Multiple Select Combo Boxes in Rails

After much trial and error, and frustration, I have finally come up with what I believe is the best possible way to do multiple select combo boxes in Rails. It’s not so much that there aren’t examples on the web, it’s just that every example is so different. I’ve used what I feel is the best from each example and created this example.

First, it’s best that the options are in an array somewhere. In this example, we’ll assume that all states are set in an array on the application.rb and the array is named $states

In the _form, or wherever your form is, do the following:

<% if @model_name and @model_name.states
 
@states_selected = @model_name.states.collect
 
end %>
 
<label for="model_name_states">State</label><br/>
 
<%= select_tag 'model_name[states][]', options_for_select($states, @states_selected), { :multiple => true, :size =>5, :id => "model_name_states" } %></p>

This will not only dynamically create your select field with each option, but it will make it so that if someone leaves off a required field the same selected states will be selected on the edit screen!

See the Rails documentation for options_for_select to customize it even further. Obviously you can leave off the :multiple and :size to make it a single select with similar results, but it’s better to use select instead of select_tag for single select combo boxes.

4 Responses  |  add yours »

4 Responses to “Best Way to do Multiple Select Combo Boxes in Rails”

  1. Herb says:

    You should encompass that select tag with the if statement, otherwise you get nil.inject errors when @states_selected is called after the initial check. Helped me out though.

  2. Thomas says:

    Nice article. There is another way for multiselect (for has_many and habtm relationships) though – showing two select boxes, one for all available options and one for the selected options, and the opportunity to move options from one select box to the other. I call this SwapSelect and it is described (incl. download) here:
    http://trendwork.kmf.de/175

  3. Kiran says:

    Nice article.It’s really useful.

  4. Anil says:

    You can try the following, it works for me:
    “multiple”, :size => 5 ) %>

Leave a Reply

(if you want a pic to show with your comment, go get a gravatar!)

Search