Forum: Ruby on Rails collection_select - how to set selected options?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Wes G. (Guest)
on 2007-01-11 22:48
In a form, I am trying to use collection_select with multiple=true, like
so:

collection_select(:user, :roles, Role.find(:all), 'id', 'name', {},
:multiple => true) %>

My multiple select box is rendered fine, but...

I want the select to have the current role options for the user
pre-selected when I view it.  So if there are five roles in the database
and this user has 3 of them, I would expect to see 3 of the options
selected (each option tag would have selected="selected" attribute set).

Is there a way to do this?  It seems like the :selected option on the
collection_select and options_from_collection_for_select form helpers
only allow you to specify one value.  Is this correct?

Is there a way to specify a test for each member of the collection that
will return true when the option should be selected?

Thanks,
Wes
Wes G. (Guest)
on 2007-01-11 23:12
I tried this:

collection_select(:user, :roles, Role.find(:all), 'id', 'name',
{:selected => @user.roles.collect {|r| r.id}}, :multiple => true)

and I believe that setting the :selected option to this array would take
care of pre-selecting the values, but it doesn't.

I'm actually questioning whether or not I should be using
collection_select anyway - wouldn't a regular select tag do fine here?

Thanks,
Wes
Wes G. (Guest)
on 2007-01-11 23:20
This seems to work:

<%= select(:user,
           :roles,
           Role.find(:all).collect {|r| [r.name, r.id]},
           {:selected => @user.roles.collect {|r| r.id}},
           :multiple => true) %>

What is the purpose of collection_select?

WG
Wes G. (Guest)
on 2007-01-12 00:00
I also tried this:

<select id="user_roles" name="roles[]" multiple="multiple">
  <%= options_from_collection_for_select(Role.find(:all), :id, :name,
:selected_value => @user.roles.collect {|r| r.id}) %>
</select>

I've read the code behind options_from_collection_for_select and I can't
figure out why the :selected_value setting isn't working.

I guess I'll just do it by hand.

Wes
Wes G. (Guest)
on 2007-01-12 00:09
Final result:

<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>
DyingToLearn (Guest)
on 2007-03-25 03:59
(Received via mailing list)
This worked for me. Thank you very much!

On Jan 11, 2:20 pm, Wes G. <removed_email_address@domain.invalid>
This topic is locked and can not be replied to.