Ruby on rails 如何使用:through设置定向多对多自联接?

Ruby on rails 如何使用:through设置定向多对多自联接?,ruby-on-rails,foreign-keys,ruby-on-rails-3.2,relationship,Ruby On Rails,Foreign Keys,Ruby On Rails 3.2,Relationship,我正在为一个客户设置一个Rails项目,他们希望用户(一个模型)能够相互跟踪(就像在Twitter中一样)。他们还希望能够跟踪一个用户何时开始跟踪另一个用户 因为我需要跟踪创建日期,我想,有很多X,:through=>Y关系将是一种方式,因此Y将跟踪创建日期 我已设置了以下模型: class Follow < ActiveRecord::Base attr_accessible :actor_id, :observer_id, :follower, :followee attr_r

我正在为一个客户设置一个Rails项目,他们希望用户(一个模型)能够相互跟踪(就像在Twitter中一样)。他们还希望能够跟踪一个用户何时开始跟踪另一个用户

因为我需要跟踪创建日期,我想,
有很多X,:through=>Y
关系将是一种方式,因此Y将跟踪创建日期

我已设置了以下模型:

class Follow < ActiveRecord::Base
  attr_accessible :actor_id, :observer_id, :follower, :followee
  attr_readonly :actor_id, :observer_id, :follower, :followee

  belongs_to :follower, :class_name => 'User', :foreign_key => :observer_id
  belongs_to :followee, :class_name => 'User', :foreign_key => :actor_id

  validates_presence_of :follower, :followee
  validates_uniqueness_of :actor_id, :scope => :observer_id
end
而且它大部分都在工作。除了
:followers
工作正常,但是
user.followers
正在做一些奇怪的事情。它似乎在检查用户是否在跟踪某人,如果他们是
user。followers
返回一个仅包含user的数组;如果不是,则返回一个空数组


有人有什么建议吗?

看起来这是正确的格式:

has_many :follows, :foreign_key => :observer_id
has_many :followed, :class_name => 'Follow', :foreign_key => :actor_id
has_many :following, :class_name => 'User', :through => :follows, :source => :followee, :uniq => true
has_many :followers, :class_name => 'User', :through => :followed, :source => :follower, :uniq => true

对于Rails新手来说,
:uniq=>true
很重要(正如我在做这件事时发现的那样),因为它可以防止
返回多个X、:到=>Y
关系(也就是说,如果没有它,您可能会得到多个不同的对象,每个对象都有自己的对象ID,都引用同一条记录/行).

这里有一个类似的问题,它引用了该模式的教程和gem。也许想看看。你为什么不试试呢?@Lichtamberg:我试过几种不同的方法。然而,我真正想知道的是,不仅要知道正确答案是什么,还要通过更好地理解不同关键字的作用来理解为什么它是正确答案。
has_many :follows, :foreign_key => :observer_id
has_many :followed, :class_name => 'Follow', :foreign_key => :actor_id
has_many :following, :class_name => 'User', :through => :follows, :source => :followee, :uniq => true
has_many :followers, :class_name => 'User', :through => :followed, :source => :follower, :uniq => true