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)")

Another gem that exists to do that: activerecord_where_assoc (I'm the author)

With it:

Client.where_assoc_exists(:products)

If you had to also specify some of the products, when you could do it like this:

Client.where_assoc_exists(:products, id: my_products.map(&:id))

Doing it without a gem makes it easy to do mistakes.

Read more in the documentation. Here is an introduction and examples.


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)