Let's assume we have users:
class User < ActiveRecord::Base
has_many :connections
has_many :groups, through: :connections
end
And groups:
class Group < ActiveRecord::Base
has_many :connections
has_many :users, through: :connections
end
Basically, standard many-to-many connection:
class Connection
belongs_to :user
belongs_to :group
end
What I intend to do is:
- Select only users who don't belong to given set of Groups (groups with ids
[4,5,6]
) - Select only users who belong to one set of Groups (
[1,2,3]
) and don't belong to another ([4,5,6]
) - Select only users who don't belong to a Group
Also, I don't want to:
- Fetch a lot of data from database to manipulate it with Ruby code. I know that will be inefficient in terms of CPU and memory (Ruby is much slower than any commonly used DB engine, and typically I want to rely on DB engine to do the heavy lifting)
- I tried queries like
User.joins(:group).where(group_id: [1,2,3]).where.not(group_id: [4,5,6])
and they return wrong results (some users from the result set belong to groups 4,5,6 as well as 1,2,3) - I don't want to do
join
merely for the sake of only checking for existence, because I know that that is a pretty complex (i.e. CPU/memory-intensive) operation for DB