0

So let's say I have Post, Category and Categorizations models.

A post can have many categories through categorizations.

Now, how can I pull out all the posts that match at least one item of an array of categories?

Example:

Post 1 has categories 2,5,6
Post 2 has categories 1,5,9
Post 3 has categories 2,4,8
Find posts that match 3,5

I want the posts 1 and 2 to be returned.

Thanks!

1 Answer 1

1

Assuming that Categorization is a join model for Post and Category:

Post.joins(:categorizations).where(:categorizations => {:category_id => [3, 5]})

If it's not, and Categorization actually has_many :categories then:

Post.joins(:categories).where(:categories=> {:id => [3, 5]})

Note that the second method will work in the first case as well, however it will require 2 SQL joins and thus may not perform as well.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.