How to filter by association count?

activerecord, ruby-on-rails, sql

Solution

Foo.all(:joins => :cakes, 
  :group => "cakes.foo_id", 
  :having => "count(cakes.bar_id) >= 10")

Problem

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)?

Original source