dace
dace

Reputation: 6363

How to query for an association of an association in Rails with ActiveRecord?

I have the following models and associations:

I'm trying to get all of the tags associated with all recipes of an organization. I want to do something like, Organization.find(1).recipes.tags, but it's not working. Is there an easier way to query for this, rather than looping through each recipe to collect it's tags?

Upvotes: 4

Views: 1113

Answers (2)

jvillian
jvillian

Reputation: 20263

Try:

Tag.where(recipe: Organization.find(1).recipes)

This assumes Tag belongs_to :recipe.

Upvotes: 1

mrzasa
mrzasa

Reputation: 23327

You need to use joins and filter on organization_id

Tag.joins(recipies: :organization).where('recipies.organization_id' => 1)

Upvotes: 2

Related Questions