PG :: FeatureNotSupported:错误:聚合函数

时间:2015-09-28 23:28:27

标签: ruby-on-rails postgresql

我收到了PG错误,我无法弄清楚如何重写此声明是一种有效的方法。当我在rails控制台中运行它时,一切似乎都很好。但是当我尝试将其作为后台工作处理时,它会出现以下错误:

    /Users/lorenzsell/DEV/Heartbeat-pods/app/mailers/notifications_mailer.rb:44:in `community_update'
/Users/lorenzsell/DEV/Heartbeat-pods/app/jobs/send_community_digest_job.rb:17:in `block (2 levels) in perform'
/Users/lorenzsell/DEV/Heartbeat-pods/app/jobs/send_community_digest_job.rb:16:in `block in perform'
/Users/lorenzsell/DEV/Heartbeat-pods/app/jobs/send_community_digest_job.rb:8:in `perform'
/Users/lorenzsell/DEV/Heartbeat-pods/app/jobs/schedule_send_community_digest_job.rb:9:in `block in perform'
/Users/lorenzsell/DEV/Heartbeat-pods/app/jobs/schedule_send_community_digest_job.rb:8:in `each'
/Users/lorenzsell/DEV/Heartbeat-pods/app/jobs/schedule_send_community_digest_job.rb:8:in `perform'
/Users/lorenzsell/DEV/Heartbeat-pods/lib/tasks/email_tasks.rake:10:in `block (2 levels) in <top (required)>'
-e:1:in `<main>'
ActiveRecord::StatementInvalid: PG::FeatureNotSupported: ERROR:  FOR UPDATE is not allowed with aggregate functions
: SELECT COUNT(*) FROM "activities" WHERE "activities"."receiver_id" = $1 AND "activities"."is_read" = 'f' FOR UPDATE
/Users/lorenzsell/DEV/Heartbeat-pods/app/mailers/notifications_mailer.rb:44:in `community_update'

以下是代码段:

community_ids = Activity.where(receiver_type: "community", is_read: false).uniq.pluck(:receiver_id)

1 个答案:

答案 0 :(得分:1)

根据the documentationlock会导致ActiveRecord生成SELECT ... FOR UPDATE。 Postgres不允许您对此类查询执行计数(尽管其他数据库可能 - 这可能是它在控制台中运行的原因),因此您需要在count关系中调用Activity 之前,您拨打lock

# base query
notifications = Activity.where(receiver_id: options['id'], is_read: false)

# save count
notifications_count = notifications.count

# apply lock
notifications = notifications.lock(true)