Forum: Ruby on Rails habtm and options_from_collection_for_select [1.0.0]

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.
Paul M. (Guest)
on 2006-04-04 22:06
(Received via mailing list)
I ran into a problem using options_from_collection_for_select :

ActiveRecord::AssociationTypeMismatch (Topic expected, got String):
     /usr/local/lib/ruby/gems/1.8/gems/activerecord-1.13.2/lib/
active_record/associations/association_collection.rb:128:in
`raise_on_type_mismatch'
     /usr/local/lib/ruby/gems/1.8/gems/activerecord-1.13.2/lib/
active_record/associations/association_collection.rb:114:in `replace'
     /usr/local/lib/ruby/gems/1.8/gems/activerecord-1.13.2/lib/
active_record/associations/association_collection.rb:114:in `replace'
     /usr/local/lib/ruby/gems/1.8/gems/activerecord-1.13.2/lib/
active_record/associations.rb:770:in `topics='

My models:

class Company < ActiveRecord::Base
   has_and_belongs_to_many :topics
end

class Topic < ActiveRecord::Base
   has_and_belongs_to_many :companies
end

And the form elements:

<select id="company_topics" name="company[topics][]"
multiple="multiple">
   <%= options_from_collection_for_select(Topic.find_all, "id",
"name") %>
</select>

I tested using the connsole, and things work as expected.

Any help greatly appreciated !

Paul
Chris H. (Guest)
on 2006-04-04 22:58
(Received via mailing list)
i don't think this is an error related to
options_from_collection_for_select.

the key in the error is:

/usr/local/lib/ruby/gems/1.8/gems/activerecord-1.13.2/lib/active_record/associations.rb:770:in
`topics='

it's clearly an association error related to topics=

if you look at the docs for habtm:

collection=objects - replaces the collections content by deleting and
adding
objects as appropriate.

so my guess in one of you're actions you trying to set the
company.topics to
a string rather than a Topic object.

a console test would confirm the same error

company = Company.find(:first)
test_params[:company][:topics] = ["1", "2", "3"]
company.topics=test_params[:company][:topics]



Chris
This topic is locked and can not be replied to.