Forum: Ruby on Rails Self-referencing model

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.
David H. (Guest)
on 2008-10-08 04:53
I'm fairly new to Ruby on Rails, and am having trouble figuring out how
to do this.  I have a model called Organization.  I want to set things
up so that an org can have sub-orgs (which can have sub-orgs

Can anyone point me to a good example or explanation (or provide one
directly) so I can get an idea of how to do this?

stuart.coyle (Guest)
on 2008-10-08 05:11
(Received via mailing list)
I've just been doing this myself with systems and sub-systems.

In the system model I have:

  has_many :sub_systems, :class_name => "System", :foreign_key =>
"system_id", :dependent=>:nullify

Then you can refer to the system.sub_systems

I also have code to prevent loops which will go around forever if you
traverse the system-sub-system tree.

 def validate
    errors.add(:sub_systems, "Cannot be a subsystem of itself.") if

def all_subs(subs = [])
    self.sub_systems.each do |s|
      unless subs.include?(s)
        subs << s

Hope that helps.

On Oct 8, 10:53 am, David H. <removed_email_address@domain.invalid>
Michael S. (Guest)
on 2008-10-08 05:11
(Received via mailing list)
Look into the :as and :source options for the has_many and belongs_to
associations, they should be able to do what you need.

Good luck!

On Oct 7, 5:53 pm, David H. <removed_email_address@domain.invalid>
stuart.coyle (Guest)
on 2008-10-08 05:14
(Received via mailing list)
I forgot this - you also have to have

belongs_to :system
Alex B. (Guest)
on 2008-10-08 07:52
(Received via mailing list)
Acts as Tree:

Does everything you need.

On Oct 7, 8:53 pm, David H. <removed_email_address@domain.invalid>
This topic is locked and can not be replied to.