views:

33

answers:

2

consider this code

class User < ActiveRecord::Base
  has_many :views
  has_many :posts, :through => :views, :uniq => true

  has_many :favorites
  has_many :posts, :through => :favorites, :uniq => true

  has_many :votes
  has_many :posts, :through => :votes, :uniq => true
end

# controller code

user = User.find(3)
posts = user.posts # ??

that said i have established three relationships between posts and users, through different way. But what about the last line??? how can I tell rails that I want to get the posts through views or favorites.

+1  A: 

You have to give the associations different names. The 2nd and 3rd has_many :posts just overwrite the previous ones. You will need something like has_many :view_posts, has_many :favorite_posts, etc.

pjb3
+4  A: 

You can give each association a different name, but point it at the same model using the :class_name option. Like so:

class User < ActiveRecord::Base
  has_many :views
  has_many :view_posts, :through => :views, :class_name => 'Post', :uniq => true, 

  has_many :favorites
  has_many :favorite_posts, :through => :favorites, :class_name => 'Post', :uniq => true

  has_many :votes
  has_many :vote_posts, :through => :votes, :class_name => 'Post', :uniq => true
end

# Then...
User.find(3).favorite_posts

You may also find named_scope useful.

Jordan