title: PostgreSQL ActiveRecord Query Optimization
body: <p>I'm new to RoR and I need a query that returns the same instances as the following definition of queue :</p>
  
  <pre><code>@all = User.all
  @membersOfActivity = User.where(id: User.joins(:memberships).where("activity_id = ?", session[:current_activity_id])) 
  @usersIAlreadyLiked = User.where(id: User.joins(:likes).where("activity_id = ? AND activity_likes_user IS NOT NULL", session[:current_activity_id])) 
  @notWanted = @membersOfActivity + @usersIAlreadyLiked 
  @queue = @all - @notWanted
  </code></pre>
  
  <p>However, I understand how inefficient the query I just wrote is for it downloads all the Users first to then select the complement. Do you have any idea on how to make it more efficient and directly select the complement of @notWanted? I tried several queries but none of those worked. 
  If you think you have a better solutions please let me know! Thanks!</p>
  
  <p>EDIT : 
  Each user has many memberships, that connect a user with an activity. So each activity has also many membership. Each membership has a user_id and an activity_id.</p>
  
  <p>Each user has many likes, and each like connects a user and an activity. Therefore each activity has also many likes. A like has a user_id, activity_id, user_liked_activity, and activity_liked_user.</p>
  
  <p>user_liked_activity is NULL if the user did not express an opinion about the activity, TRUE is the user liked the activity, and FALSE if the user disliked the activity. Viceversa for activity_liked_user. </p>