Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord::HasManyThroughAssociationNotFoundError in UserController#welcome

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

like image 745
scott Avatar asked Jan 31 '10 00:01

scott


1 Answers

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
like image 170
zetetic Avatar answered Oct 21 '22 14:10

zetetic