Collection_select - how to set selected options?

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

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

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

I also tried this:

<%= options_from_collection_for_select(Role.find(:all), :id, :name, :selected_value => @user.roles.collect {|r| r.id}) %>

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

Final result:

<% Role.find(:all).each do |r| %> "><%= r.name %> <% end %>

This worked for me. Thank you very much!

On Jan 11, 2:20 pm, Wes G. [email protected]