Posted by & filed under Developer Blog.

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.