【问题标题】:Bidirectional self referential associations双向自引用关联
【发布时间】:2010-05-27 18:14:32
【问题描述】:

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

他以用户的两个关联结束

  • :朋友
  • :inverse_friends

鉴于用户不会关心谁促成了友谊,你会想要一个简单的用户关联

  • :朋友

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

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

更新 - Josh Susser 在这里有一篇关于此的帖子: http://blog.hasmanythrough.com/2006/4/21/self-referential-through

然而,它仍然在讨论 has_many :sources 和 has_many :sinks,而实际上应该有一个包含源和接收器的 has_many :nodes。

【问题讨论】:

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


    【解决方案1】:

    看看这对你有用吗?

    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
    

    【讨论】:

    • 谢谢!就像更新一样。我用了你这里描述的方法,效果很好。
    猜你喜欢
    • 2012-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多