我有一个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中工作?
在此先感谢!