# Finding non-empty associations

**URL:** <https://www.ruby-forum.com/t/finding-non-empty-associations/121513>\
**Category:** Rails\
**Created:** [November 28, 2007, 4:38pm UTC](https://www.ruby-forum.com/t/finding-non-empty-associations/121513 "2007-11-28T16:38:07Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [November 28, 2007, 4:38pm UTC](https://www.ruby-forum.com/t/finding-non-empty-associations/121513/1 "2007-11-28T16:38:07Z")

</div>

Using the Farmer/Cow example from the Pro Active Record book, assume the  
following:

Farmers are related to Cows such that Farmers have\_many Cows and Cows  
belong\_to Farmers. That is, a plain old one-to-many association.

However, not all farmers have cows. Some just grow vegetables. So how do  
I  
find all the farmers who have cows?

Something like this would be nice:

```
farmers = Farmer.find(:all, :conditions => !farmers.cows.empty?)

```

But this doesn’t work, of course. Neither AWD nor the Active Record book  
get  
into this kind of thing. Is there any way to do this with Active Record?  
Or  
do I just need to use a SQL statement?

TIA: John

---

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [November 28, 2007, 4:49pm UTC](https://www.ruby-forum.com/t/finding-non-empty-associations/121513/2 "2007-11-28T16:49:58Z")

</div>

On Nov 28, 2007 10:37 AM, Identry [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> ```
> farmers = Farmer.find(:all, :conditions => !farmers.cows.empty?)
> 
> ```
> 
> But this doesn’t work, of course. Neither AWD nor the Active Record book get  
> into this kind of thing. Is there any way to do this with Active Record? Or  
> do I just need to use a SQL statement?

I think the most efficient way would be:

Farmer.find :all, :conditions =\> ‘id in (select farmer\_id from cows)’

---

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [November 28, 2007, 5:12pm UTC](https://www.ruby-forum.com/t/finding-non-empty-associations/121513/3 "2007-11-28T17:12:16Z")

</div>

Bob,

That did it. Thanks.

– John
