Friday September 25, 2009
If I could just get the stupid thing to build
Rails: Setting selected options in a ListBox
I really struggled with this yesterday. I'm writing a Rails CRUD app and when creating a new entry one of the fields presented is a ListBox that allows multiple selections. That was straightforward, but i had problems when editing an existing entry. What didn't want to work for me are the recognised methods for having the current items for the entry being edited be selected in the ListBox.
The way that I understand that it should work is like this:
collection_select(:user, :group_ids, Group.find(:all), :id, :name,{},{:multiple=>,:name=>'user[group_ids][]'})
But needless to say it didn't. In the end I found this from Wes Gamble (weyus on Ruby Forum). It's a bit more DIY but it works a treat. I'm reproducing it here in case it's useful to anyone else (thanks Wes!)
<select id="user_roles" name="roles[]" multiple="multiple">
<% Role.find(:all).each do |r| %>
<option value="<%= r.id %>" <%= @user.roles.include?(r) ?
"selected=\"selected\"" : '' %>"><%= r.name %></option>
<% end %>
</select>
Posted at 12:05PM Sep 25, 2009 by MandyWaite in Ruby (on Rails) | Comments[0]