简体   繁体   中英

Rails how to find records where the has_many relation exists?

In the below association, I want to collect all Users who don't have any projects->

class User <  ActiveRecord::Base    
  has_many :projects, :foreign_key => :user_id  
end

class Projects < ActiveRecord::Base 
  belongs_to :user, :foreign_key => "user_id"
end

From User model, how can I get all the users that do not have any projects? I tried using includes and join but didn't get the expected result

You could try:

User.where.not(id: Project.pluck(:user_id).uniq)

Breaking it down:

Project.pluck(:user_id).uniq

will give you an array of user_ids from your projects. Essentially, users with projects.

Then:

User.where.not(id: Project.pluck(:user_id).uniq)

returns users who have an id that is not in the array of users with projects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM