【发布时间】:2019-10-21 15:02:27
【问题描述】:
我正在尝试将用户分组到家庭中。一个家庭可以有一个父母和多个成员 所以父母也被认为是成员。
我已经尝试过这里提供的答案 association and migration between users and teams (rails) 和这里 rails many to many self join 试图让它工作,但没有运气
这就是我所拥有的
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
因此,如果我的用户 1 是父母并且有四个成员,我可以使用
user.family_members # to get family members for this parent
但是我该怎么做才能让我也能从一个成员那里得到全家人
数据库示例
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
我该怎么说像
user = User.find(4)
user.family.parent.members # which would return a family association
完整的解决方案是(如果有人感兴趣的话):
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
【问题讨论】:
标签: ruby-on-rails-5 rails-activerecord model-associations