像Twitter粉丝这样的关系/在ActiveRecord中跟随

我试图在我的应用程序中表示用户之间的关系,其中用户可以拥有许多关注者并且可以关注其他用户。 我想有像user.followers()和user.followed_by()这样的东西你能告诉我如何使用ActiveRecord来表示这个吗?

谢谢。

你需要两个模型,一个人和一个跟随

rails generate model Person name:string rails generate model Followings person_id:integer follower_id:integer blocked:boolean 

以及模型中的以下代码

 class Person < ActiveRecord::Base has_many :followers, :class_name => 'Followings', :foreign_key => 'person_id' has_many :following, :class_name => 'Followings', :foreign_key => 'follower_id' end 

并在你写的关注课中对应

 class Followings < ActiveRecord::Base belongs_to :person belongs_to :follower, :class_name => 'Person' end 

你可以根据自己的喜好使名字更清晰(我特别不喜欢Followings -name),但这应该让你开始。

Twitter粉丝模型与友谊模型的不同之处在于,您不需要该人员的许可即可遵循它们。 在这里,我设置了一个延迟加载,其中关系未在person对象中完全定义。

/app/models/person.rb

  def followers Followership.where(:leader_id=>self.id).not_blocked end def following Followership.where(:follower_id=>:self.id).not_blocked end has_many :followers, :class_name=>'Followership' has_many :followed_by, :class_name=>'Followership' 

/app/models/followership.rb

  belongs_to :leader, :class_name=>'Person' belongs_to :follower, :class_name=>'Person' #leader_id integer #follower_id integer #blocked boolean scope :not_blocked, :conditions => ['blocked = ?', false]