Having groups within groups

Hi,

I have bee talking with a colleague about a project idea. He stated that one of the features would be that you would have groups which have members. Within this group other groups could be created as well. They live within the parent group if you like. So for example Group 1 could have 5 groups attached to it. I have looked around some docs and cant find a solid way that this could be achieved.

Can anyone point me in the right direction to how this may be achieved?

Damien

I have done this in other languages using a recursive table (a table that references itself). Basically every record would have a reference to something in that table. Doing this allows you to have nested groups as deep as you would like.

  • Parent Group
    • Sub Group
    • Sub Sub Group

and so on like that until the end of time or you put a limit in the code. In past I had limited it to between 4 and 6 nested levels including the parent. So the above example would be 3 levels. I have also used this for creating pages and sub pages. You should be able to use something like this on your category model.

belongs_to          :parent,
                          :foreign_key => "parent_id",
                          :class_name => "Category"

has_many           :children,
                          :foreign_key => 'parent_id',
                          :class_name => 'Category',
                          :order => 'created_at ASC',
                          :dependent => :delete_all

so a record would look something like this.

id => 1
category_name => “Parent Group”
created_at => 6-19-2014
updated_at => 6-19-2014
parent_id => 0 (Note: This might possibly need to be null)

So every Top level category would get a default id of 0 meaning it has no parent. Any sub category would have an identical setup except for it having an id referencing its parent…

id => 2
category_name => “Sub Group”
created_at => 6-19-2014
updated_at => 6-19-2014
parent_id = > 1

So record two now references its own table and contains the Id of its parent category.

I did a little research on google and found. This is a gem that helps add the functionality for doing what was described above.

https://rubygems.org/gems/acts_as_tree

As for linking the members to groups you would create a model for members and a model for the linking them to groups. These would be separate tables in your database. You would use something like this on your member model.

 has_many :groups, :through => :member_groups

This would allow your members to belong to 1 or 100 groups.

Anyway I hope this helps you out.