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.

Ken

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 Susser’s blog post on Self-referential has_many :through associations: http://blog.hasmanythrough.com/articles/2006/04/21/self-referential-through

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.

Ken

Thorsten L wrote:

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

Ken

Bala Paranj wrote: