Forum: Ruby on Rails Any progress on undirected self-referential many to many relationships?

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Ce1ef96a78d76845cc2fa24c872c3a31?d=identicon&s=25 Eli Gibson (Guest)
on 2008-11-20 08:03
(Received via mailing list)
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
Fb231c581a4c246c7d8d2e3ada171959?d=identicon&s=25 Ewout Kleinsmann (ewoutk)
on 2008-11-28 00:18
Aafa8848c4b764f080b1b31a51eab73d?d=identicon&s=25 Phlip (Guest)
on 2008-11-28 02:42
(Received via mailing list)
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
the Model objects until they express your business rules, like any other

6165aecb1a97c3ee6df433e38b49ca37?d=identicon&s=25 Blake M. (blake_m)
on 2011-04-15 23: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.
This topic is locked and can not be replied to.