【问题标题】:Graph Edges Rails图形边缘 Rails
【发布时间】:2009-05-07 20:13:30
【问题描述】:

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

class Befriending < ActiveRecord::Base
  belongs_to :initiator, :class_name => :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 < ActiveRecord::Base
  has_many :befriending_edges
  has_many :friends, :through => :befriending_edges, :source => :user
  has_many :befriendings, :through => :befriending_edges, :source => :befriending
end

但我只是不太明白它是如何工作的。谁能帮我解释一下。它看起来像一个双重的belongs_to。只是不太明白这一点。

谢谢

【问题讨论】:

    标签: ruby-on-rails relational


    【解决方案1】:
    1. 我是用户
    2. 我有朋友
    3. 我的朋友也是用户

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

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

    所以是的:用数据库术语来说,“用户属于用户”:我的朋友也是用户。但此外,友谊是双向的:如果我们是朋友,这意味着我是你的朋友并且你是我的朋友。

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

    【讨论】:

      猜你喜欢
      • 2016-10-02
      • 2022-09-28
      • 1970-01-01
      • 1970-01-01
      • 2012-02-28
      • 1970-01-01
      • 2012-10-28
      相关资源
      最近更新 更多