When using .group with ActiveRecord, count(:all) returns a Hash instead of a number. Each entry in the hash is keyed by the group(s) and then has the count for that group as the value. The count in this case is the number of entries NOT the sum of the values. When joining a has_many a single Model (grouped by id for example) would have a count of the number of children in the has_many.
{
106119=>1,
583542=>1,
619501=>1,
...
}
The spec I added does not really show why someone would want to group. There's only a single model (User) available. Here's an example snippet from our production codebase that shows pulling in child aggregates into a datatable.
Quote
.left_joins(:address, :customer, :job, :quote_line_items)
.select('quotes.*')
.select('COUNT(DISTINCT quote_line_items.id) AS item_count')
.group(:id, 'customers.id', 'jobs.id', 'addresses.id')
# IMPORTANT: Do NOT combine into a single string expression, count(:all) can not handle a single string with multiple columns
When using
.group
with ActiveRecord,count(:all)
returns a Hash instead of a number. Each entry in the hash is keyed by the group(s) and then has the count for that group as the value. The count in this case is the number of entries NOT the sum of the values. When joining a has_many a single Model (grouped by id for example) would have a count of the number of children in the has_many.The spec I added does not really show why someone would want to group. There's only a single model (User) available. Here's an example snippet from our production codebase that shows pulling in child aggregates into a datatable.