双向自引用关联

时间:2010-05-27 18:14:33

标签: ruby-on-rails bidirectional self-reference

以Ryan Bates的asciicast为例: http://asciicasts.com/episodes/163-self-referential-association

他以User

的两个关联结束
  • :朋友
  • :inverse_friends

鉴于用户不关心是谁煽动友谊,你会想要一个简单的用户关联

  • :朋友

由两种关系组成。即用户发起的关系和用户朋友发起的关系。

那么如何实现这种双向自引用关联?

更新 - Josh Susser在此发表了一篇文章: http://blog.hasmanythrough.com/2006/4/21/self-referential-through

然而,它仍然讨论has_many:sources和has_many:sink真的应该有一个has_many:包含源和接收器的节点。

1 个答案:

答案 0 :(得分:8)

看看这对你有用吗?

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