views:

22

answers:

1

Hi,

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

+1  A: 

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]) 
Francisco
Thats exactly what I needed! Do you know how I do it when I don't have the CategoryArticles Model by just implementing the has_and_belongs_to_many property?
Markus
I'm not sure that you can do it with a `has_and_belong_to_many`. My suggestion is to do it like that. class CategoryArticles belongs_to :article belongs_to :category, :counter_cache => true end class Category has_many :articles, :through => :category_articles has_many :category_articles end class Article has_many :categories, :through => :category_articles has_many :category_articles end
Francisco
Just saw that you cannot format the code in comments... you can take a look in this gist http://gist.github.com/611736
Francisco
Ok, thanks a lot! I will change my schema then.
Markus