开发者

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 开发者_StackOverflow社区didn't find a efficient solution, without searching retrieving all the articles.

Thanks, Maechi


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]) 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜