如何使用ActiveRecord关联在rails中指定模型之间的多个关系

假设有两种模式:用户和post,我想跟踪谁阅读了哪个post,谁写了哪个post,哪个用户喜欢哪些post等等。然后我想出了以下解决方案:

class User  :writings has_many :readings has_many :posts, :through => :readings #.. end class Post  :writings #... end 

并建立中间模型 – 写作,阅读。 这是有效的,但最后我发现当我写这篇文章时

 @user.posts #... 

返回的数组包含写作和读数的内务处理信息。 我怎么解决这个问题。

你想要这样的东西:

 class User < ActiveRecord::Base has_many :writings has_many :posts, :through => :writings has_many :readings has_many :read_posts, :through => :readings, :class_name => "Post" #.. end 

通过给予关联名称以外的其他内容:post您可以单独引用每个名称。 现在…

 @user.posts # => posts that a user has written via writings @user.read_posts # => posts that a user has read via readings