Forum: Ruby on Rails collection_select - why doesn't it work?

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Fc582698581884352e745d1d4c64699d?d=identicon&s=25 Joshua Muheim (josh)
on 2007-03-20 21:22
Hi all

I guess this is quite a newbie question, but I'm just stuck here and
don't know why.

<%= form.collection_select :origin_country, Country.find(:all), :id,
:name %>

gives me a select list with name="member[origin_country]". When
submitting the form the following error is shown:

Country expected, got String

When I try

<%= form.collection_select :origin_country_id, Country.find(:all), :id,
:name %>

I get the error

undefined method `origin_country_id' for #<Member:0x23f52e8>

So I try it with

<%= :origin_country, Country.find(:all).map{|obj| [,]} %>

but again the same "Country expected, got String" error.

As far as I know Rails expects a select list with a name
"member[origin_country_id]" or something like that?

My models look like that:

class Member < ActiveRecord::Base
  belongs_to :origin_country,
    :class_name => 'Country'

class Country < ActiveRecord::Base
  has_many  :originating_members,
    :class_name => 'Member'

And the foreign key column in the members table is called "country_id".

So where's the mistake? Thanks a lot for help. :-)
B1b1d33e0655e841d4fd8467359c58d0?d=identicon&s=25 Yossef Mendelssohn (Guest)
on 2007-03-20 23:00
(Received via mailing list)
It's a pretty simple mistake, but it's confused by your unconventional
association.  Normally, you would assign to the association name plus
'_id', but that doesn't match the class.  And just like the error
says, you can't assign a string (the Country object's ID) to the
association (because it wants a Country object).  Try a select on
country_id instead of origin_country or origin_country_id.

By the way, I prefer to fully qualify any association that doesn't use

belongs_to :origin_country, :class_name => 'Country', :foreign_key
=> :country_id

Otherwise, it can be confusing to know whether the foreign key depends
on the association name or class name (and I believe it has switched
or will switch or something, but I could be wrong about that).

Fc582698581884352e745d1d4c64699d?d=identicon&s=25 Joshua Muheim (josh)
on 2007-03-20 23:20
Thanks a lot, very helpful!
This topic is locked and can not be replied to.