I have a user system in which a user can be associated with a group. This works fine.
Now I am in the need to be able to associate a user with a group and that group can be associated with another group. I want to be able to fetch the users that belongs to both the parent group and all the child groups in one operation.
So it goes:
Group -> Group -> Member
This is how the setup looks today:
class Group < ActiveRecord::Base
belongs_to :customer
has_many :child_groups, class_name: "Group", foreign_key: 'parent_group_id'
belongs_to :parent_group, class_name: "Group"
has_many :memberships, :class_name => "Group::Membership"
has_many :members, :through => :memberships
end
And Group::Membership looks like this:
class Group::Membership < ActiveRecord::Base
belongs_to :member
belongs_to :group
has_many :customers, :through => :group
end
Lets say I fetch a group which has several child groups associated with it with the command Group.first.members and fetch all the members in both the main group and all the members in the child groups in preferably one DB request.
Is this possible with only base Rails associations or do I need to do some custom SQL?
I would look into using Single Table Inheritance. Have all your other groups inherit from the parent group.
You will then be able to query ParentGroup.all and see every group.
search for Single Table Inheritance in this link
http://api.rubyonrails.org/classes/ActiveRecord/Base.html