I am going to re-ask a question that has been asked a few times in the past. What is the best way to represent an undirected self-referential many to many relationship. Trivial examples of this include an edge in an undirected graph, or a mutual friendship. Alice is a person Bob is a person Alice and Bob are friends of each other We have a whole bunch of extra information about their friendship (when it started, who introduced them, where they met, etc.) We want to query "Are Bob and Alice friends?", "Who are Bob's friends?", "Who are the people that introduce Bob to friends?" etc. We could represent this as a has_many :through relationship, with a friendship_information database (containing extra information), and a friendship database with two entries in the database per friendship (<Bob, Alice> and <Alice, Bob>). But that seems inefficient. Is there a better way to do this? Alternatively, is there a way to merge 2 lists into a single has_many? Like this: has_many :initiated_friendships, :foreign_key =>'befriender_id', :class_name => 'Friendship', :dependent => :destroy has_many :received_friendships, :foreign_key =>'befriendee_id', :class_name => 'Friendship', :dependent => :destroy has_many :friends, :through=>union (:received_friendships,:initiated_friendships)
on 2008-11-20 09:03
on 2008-11-28 01:18
on 2008-11-28 03:42
Ewout Kleinsmann wrote: > Bump! Unbump! Just use the has_many :through option, and build the intermediate table by hand. There's nothing "inefficient" about it; you just have to keep tuning the Model objects until they express your business rules, like any other model relationship... -- Phlip
on 2011-04-16 01:41
There is something inefficient about it. For it to act like an undirected graph the join table needs to have 2 rows per edge. AFAIK there is no good solution to this out there ... a "good" solution meaning one which doesn't double the size of the join table to make the directed graph behave like an undirected graph.