Graph Edges Rails

女生的网名这么多〃 提交于 2019-12-11 01:16:34

问题


I found this recently when trying to do bidirectional relationships in 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

But I just don't quite understand how it works. Can anyone helps explain to me. It looks like a double belongs_to. Just not quite understanding this.

Thanks


回答1:


  1. I'm a user
  2. I have friends
  3. My friends are also users

The way to model this using a graph (http://en.wikipedia.org/wiki/Graph_%28mathematics%29) is with

  • nodes that represent users/friends
  • edges that represent friendship links

So yes: in databases terms, "users belong to users" : my friends are also users. But in addition, friendship is bi-directional: if we're friends that means, I'm your friend AND you're my friend.

Also, using a separate model to store edges/relationships allows you potentially store additional information about the friendship (e.g. "friends since").



来源:https://stackoverflow.com/questions/836800/graph-edges-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!