Forum: Ruby on Rails collection_select not selecting default value

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.
Gu s. (Guest)
on 2009-01-15 03:37
Hi,

I'm trying to create a dropdown using collection_select. However, I cant
seem to get it to select the right option by default.

In my controller I have a setup like this:

@content = Content.new
@content.selection_id = 3
@selections = Selection.find(:all)

In my view I have:

<% form_for :content, @content, :url => { :action => 'create' } do |f|
%>
    <%= f.collection_select :selection, @selections, :id, :name %>
    <%= submit_tag 'Create' %>
<% end %>

Despite me specifying the default value in the controller,
collection_select doesnt seem to pick that up when rendering the html,
which defaults to the first option in the dropdown.

What idiot-simple thing am I missing? ;)

Thanks!

g.
Brandon K. (Guest)
on 2009-01-15 05:17
(Received via mailing list)
On Wed, Jan 14, 2009 at 8:37 PM, Gu stav
<removed_email_address@domain.invalid> wrote:
> @selections = Selection.find(:all)
>
> In my view I have:
>
> <% form_for :content, @content, :url => { :action => 'create' } do |f|
> %>
>    <%= f.collection_select :selection, @selections, :id, :name %>
>    <%= submit_tag 'Create' %>
> <% end %>

The first thing that sticks out is it should be :selection_id instead
of :selection.

> Despite me specifying the default value in the controller,
> collection_select doesnt seem to pick that up when rendering the html,
> which defaults to the first option in the dropdown.
>
> What idiot-simple thing am I missing? ;)

And if that doesn't fix it, then my only other suggestion would be to
make sure you have selection_id set as an integer in the database.
I've accidentally created a foreign key as a string before, which
works fine mostly, except when trying to do a select box and it's
comparing integers to strings.

Hope that helps.

-- Brandon
--------------------------------------------------------------------------------
Training by Collective Idea: Ruby on Rails training in a vacation
setting
http://training.collectiveidea.com – San Antonio, TX – Jan 20-23
Gu s. (Guest)
on 2009-01-15 06:18
> The first thing that sticks out is it should be :selection_id instead
> of :selection.

that fixes it. thanks a million!
This topic is locked and can not be replied to.