2012-07-26 80 views
1

我有一個ActiveRecord查詢我一直在使用(歷史here),在MySQL中效果很好,但現在我需要將我的數據庫轉換爲PostgreSQL,並且出現錯誤。下面是該查詢:將Rails的ActiveRecord GROUP查詢從MySQL轉換到PostgreSQL

class Shoe < ActiveRecord::Base 
    has_many :purchases 

    def self.available_shoes 
    #show all shoes that have been purchased less than num_in_stock 
    num_in_stock = 3 
    Shoe.includes(:purchases) 
     .group("purchases.shoe_id") 
     .having("COUNT(purchases.shoe_id) < ?", num_in_stock) 
    end 
end 

簡單地切換的寶石和適配器的Postgres是不夠的:我現在得到以下錯誤:

ActionView::Template::Error (PG::Error: ERROR: column "shoes.id" must appear in the GROUP BY clause or be used in an aggregate function LINE 1: SELECT "shoes"."id" AS t0_r0, "shoes"."created_at" AS ...

我試圖改變

.group("purchases.shoe_id") 

.group("purchases.shoe_id, shoes.id, purchases.id") 

and whil這擺脫了錯誤,它也改變了SQL並破壞了我的一些測試。

我已經閱讀了許多有關此錯誤的計算器問題,但我無法找到解決方案。我需要在ActiveRecord查詢中更改以使其在postgres中工作?

在此先感謝!

回答

1

您是否找到解決方案? 如果不嘗試:

Shoe.where("not exists (select 1 from purchases where shoe_id = shoes.id offset ? limit 1)", num_in_stock - 1) 

這將是大num_in_stock慢,你應該有purchases.shoe_id列索引。

我認爲大桌子上沒有快速解決方案,除非您已經計算購買量。

編輯

考慮使用counter_cache或counter_culture gem