ActiveRecord::HasManyThroughAssociationNotFoundError in UserController#welcome

scott picture scott · Jan 31, 2010 · Viewed 7.8k times · Source

I have a many to many relationship in rails. All database tables are named accordingly and appropriately. All model files are plural and use underscore to seperate words. All naming comventions are followed by ruby and rails standards. I'm using has many through in my models like this:

has_many :users, :through => :users_posts #Post model
has_many :posts, :through => :users_posts #User model
belongs_to :users #UsersSource model
belongs_to :posts #UsersSource model

What else could this error be from?

ActiveRecord::HasManyThroughAssociationNotFoundError in UsersController#welcome Could not find the association :users_posts in model Post

Answer

zetetic picture zetetic · Jan 31, 2010

You need to define the join model as a separate association when using has_many :through:

class Post < ActiveRecord::Base
  has_many :user_posts
  has_many :users, :through => :user_posts
end

class User < ActiveRecord::Base
  has_many :user_posts
  has_many :posts, :through => :user_posts
end

class UserPost < ActiveRecord::Base
  belongs_to :user # foreign_key is user_id
  belongs_to :post # foreign_key is post_id
end

This works best when you need to keep data that pertains to the join model itself, or if you want to perform validations on the join separate from the other two models.

If you just want a simple join table, it's easier to use the old HABTM syntax:

class User < ActiveRecord::Base
  has_and_belongs_to_many :posts
end

class Post < ActiveRecord::Base
  has_and_belongs_to_many :users
end