title: Rails 3 query on condition of an association's count
body: <p>In Rails 3 with mysql, suppose I have two models, Customers and Purchases, obviously purchase belongs_to customer. I want to find all the customers with 2 orders or more. I can simply say:</p>
  
  <pre><code>Customer.includes(:purchases).all.select{|c| c.purchases.count &gt; 2}
  </code></pre>
  
  <p>Effectively though, the line above makes query on the magnitude of Customer.all and Purchase.all, then does the "select" type processing in ruby. In a large database, I would much prefer to avoid doing all this "select" calculation in ruby, and have mysql do the processing and only give me the list of qualified customers. That is both much faster (since mysql is more tuned to do this) and significantly reduces bandwidth from the database. </p>
  
  <p>Unfortunately I am unable to conjure up the code with the building blocks in rails(where, having, group, etc) to make this happen, something on the lines of (psudo-code):</p>
  
  <pre><code>Customer.joins(:purchases).where("count(purchases) &gt; 2").all
  </code></pre>
  
  <p>I will settle for straight MySql solution, though I much prefer to figure this out in the elegant framework of rails. </p>