简体   繁体   English

使用Rails从具有多个组的组中检索具有所有组的用户

[英]Retrieve users having all of the groups from an array of groups with Rails

I have an app in which users have many groups and groups have many users, through a GroupUsers join table. 我有一个应用程序,其中通过GroupUsers连接表,用户具有多个组,并且组具有许多用户。

I'd like to get all the Users in exactly all of the groups of a given array of groups. 我想让所有用户完全位于给定组数组的所有组中。

It sounds quite simple, yet I've not managed to find a way to do it. 听起来很简单,但我还没有找到一种方法来做到这一点。

This is what I tried ( all_groups is the array of groups) : 这就是我尝试过的( all_groups是组的数组):

users = User
all_groups.each do |group| 
  users = users.joins(:group_users).where("group_users.group_id = ?", group.id)
end   

I always get no result, so I tried this to understand what's going on : 我总是没有结果,所以我尝试这样做以了解发生了什么:

users = User

group1 = all_groups.first 
group2 = all_groups.last 

users1 = users.joins(:group_users).where("group_users.group_id = ?", group1.id)
users2 = users1.joins(:group_users).where("group_users.group_id = ?", group2.id)  

users1 is an array with all the users in group1 as expected, but users2 is always empty. users1是一个数组,其中group1所有用户均符合预期,但是users2始终为空。

Does someone have a clue about how to solve this ? 有人对如何解决这个问题有一个线索吗?

EDIT : Answer : 编辑 :答案:

users = User
all_groups.each do |group| 
  users = User.including_ids(users.map(&:id)).joins(:group_users).where("group_users.group_id = ?", group.id)
end  

With in models/user.rb : 在in models / user.rb中:

scope :including_ids, ->(*ids) {
  where(arel_table[:id].in(ids))
}

That's not really beautiful but it's working. 那不是真的很漂亮,但是可以正常工作。

based on the explanation you gave, I assume you have something like: 根据您的解释,我假设您有以下内容:

class User
  has_many :group_users
  has_many :groups, through: :group_users
end

class GroupUser
  belongs_to :user
  belongs_to :group
end

class Group
  has_many :group_users
  has_many :users, through: :group_users
end

If yes, you can probably do the following: 如果是,则可以执行以下操作:

# get groups
groups = Group.where( ......some condition here ) 

# as long as groups is an ActiveRecord::Relation type you can use 'pluck'
User.joins( :group_users ).where( 'group_users.group_id IN (?)', groups.pluck(:id) ).uniq

Hope that helps. 希望能有所帮助。 :) :)

Cheers! 干杯!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM