Collection_select option ":selected" not working

The “:selected” statement is not working. Ideas why? Similar
experiences?

<%= start_form_tag :action => ‘dummy’ %>
<% @teams = Team.find(:all) %>
Team

<%= collection_select(“team”, “id”, @teams, :id, :name, {
:include_blank => true, :selected => @teams[5].id }) %>
<%= end_form_tag %>

It is generating the follwing code:

Team
Baltimore Buffalo Cincinnati Cleveland Denver Houston Indianapolis Jacksonville Kansas City

… etc

Oddly, the option :for include_blank is working, while the selected
right next to it is not.

Please help.


(**********************************************************

Try this:

<%= collection_select(“team”, “id”, @teams, :id, :name,
{:include_blank => true}, {:selected => @teams[5].id }) %>

I think :selected belongs in html_options instead of options:
collection_select(object, method, collection, value_method,
text_method, options = {}, html_options = {})

Aaron

Aaron’s solution won’t work, unfortunately. And although there is a way
to pre-select an item by setting

@team.id = @teams[5].id

for a select list like

select(:team, :id,
Team.find_all.collect {|p| [ p.name, p.id ] },
{ :include_blank => true })

that possibility is missing for collection_select.

But for your described needs the select list should work perfectly, so
you don’t have to bother about shortcomings of collection_select lists
:stuck_out_tongue:

The best way to pre-select an item in a collection_select list is – as
far as I know – using a separate options_from_collection_for_select for
which you can define a selected_value as last parameter.
The downside, however, is that such a options list is working with
select_tag only. So you have to handle the return value a bit
differently in your controller (which should be no problem in most
cases).
Another drawback is the missing possibility of defining :include_blank
for neither select_tag nor options_from_collection_for_select (yet). But
you can add an empty item to top easily before passing the values hash
to the form helper.
A quick outline of this solution:

select_tag(:team_id,
options_from_collection_for_select(@teams, :id, :name,
@teams[5].id))

…untested.

This might help you out: http://shiningthrough.co.uk/blog/show/6

On Nov 21 2006, 10:52 am, Andre Pankratz <rails-mailing-l…@andreas-

Amendment: The collection_select bug has been fixed, eventually.

“…This is outdated. You can just use collection_select. If it is
already set, it will select the correct option for you.”
http://wiki.rubyonrails.org/rails/pages/HowtoUseFormOptionHelpers

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs