Rails ActiveRecord return records where id exists in related table Rails ActiveRecord return records where id exists in related table ruby-on-rails ruby-on-rails

Rails ActiveRecord return records where id exists in related table


Simplest but not the fastest:

Client.where(:id => Product.select(:client_id).map(&:client_id))

SQL subquery (more faster):

Client.where("EXISTS(SELECT 1 from products where clients.id = products.client_id)")


Here's another solution. It's a subquery like Valery's second solution, but without writing out the sql:

Client.where(Product.where(client_id: Client.arel_table[:id]).exists)


Here is the solution which uses Where Exists gem (disclosure: I'm its author):

Client.where_exists(:products)