2012-07-26 81 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