双向自引用关联 [英] Bidirectional self referential associations
问题描述
以Ryan Bates的asciicast为例:http://asciicasts.com/episodes/163-self-referential-association
Taking Ryan Bates' asciicast as an example: http://asciicasts.com/episodes/163-self-referential-association
他以两个用户关联结束
- :朋友
- :inverse_friends
鉴于用户不关心谁促成了友谊,您需要一个简单的用户关联
Given that a user would not care who instigated the friendship, you would want a User association that was simply
- :朋友
由两种关系组成.即用户发起的关系和用户朋友发起的关系.
that consisted of both relationships. i.e Relationships instigated by the user and relationships instigated by the user's friend.
那么如何实现这种双向自引用关联?
So how can you achieve this bidirectional self-referential association?
更新 - Josh Susser 在这里发表了一篇关于此的帖子:http://blog.hasmanythrough.com/2006/4/21/自我参照
UPDATE - Josh Susser has a post about this here: http://blog.hasmanythrough.com/2006/4/21/self-referential-through
然而,它仍然谈论 has_many :sources 和 has_many :sinks,而实际上应该有一个包含源和接收器的 has_many :nodes.
However, it still talks about has_many :sources and has_many :sinks when really there should be a has_many :nodes that includes both the sources and the sinks.
推荐答案
看看这是否适合您?
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
这是给定的数据库表模式
this is given a database table schema of
users
- id
- first_name
- etc...
friendships
- id
- person_id
- friend_id
这篇关于双向自引用关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!