# Find Not Empty Categories

**URL:** <https://www.ruby-forum.com/t/find-not-empty-categories/107636>\
**Category:** Rails\
**Created:** [June 24, 2007, 5:27pm UTC](https://www.ruby-forum.com/t/find-not-empty-categories/107636 "2007-06-24T17:27:17Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![matt](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/a6a055/32.png) [@matt](https://www.ruby-forum.com/u/matt)\
**Post date:** [June 24, 2007, 5:27pm UTC](https://www.ruby-forum.com/t/find-not-empty-categories/107636/1 "2007-06-24T17:27:17Z")

</div>

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?

---

<div class="post-metadata">

**Author:** ![matt](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/a6a055/32.png) [@matt](https://www.ruby-forum.com/u/matt)\
**Post date:** [June 25, 2007, 9:41am UTC](https://www.ruby-forum.com/t/find-not-empty-categories/107636/2 "2007-06-25T09:41:00Z")

</div>

> 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 …

---

<div class="post-metadata">

**Author:** ![matt](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/a6a055/32.png) [@matt](https://www.ruby-forum.com/u/matt)\
**Post date:** [June 25, 2007, 10:46am UTC](https://www.ruby-forum.com/t/find-not-empty-categories/107636/3 "2007-06-25T10:46:28Z")

</div>

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.
