2

There are two tables, groups, and groups_hierarchy. groups has standard information about a group and the group_hierarchy has two columns (parent, child) that list the parent group's id and child group's id. This is to say that the child group is a subgroup of the parent group. I have been trying to figure out what the associations would be in the GroupHierarchy and Group Data Models. Can someone help me with this?

A group can have many subgroups and it can be a subgroup of many other groups. I figured it would be a has_many :grouphierarchies in Group and belongs_to :group in GroupHierarchy but that didn't work...the thing is GroupHierarchy technically belongs to 2 groups.

Thanks

Counterfly
  • 29
  • 1
  • 4

1 Answers1

0

In my Group Model I needed the following:

class Group < ActiveRecord::Base

has_and_belongs_to_many :children, :class_name => 'Group', :join_table => 'groups_hierarchy', :foreign_key => 'parent', :association_foreign_key => 'child'

has_and_belongs_to_many :parents, :class_name => 'Group', :join_table => 'group_hierarchy', :foreign_key => 'child', :association_foreign_key => 'parent'

end

And you actually don't need anything in the GroupHierarchy class, which seems to just act as a support table to allow for self-referencing.

Thanks again

Counterfly
  • 29
  • 1
  • 4