2015-09-28 42 views
1

我得到一個PG錯誤,我無法弄清楚如何重寫這句話是一個可行的辦法。當我在軌道控制檯中運行它時,一切似乎都很好。但是,當我嘗試處理它作爲後臺作業,它borks,出現以下錯誤:PG :: FeatureNotSupported:ERROR:FOR UPDATE不與聚合函數允許

/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) 
+0

我看不出該片段如何產生該SQL。你確定它不是來自另一行代碼嗎?用'.count'做些什麼? – ahmacleod

+0

我不是100%確定。我已經用該消息的其餘部分更新了錯誤片段。根據我的分析,我就跟蹤到該行是在:/schedule_send_community_digest_job.rb:8:in'執行」。你認爲這是別的嗎? – Lorenz

+0

也許從'notifications_mailer'發佈'community_update'方法的源? – ahmacleod

回答

1

the documentationlock導致的ActiveRecord生成一個SELECT ... FOR UPDATE 。 Postgres將不會讓你進行這樣的查詢計數(雖然其他數據庫可能 - 這可能是爲什麼它在控制檯工作),所以你需要打電話lock之前調用countActivity關係

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

# save count 
notifications_count = notifications.count 

# apply lock 
notifications = notifications.lock(true) 
+0

這個技巧。感謝您的支持。 – Lorenz