Some models have the following relationships:
Group-<GroupUser>-User
User
can belong to Group.
How should I write to find Group
to which User A
and User B
and User C
Only belong?
Now I'm checking the Group
one by one and it's very inefficient.
Thank you for your cooperation.
As @naopontan said, I think it would be faster to search the group_users
table.
class UserGroup<ApplicationRecord#GroupUser was taken by rails, so this is the substitute.
self.table_name = 'group_users'
end
UserGroup
.select(:group_id)
.where(user: [user_a, user_b, user_c])
.group(:group_id)
.having('count(user_id)=3')
© 2024 OneMinuteCode. All rights reserved.