I'm trying to group users in families. A family can have one parent and multiple members so a parent is considered a member as well.
I have tried answers provided here association and migration between users and teams (rails) and here rails many to many self join to try to make it work but no luck
Here is what I have
class User < ActiveRecord::Base
# this defines the parent to members fine and you can get them
# only if you have the parent
has_many :memberships, :class_name => 'Family', :foreign_key => 'user_id'
has_many :family_members, :through => :memberships, :source => :registrar
# trying to define that user is also a member of family
belongs_to :registrar_family, :foreign_key => 'member_user_id'
end
class Family < ActiveRecord::Base
belongs_to :user, :class_name => 'User', :foreign_key => "user_id"
has_many :users, :class_name => 'User', :foreign_key => "id"
end
So if I have user 1 who is a parent and has four members I can use
user.family_members # to get family members for this parent
but how do I make so that I can also get the full family from a members
examples of DB
Users:
id, name
1, King
2, Queen
3, Prince
4, Duaghter
Users Family:
id,user_id, member_user_id
1, 1, 2
1, 1, 3
1, 1, 4
How do I say something like
user = User.find(4)
user.family.parent.members # which would return a family association
The complete solution for this is (if anyone is interested):
class User < ActiveRecord::Base
def family
members = Family.where("user_id = ? OR member_user_id = ?", self.id, self.id)
# if members is only 1 person then this person is a member only
# then get all members from parent
if members.count == 1
members = members.first.parent.family
end
members
end
def family_count
# if there is family then count is family + parent else 0
family.count > 0 ? family.count + 1 : 0
end
end
class Family < ActiveRecord::Base
belongs_to :parent, :class_name => 'User', :foreign_key => "user_id"
end