Ruby on Rails has_many :through NameError: uninitialized constant
Are you getting the error message, “NameError: uninitialized constant” from Rails? I was too, and the solution was a simple change to my models. I have two models with “has_many :through”, for my “events” and “people” tables:
class Event < ActiveRecord::Base
has_many :memberships
has_many :people, :through => :memberships
end
And:
class Person < ActiveRecord::Base
has_many :memberships
has_many :events, :through => :memberships
end
The join table is “memberships”, and the problem was in its model:
class Membership < ActiveRecord::Base
validates_presence_of :event_id, :person_id
belongs_to :people
belongs_to :events
end
It is a subtle problem; the model looks OK. However, the “belongs_to” statements should point to the models of the other two tables, not the names of the tables themselves. The models are Event and Person, so the join model should be:
class Membership < ActiveRecord::Base
validates_presence_of :event_id, :person_id
belongs_to :person
belongs_to :event
end
It took me a while to see the problem because it is so subtle, even though the answer is everywhere. Hopefully spelling it out here will help someone.
Tags: has_many-:through, Ruby on Rails

March 31st, 2008 at 6:56 pm
THANK YOU!!!!!!!
it took me about an hour until i found your post…
i would surely spend the whole day on this!!
May 8th, 2008 at 9:58 am
OMG I <3 you.
October 2nd, 2008 at 7:07 am
Thanks! Subtle indeed, and almost too obvious to notice.
October 7th, 2008 at 4:17 am
Thanks! It just helped me out!