Forum: Ruby on Rails many:many relation on a single table

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.
9e7f68f8cf444a3a919a247e562bc464?d=identicon&s=25 Josh (Guest)
on 2007-04-12 19:21
(Received via mailing list)
Consider a tree.  Not a perfect example since every branch only has
one parent...but you get the idea.

What I want is the following:


I think the problem is not being able to change the method name
without changing the attribute it points to.  Here is my idea so far.

Thanx for looking!

class Branch < ActiveRecord::Base
  has_many :parents, :through => :relations
  has_many :children, :through => :relations

class Relation < ActiveRecord::Base
      belongs_to :branch, :foreign_key => "parent_id"
      belongs_to :branch, :foreign_key => "child_id"

table Relations
parent_id int
child_id int
foo ---
bar ---
52cb4115a870ff1942e7e1ae96f4306f?d=identicon&s=25 Tyler MacDonald (Guest)
on 2007-04-12 19:31
(Received via mailing list)
You're going to have to be very, very careful to not create loops (eg
situations where something is a child of itself) if you're going after a
tree structure. That's the sort of data integrity thing that I would
right down to the database layer as triggers on your appropriate table.

The schema here (from my old perl days) does that:

In postgres:


Hopefully you'll find something there you can use.


Josh <> wrote:
> without changing the attribute it points to.  Here is my idea so far.
>       belongs_to :branch, :foreign_key => "child_id"
> >
83ca41657a99b65d99889abe712ba5e2?d=identicon&s=25 Jason Roelofs (Guest)
on 2007-04-12 19:32
(Received via mailing list)
Hmm, check out plugins like acts_as_graph:

This topic is locked and can not be replied to.