Home Ask Login Register

Developers Planet

Your answer is one click away!

Michael Victor February 2016

Using `count` with scopes that have a select method

I have a scope --

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')
}

When I run Item.most_stock, everything works fine and dandy.

However, when I run Item.most_stock.count, I get the following error -

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

The generated SQL Query is -

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

A work around is to use length

I'm curious to know what count didn't work here or is it something that should ideally work?

Answers


Ilya February 2016

Because count method, invoked on ActiveRecord::Association, modified your sql query, length method not.

Post Status

Asked in February 2016
Viewed 1,749 times
Voted 6
Answered 1 times

Search




Leave an answer


Quote of the day: live life