Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for grouped results #419

Merged
merged 1 commit into from
Apr 19, 2023

Conversation

dmorehouse
Copy link

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

@n-rodriguez n-rodriguez merged commit c20adb0 into jbox-web:master Apr 19, 2023
@n-rodriguez
Copy link
Member

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants