Finding non-empty associations

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

On Nov 28, 2007 10:37 AM, Identry [email protected] 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)’

Bob,

That did it. Thanks.

– John