Home > Mobile >  How to find unassociated records Rails Activerecord
How to find unassociated records Rails Activerecord

Time:10-16

I have these three models

class User < ApplicationRecord
  has_many :subscribes
  has_many :groups, through: :subscribes
end
class Group < ApplicationRecord
  has_many :subscribes
  has_many :users, through: :subscribes
end
class Subscribe < ApplicationRecord
  belongs_to :user
  belongs_to :group
end

I want to query in a clean way, all the groups that the user is not in. How can I do this?

CodePudding user response:

One way to do this would be to use the "where" method in ActiveRecord.

For example:

Group.where("id NOT IN (?)", user.groups.map(&:id))

This would give you all of the groups that the user is not in.

you can also use a subquery for this:

Group.where("id NOT IN (SELECT group_id FROM subscribes WHERE user_id = ?)", user.id)

This would give you the same result as the previous example, but without using the .map method. "

CodePudding user response:

If user has groups association, it means it has group_ids method

Group.where.not(id: user.group_ids)

And also you can explicitly extract such ids

Group.where.not(id: Subscribe.select(:group_id).where(user_id: user.id))
  • Related