I’ve been stumped on this for a few days and I’m not sure if it’s an error on my end or an actual bug. I have a system where I have workshops and users. Workshops have students, presenters, and troubleshooters. I wanted to represent this simply by using has_many :through with :source.
Workshop
has_many :presenters, :through =>:presenterships, :source=>:user
This actually works great. However, I am running into a really interesting problem when doing the assignments:
This works:
@u = User.find 1
@w = Workshop.find 1
@w.presenterships.create :user_id => [u.id](http://u.id)
But this fails:
@u = User.find 1
@w = Workshop.find 1
@w.presenterships.create :user => u
Notice t he assignment of the object instead of the id field.
The trickiest part of all this is that I get a really strange error message:
ActiveRecord::AssociationTypeMismatch: User expected, got User
from c:/ruby/lib/ruby/gems/1.8/gems/activerecord-1.15.2/lib/active_recor
d/associations/association_proxy.rb:148:in raise_on_type_mismatch' from c:/ruby/lib/ruby/gems/1.8/gems/activerecord-1.15.2 /lib/active_recor d/associations/belongs_to_association.rb:22:in
replace’
from c:/ruby/lib/ruby/gems/1.8/gems/activerecord-1.15.2/lib/active_recor
d/associations.rb:900:in user=' from c:/ruby/lib/ruby/gems/1.8/gems/activerecord- 1.15.2/lib/active_recor d/base.rb:1673:in
attributes=’
from c:/ruby/lib/ruby/gems/1.8/gems/activerecord-1.15.2/lib/active_recor
d/base.rb:1672:in attributes=' from c:/ruby/lib/ruby/gems/1.8/gems/activerecord- 1.15.2/lib/active_recor d/base.rb:1506:in
initialize_without_callbacks’
from c:/ruby/lib/ruby/gems/1.8/gems/activerecord-1.15.2/lib/active_recor
d/callbacks.rb:225:in initialize' from c:/ruby/lib/ruby/gems/1.8/gems/activerecord- 1.15.2/lib/active_recor d/associations/has_many_association.rb:13:in
build’
from c:/ruby/lib/ruby/gems/1.8/gems/activerecord-1.15.2/lib/active_recor
d/associations/association_collection.rb:93:in `create’
from (irb):5
I’ve pasted my classes below. The migrations are standard (presenterships just has its own id and the two foreign keys). I’d appreciate any insight. I have a workaround but I was just wondering if this was a bug or a limitation.
class Workshop < ActiveRecord::Base
has_many :presenterships
has_many :presenters, :through =>:presenterships, :source=>:user
end
class Presentership < ActiveRecord::Base
belongs_to :workshop
belongs_to :user
end
class User
# lots of validations
end