ActiveRecord & PostgreSQL 排序错误



我的 Rails 应用程序中有两个模型:Product 和 CardItem

产品有现场价格

卡片项目具有字段数量,属于产品。

我想根据产品选择所有卡项目的总价.价格 * 数量

class CardItem < ActiveRecord::Base
  belongs_to :product
  scope :total_price, -> {
    result = joins(:product).select('SUM(products.price * card_items.quantity) as total_price')
    result.empty? ? 0 : result.first.total_price
  }
end

这段代码在 sqlite 中完美运行,但使用 postgresql 时它会抛出错误:

PG::GroupingError: ERROR:  column "card_items.id" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: ...t_id" WHERE "card_items"."user_id" = $1  ORDER BY "card_item...
                                                             ^
: SELECT  SUM(products.price * card_items.quantity) as total_price FROM "card_items" INNER JOIN "products" ON "products"."id" = "card_items"."product_id" WHERE "card_items"."user_id" = $1  ORDER BY "card_items"."id" ASC LIMIT 1
ActiveRecord::StatementInvalid: PG::GroupingError: ERROR:  column "card_items.id" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: ...t_id" WHERE "card_items"."user_id" = $1  ORDER BY "card_item...
                                                             ^
: SELECT  SUM(products.price * card_items.quantity) as total_price FROM "card_items" INNER JOIN "products" ON "products"."id" = "card_items"."product_id" WHERE "card_items"."user_id" = $1  ORDER BY "card_items"."id" ASC LIMIT 1

请帮我解决这个问题

附言我使用 Rails 4.0.0

PostgreSQL对其聚合查询非常严格。SQLite不是。

这并不意味着代码可以与SQLite完美配合,它只是意味着您没有被告知可能的错误来源。

在这种情况下,我什至不确定按未在 SELECT 列中列出的字段排序意味着什么。你怎么知道你得到的是哪个 card.id 的总数?

由于您没有指定排序顺序,我猜这是 ActiveRecord 默认的东西,可能是由您使用first触发的。它试图给出一个默认顺序,以便"第一个"结果具有一些一致的含义。

但是,您的查询对我来说没有意义,除非您每个user_id只能有一个card_item。筛选器处于打开状态user_id如果user可以有多个与之关联的card_item,则意味着您可以返回多行。这与将total_price与card_item而不是user相关联的想法不符。除非我错过了什么。

最新更新