我最近在尝试在 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。只是不太明白这一点。
谢谢