以 Ryan Bates 的 asciicast 为例:http://asciicasts.com/episodes/163-self-referential-association
他以两个 User 关联结束
鉴于用户不关心谁煽动了友谊,您需要一个简单的用户关联
由这两种关系组成。即由用户发起的关系和由用户的朋友发起的关系。
那么如何才能实现这种双向自我参照关联呢?
更新 - Josh Susser 在这里发表了一篇关于此的文章:http://blog.hasmanythrough.com/2006/4/21/self-referential-through
然而,它仍然谈论 has_many :sources 和 has_many :sinks ,而实际上应该有一个包含源和接收器的 has_many :nodes 。
看看这对你有用吗?
class User < ActiveRecord::Base
has_many :friendships, :foreign_key => "person_id", :class_name => "Friendship"
has_many :friends, :through => :friendships
def befriend(user)
# TODO: put in check that association does not exist
self.friends << user
user.friends << self
end
end
class Friendship < ActiveRecord::Base
belongs_to :person, :foreign_key => "person_id", :class_name => "User"
belongs_to :friend, :foreign_key => "friend_id", :class_name => "User"
end
# Usage
jack = User.find_by_first_name("Jack")
jill = User.find_by_first_name("Jill")
jack.befriend(jill)
jack.friends.each do |friend|
puts friend.first_name
end
# => Jill
jill.friends.each do |friend|
puts friend.first_name
end
# => Jack
这是给定的数据库表模式
users
- id
- first_name
- etc...
friendships
- id
- person_id
- friend_id
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)