I have simple model of Product
, Guide
and Document
which are like this :
Product
has many Guides
and Guide
has many Documents
The query I'm looking for is to return the Product only if it contains a document.
Product.joins(:guides).distinct
is giving Product with at least a guide, but how to add a nested level?
Product.joins(guides: :documents).distinct
Assuming your models have set up the has_many
associations, your table names are standard, and that should generate the query:
SELECT DISTINCT "products".* FROM "products"
INNER JOIN "guides" ON "guides"."product_id" = "products"."id"
INNER JOIN "documents" ON "documents"."guides_id" = "guides"."id"
(The query will vary based on the flavor of SQL you are using; This is for Postgres.)
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.