Graph Edges Rails

2019-07-16 13:19发布

问题:

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").