title: Using Postgres, calculate count of association
body: <p>I have 2 models</p>
  
  <pre><code>class Foo &lt; ActiveRecord::Base
    # columns are
    # max_spots
  
    has_many :bars
  end
  
  class Bar &lt; ActiveRecord::Base
    # columns are
    # a_id
  
    belongs_to :foo
  end
  </code></pre>
  
  <p>I need to get all Foos whose max_spots is greater than the number of bars associated to it but I need it to be done via active record and not by going through each Foos like</p>
  
  <pre><code>class Foo
    #bad
    def self.bad_with_spots_left
      all.select do |foo|
        foo.max_spots - foo.bars.count &gt; 0
      end 
    end
  
    #good but not working
    def self.good_with_spots_left
      joins(:bars).select('COUNT(bars.id) AS bars_count').where('max_spots - bars_count &gt; 0')
    end
  end
  </code></pre>
  
  <p>I know I can just add a counter cache to foo, but just want to know how I can do this without that. Thanks!</p>