How do I model self-referential entities?

Hi all -

I am having some trouble figuring out how to model self-referential
entities in Rails.

I have a “group” model, which can have 0 or more “group” objects or 0 or
more “user” objects.

I tried creating a subgroup table that has a parent_group_id and a
child_group_id as foreign keys but can’t figure out how to create the
mapping in my ruby model classes. I can’t come up with the correct
parameters for habtm or has_many :through.

Any help would be appreciated.


Well the relationship between groups & users is simple with a
has_and_belongs_to_many or has_many :through association…

for stuff with parent & child groups, have a look at acts_as_nested_set
or _acts_as_tree
in the rails API docs … exactly what you need i think.

Check out Josh S.'s blog post on Self-referential has_many :through

Thanks, this is exactly what I needed. Works great.


Hi Thorsten -

I don’t think the acts_as_tree will work for me, because I am really
dealing with a many-to-many self-referential relationship. A group can
be a member of one or more groups, just as a user can be a member of one
or more groups.