0
votes

Here's the query I'm trying to run:

Stack.joins(:services)
     .select('stacks.id, stacks.name, count(services.id) as services_count')
     .group('stacks.id').having('services_count > 2')

The error I'm getting is:

ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR: column "services_count" does not exist LINE 1: ...ack_items"."service_id" GROUP BY stacks.id HAVING services_c...


Here are how my Stack model is related:

class Stack < ActiveRecord::Base
  has_many :services, through: :stack_items
end

class StackItem < ActiveRecord::Base
  belongs_to :service
  belongs_to :stack
end

class Service < ActiveRecord::Base
  has_many :stacks, through: :stack_items, dependent: :destroy    
end

I just want to get a collection of Stacks that have at least 3 stack items where service.weight == 1.

Any suggestions?

1

1 Answers

0
votes

Aliases that you set in the SELECT list in Postgres are not available in a group by clause, so simply change .having('services_count > 2') to .having('count(services.id) > 2').