Collection_select - why doesn't it work?

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

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

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’
end

class Country < ActiveRecord::Base
has_many :originating_members,
:class_name => ‘Member’
end

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

So where’s the mistake? Thanks a lot for help. :slight_smile:
Joshua

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
defaults.

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).


-yossef

Thanks a lot, very helpful!