Search code examples
sqlruby-on-railsmodelhas-many

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


Solution

  • 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.