Markus
Markus

Reputation: 4038

rails: filter categories where there are at least one article

I have articles and categories in a n:m relation:

I looking for a find statement on the Category Model so that I can get all categories witch consist at least one article.

Should be easy, but I didn't find a efficient solution, without searching retrieving all the articles.

Thanks, Maechi

Upvotes: 0

Views: 219

Answers (1)

Fran
Fran

Reputation: 1073

I think that counter cache is your friend here. Take a look here.

You can add the counter cache to the categories table and in the CategoryArticles you do like

class CategoryArticles
  belongs_to :article
  belongs_to :category, :counter_cache => true
end

So you can find your Category with

@categories = Category.find(:all, :conditions => ["category_articles_count > ?", 0]) 

Upvotes: 1

Related Questions