开发者

question about rails associations

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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜