将`count`与具有select方法的作用域一起使用

时间:2016-02-06 21:13:19

标签: ruby-on-rails activerecord

我有一个范围 -

scope :most_stock, -> {
    joins(:stock_keeping_units).
    select("items.*, count(stock_keeping_units.id) AS stock_keeping_unit_count").
    group('items.id').
    order('stock_keeping_unit_count DESC').
    where('stock_keeping_units.sold = FALSE')
}

当我运行Item.most_stock时,一切正常,花花公子。

但是,当我运行Item.most_stock.count时,我收到以下错误 -

PG::SyntaxError: ERROR: syntax error at or near "AS" LINE 1

生成的SQL查询是 -

SELECT COUNT(items.*, count(stock_keeping_units.id) AS stock_keeping_unit_count) AS count_items_all_count_stock_keeping_units_id_as_stock_keeping_u, items.id AS items_id FROM "items" INNER JOIN "stock_keeping_units" ON "stock_keeping_units"."item_id" = "items"."id" AND "stock_keeping_units"."deleted_at" IS NULL WHERE "items"."deleted_at" IS NULL AND (stock_keeping_units.sold = FALSE) GROUP BY items.id ORDER BY stock_keeping_unit_count DESC

解决方法是使用length

我很想知道count在这里不起作用或者理想情况下应该有效吗?

0 个答案:

没有答案