Note that there are some explanatory texts on larger screens.

plurals
  1. POEfficiently Filter Many-To-Many
    primarykey
    data
    text
    <p>In an app I'm writing I have users that may belong to any number of groups. There exists a has_many relationship through a corresponding group_membership model. </p> <p>I am working on a reporting interface and would like to filter by groups, so I would like to return users who belong to ALL listed groups (even if they belong to other additional groups). </p> <p>Currently, I repeatedly filter the set of users based on their membership to each group in turn, such that users are filtered out if they are not members of the current group. </p> <pre><code> @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? </code></pre> <p>Is there a more efficient way of doing this? </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload