views:

48

answers:

1

Let's say I have models that look like this:

class Foo < ActiveRecord::Base
    has_many :bars, :through => :cakes
    has_many :cakes
end

class Bar < ActiveRecord::Base
    has_many :foos, :through => :cakes
    has_many :cakes
end

class Cake < ActiveRecord::Base
    belongs_to :foo
    belongs_to :bar
end

How would I get all foos which had 10 or more bars (and therefore 10 or more cakes)?

+3  A: 
Foo.all(:joins => :cakes, 
  :group => "cakes.foo_id", 
  :having => "count(cakes.bar_id) >= 10")
pjb3
You can speed this up by using a counter_cache. Foo.find(:all, :conditions => ['foo.cake_count > 10'])
jonnii