title: Rails where having query
body: <p>Here's the query I'm trying to run:</p>
  
  <pre><code>Stack.joins(:services)
       .select('stacks.id, stacks.name, count(services.id) as services_count')
       .group('stacks.id').having('services_count &gt; 2')
  </code></pre>
  
  <p>The error I'm getting is:</p>
  
  <blockquote>
    <p>ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR:  column "services_count" does not exist
    LINE 1: ...ack_items"."service_id" GROUP BY stacks.id HAVING services_c...</p>
  </blockquote>
  
  <hr>
  
  <p>Here are how my Stack model is related:</p>
  
  <pre><code>class Stack &lt; ActiveRecord::Base
    has_many :services, through: :stack_items
  end
  
  class StackItem &lt; ActiveRecord::Base
    belongs_to :service
    belongs_to :stack
  end
  
  class Service &lt; ActiveRecord::Base
    has_many :stacks, through: :stack_items, dependent: :destroy    
  end
  </code></pre>
  
  <hr>
  
  <p>I just want to get a collection of <code>Stacks</code> that have at least 3 stack items where <code>service.weight == 1</code>.</p>
  
  <p>Any suggestions?</p>