在我正在编写的应用程序中,我的用户可能属于任意数量的组。通过相应的 group_membership 模型存在 has_many 关系。
我正在开发报告界面并希望按组过滤,因此我想返回属于所有列出的组的用户(即使他们属于其他其他组)。
目前,我根据每个组的成员身份依次重复过滤用户集,这样如果用户不是当前组的成员,就会被过滤掉。
@users = @account.users.joins(:groups).where("groups.id in (?)",all_groups).pluck('users.id') #All user IDs
positions_users = @account.users.joins(:groups).where("groups.id in (?)",positions).pluck('users.id') unless positions.empty?
departments_users = @account.users.joins(:groups).where("groups.id in (?)",departments).pluck('users.id') unless departments.empty?
locations_users = @account.users.joins(:groups).where("groups.id in (?)",locations).pluck('users.id') unless locations.empty?
miscellaneous_users = @account.users.joins(:groups).where("groups.id in (?)",miscellaneous).pluck('users.id') unless miscellaneous.empty?
@users = @users.select {|x| positions_users.include? x } unless positions_users.nil? || positions_users.empty?
@users = @users.select {|x| departments_users.include? x } unless departments_users.nil? || departments_users.empty?
@users = @users.select {|x| locations_users.include? x } unless locations_users.nil? || locations_users.empty?
@users = @users.select {|x| miscellaneous_users.include? x } unless miscellaneous_users.nil? || miscellaneous_users.empty?
有没有更有效的方法来做到这一点?