图边缘轨道

我最近在尝试在rails中建立双向关系时发现了这一点( http://www.dweebd.com/sql/modeling-bidirectional-graph-edges-in-rails/ )

class Befriending  :User belongs_to :recipient, :class_name => :User after_create do |b| BefriendingEdge.create!(:user => b.initiator, :befriending => b) BefriendingEdge.create!(:user => b.recipient, :befriending => b) end end class BefriendingEdge < ActiveRecord::Base belongs_to :user belongs_to :befriending end class User  :befriending_edges, :source => :user has_many :befriendings, :through => :befriending_edges, :source => :befriending end 

但我只是不太明白它是如何工作的。 任何人都可以帮我解释一下。 它看起来像一个double belongs_to。 只是不太了解这一点。

谢谢

  1. 我是用户
  2. 我有朋友
  3. 我的朋友也是用户

使用图形(http://en.wikipedia.org/wiki/Graph_%28mathematics%29)对此进行建模的方法是

  • 表示用户/朋友的节点
  • 代表友谊链接的边缘

所以是的:在数据库方面,“用户属于用户”:我的朋友也是用户。 但此外,友谊是双向的:如果我们是朋友意味着,我是你的朋友而你是我的朋友。

此外,使用单独的模型来存储边缘/关系可以让您潜在地存储有关友谊的其他信息(例如“以后的朋友”)。