Technology from the trenches

Ruby on Rails has_many :through NameError: uninitialized constant

Monday, March 10th, 2008

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