Active Record query based on property of has_many relationship?

142 Views Asked by At

Here's a common occurrence. I have a parent category, say Category. It has_many child categories, say Books. Books have a property published, and I want to get all Categories that have published books. How do I do that?


I could loop through the Categories to find them, but I want a better way. In this Railscast, he suggests using the following query: Category.joins(:products).merge(Product.cheap), or Subject.joins(:books).merge(Book.published) in my example. However, I don't have a scope published in Book.

I have a method all_published in Book that returns all published books, so I tried Category.joins(:books).merge(Book.all_published) but it contained duplicate categories. What's the best general way to solve this common problem?

1

There are 1 best solutions below

0
On BEST ANSWER

The .joins makes duplicates, whereas .includes does not.

In your case, the following should work:

Category.includes(:books).merge(Book.all_published)