Ruby on rails 关系,如Twitter追随者/在ActiveRecord中跟踪

Ruby on rails 关系,如Twitter追随者/在ActiveRecord中跟踪,ruby-on-rails,ruby,activerecord,Ruby On Rails,Ruby,Activerecord,我试图在我的应用程序中表示用户之间的关系,其中一个用户可以有许多追随者,也可以跟随其他用户。 我想要像user.followers()和user.u后面跟() 你能详细地告诉我如何用ActiveRecord来表示这个吗 谢谢 推特关注者模式与友谊模式的不同之处在于,你不需要获得关注者的许可。在这里,我设置了一个延迟加载,其中person对象中没有完全定义关系 /app/models/person.rb def followers Followership.where(:leader_

我试图在我的应用程序中表示用户之间的关系,其中一个用户可以有许多追随者,也可以跟随其他用户。 我想要像user.followers()和user.u后面跟() 你能详细地告诉我如何用ActiveRecord来表示这个吗


谢谢

推特关注者模式与友谊模式的不同之处在于,你不需要获得关注者的许可。在这里,我设置了一个延迟加载,其中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] 

你需要两个模特,一个人和一个追随者

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-Person'followers',:foreign\u key=>'person\u id'
有多个:following,:class\u name=>'Followings',:foreign\u key=>'follower\u id'
结束
并在你写的以下课程中对应

class Followings < ActiveRecord::Base
  belongs_to :person
  belongs_to :follower, :class_name => 'Person'
end
class follows“Person”
结束
您可以根据自己的喜好使名称更清晰(我尤其不喜欢下面的
-name),但这应该可以让您开始