How to find models that have at least one associated has_many

I’m having a senior moment. I’ve done this before but I can’t remember
how.

Two active record models,

Foo belongs_to Bar

Bar has_many Foos

I want to find all Bars that have at least one Foo, is it:

Bar.all(:include => :foos, :conditions => "foo.id IS NOT NULL’)

or something else?


Rick DeNatale

Blog: http://talklikeaduck.denhaven2.com/
Github: rubyredrick (Rick DeNatale) · GitHub
Twitter: @RickDeNatale
WWR: http://www.workingwithrails.com/person/9021-rick-denatale
LinkedIn: http://www.linkedin.com/in/rickdenatale

Hi Rick,

On Fri, Jun 11, 2010 at 1:26 PM, Rick DeNatale [email protected]
wrote:

Bar.all(:include => :foos, :conditions => "foo.id IS NOT NULL’)
Seems like it would be ‘foo.bar_id’ in the condition clause.

HTH,
Bill

On 11 June 2010 19:26, Rick DeNatale [email protected] wrote:

I’m having a senior moment. I’ve done this before but I can’t remember how.

I want to find all Bars that have at least one Foo, is it:

Bar.all(:include => :foos, :conditions => "foo.id IS NOT NULL’)

or something else?

Doesn’t…

Bar.all(:joins => :foos).uniq

…do the job?

On 11 June 2010 20:10, Michael P. [email protected] wrote:

Bar.all(:joins => :foos).uniq

Seems to… quick and dirty test on one of my models:

Person.all(:include => :graduations).select { |person| !person.graduations.empty? }.size
=> 87
Person.all(:include => :graduations).select { |person| person.graduations.size > 0 }.size
=> 87
Person.all(:joins => :graduations).size
=> 103
Person.all(:joins => :graduations).uniq.size
=> 87