Search code examples
ruby-on-railsactiverecordancestry

Rails 3: Modeling groups and members as a hierarchy


A Group instance can contain Person instances or other Group instances. I want to use the Ancestry gem to mirror a hierarchy, but Ancestry does not seem to work with two different models. I don't want to use Single Table Inheritance on Person and Model because they are conceptually different.

What is the best way to go about modeling this requirement? I am willing to build my own hierarchy using many-to-many or other types of associations, but I am not sure how to make the two models (Person and Group) play nice with each other.

Thank you.


Solution

  • You can easily set a hierarchy on the Group class (using whatever suits you for single-model hierarchies) and then add a one-to-many association between Groups and Users:

    class Group < AR::Base
      acts_as_tree # or whatever is called in your preferred tree implementation
      has_many :users
    end
    
    class User < AR::Base
      belongs_to :group
    end
    

    You will have

    @group.children # => a list of groups
    @group.parent   # => another group or nil if root
    @group.users    # => the users directly below this group
    @user.group     # => a group
    

    If you really need the group to have either users or subgroups but not both, use a validation rule.