Context: I am using Active Admin and would like to define a scope to show me any Users with more than 5 orders in the next week. This is a Postgres DB in a Rails app.
User.where(vetting_status: ["Enabled"]).joins(:orders).where('orders.date >= ? AND orders.date <= ?', Date.today, Date.today + 6.days).select('users.first_name, COUNT(orders.id) AS order_count').group('users.first_name').having('order_count > 5').order('order_count desc')
However, this gives me the following error when I try to run it: ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR: column "order_count" does not exist
The issue is with the .having('order_count > 5')
as I can run the query if I remove that part. However, that's the crucial part and I'm not sure what I'm getting wrong. I've tried .having('gardener.order_count > 5')
and .having('orders.order_count > 5')
but neither of those worked either. Thanks in advance for help. P.S. I have searched a fair few answers and couldn't find a solution.