Rails Nested SQL Queries

Here's how to make nested queries:

LineItem.where(product_id: Product.where(price: 50))

It makes the following request:

SELECT "line_items".* FROM "line_items" 
WHERE "line_items"."product_id" IN 
(SELECT "products"."id" FROM "products" WHERE "products"."price" = 50)

Note that only ids will be fetched from the products table. If you are trying to make another way to connect two entities and this magic isn't suitable, use Product.select(:some_field).where(...).


I'd like to suggest an updated answer. In Rails v5.0.x, you can use select to use an attribute other than id while still doing a nested query.

LineItem.where(product_id: Order.where(price: 50).select(:product_id))