Benoit
Benoit

Reputation: 373

Rails active record querying nested association existence

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?

Upvotes: 0

Views: 271

Answers (1)

hoffm
hoffm

Reputation: 2436

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

Upvotes: 2

Related Questions