我有四种模式:
User (users)
Caretaker (a completely different type of user)
MessageGroup (a group)
MessageGroupMembership (a join table between MessageGroup and (Users && Caretakers))
我正在尝试定义一个检查组是否存在x成员的方法(成员可以是用户或看护人)。
def group_containing(members)
# return group if a MessageGroup exists whose members have the members
# passed in and those member only. No more. No less.
end
我的问题是成员是多态的,所以我无法弄清楚如何最好地构建活动记录查询。
我的课程是:
class User < ActiveRecord::Base
has_many :message_group_memberships
has_many :message_groups, through: :message_group_memberships
end
class Caretaker < ActiveRecord::Base
has_many :message_group_memberships
has_many :message_groups, through: :message_group_memberships
end
class MessageGroupMembership < ActiveRecord::Base
belongs_to :member, polymorphic: true
belongs_to :message_group
end
class MessageGroup < ActiveRecord::Base
has_many :message_group_memberships
has_many :members, through: :message_group_memberships
has_many :messages
def group_containing(members)
# method goes here.
end
end
答案 0 :(得分:0)
def group_containing(members)
member_ids = members.map(&:id)
MeesageGroup.joins(:message_group_memberships).where({:message_group_memberships => member_ids})
end
试试这个