【发布时间】:2015-10-26 05:09:21
【问题描述】:
我试图在我的应用程序中表示用户之间的关系,其中一个用户可以有很多关注者并且可以关注其他用户。 我想要像 user.followers() 和 user.followed_by() 这样的东西 您能否详细告诉我如何使用 ActiveRecord 来表示?
谢谢。
【问题讨论】:
标签: ruby-on-rails ruby activerecord
我试图在我的应用程序中表示用户之间的关系,其中一个用户可以有很多关注者并且可以关注其他用户。 我想要像 user.followers() 和 user.followed_by() 这样的东西 您能否详细告诉我如何使用 ActiveRecord 来表示?
谢谢。
【问题讨论】:
标签: ruby-on-rails ruby activerecord
你需要两个模型,一个 Person 和一个 Follows
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
在你写的Followings类中对应
class Followings < ActiveRecord::Base
belongs_to :person
belongs_to :follower, :class_name => 'Person'
end
您可以根据自己的喜好使名称更清晰(我特别不喜欢Followings-name),但这应该可以帮助您入门。
【讨论】:
推特追随者模型与友谊模型的不同之处在于,您无需获得对方的许可即可关注他们。这里我设置了一个延迟加载,其中关系没有在 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]
【讨论】: