Technology from the trenches

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: ,

5 Responses to “Ruby on Rails has_many :through NameError: uninitialized constant”

  1. eirc Says:

    THANK YOU!!!!!!!

    it took me about an hour until i found your post…
    i would surely spend the whole day on this!!

  2. dave Says:

    OMG I <3 you.

  3. Fredrik Says:

    Thanks! Subtle indeed, and almost too obvious to notice.

  4. Edouard Says:

    Thanks! It just helped me out!

  5. dustycoder Says:

    Spent an hour on this… you just saved me another three days, surely.

Leave a Reply