Find Not Empty Categories

I have some categories that may contain posts in a has_many
relationship.

Can I use the “find” method on the object class to only retrieve those
categories that are not empty?

Can I use the “find” method on the object class to only retrieve those
categories that are not empty?

Category.with_scope(:find => {:conditions => “foreign_key_id != null” }
)

may be good for you, but you should dig in a little further to see if
this fits your needs; check out with_scope. it will change the find
method for the whole class. maybe it’s worth doing something simpler …

My suggestion:

class Category
has_many :posts
end

class Post
belongs_to :category, :counter_cache => true
end

In your categories table create a new column “posts_count”, not null,
default value 0 (or modify your migration similarly). Now every time
you make create a post object in a category, that category’s posts_count
is increased by one without any intervention from you.

Then you can:

Category.find(:all, :conditions => ‘posts_count > 0’)

You can choose to not use this and modify your find statement but each
time you use it you will have to sum every category’s posts within the
query… I’m actually not even sure what the query would be. I think
counter_cache will work out better in the long run.