简体   繁体   中英

ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR: column “order_count” does not exist when .having('order_count > 5')

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. PS I have searched a fair few answers and couldn't find a solution.

The HAVING clause is evaluated before the SELECT - so the server doesn't yet know about that alias.

Instead of COUNT(orders.id) AS order_count you should do count(orders) as order_count You can look around here
I have tried so far below and its working, hopefully it will help you.

User.where(vetting_status: ["Enabled"]).joins(:orders).where('orders.date >= ? AND orders.date <= ?', Date.today, Date.today + 6.days).group('users.first_name').having('count(orders) > 5').order('count(orders) desc').select('users.first_name')

Alternatively you should do as with your above query: -

count(orders) as order_count

This also means the it will get total orders of user as order count. like this: -

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) as order_count').group('users.first_name').having('count(orders) > 5').order('order_count desc')

Hence both answers are working without any error. :D

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM