user1381745
user1381745

Reputation: 3900

Loading associated data in a single query

That's probably a terrible title, but here goes.

I have two models, Item and Category. It's a many-to-many relationship (items can belong to multiple categories, categories can hold multiple items).

What's the best way to look up (e.g. by 'name') list of categories and find all items included in them? If I were using SQL, I'd do something like the following:

SELECT * FROM items
WHERE category_id in (
   SELECT id FROM category
   WHERE name IN ('cat1', 'cat2', 'cat3')
)

or something, but I'd like to do it in a Railsy way if possible.

Thanks!

Upvotes: 1

Views: 28

Answers (2)

Arnaud
Arnaud

Reputation: 17737

You can do

Item.joins(:categories).where("categories.name" => ['cat1', 'cat2', 'cat3'])

Upvotes: 1

Rafal
Rafal

Reputation: 2576

EDIT

Item.includes(:categories).where("categories.name IN(?)", list_of_names)

Upvotes: 0

Related Questions