rails/rails — pull request #10797 by afeld (2013-05-30 06:23:57+00:00)
Title: Add `group_by` to `ActiveRecord::FinderMethods`

*Replaces #10447, since Github Pull Requests don't understand rebasing.*

* Incorporated feedback from @egilburg.
* Updated benchmarks, and included pre-patch times [here](https://gist.github.com/afeld/5516129).

---------

Enables collecting of records into sets, grouped by distinct values for the specified `field`. Leverages `ActiveRecord::Relation` to be far more efficient than `Enumerable#group_by` when selecting based on a column name.

Example:

```ruby
User.group_by('role')
# => {
# "normal" => #,
# "admin" => #
# }
```

I work with a lot of people who are new to Rails, and I've had multiple people ask if there was a way to do this with ActiveRecord. Figured it was time to finally support it.

One question: should documentation be added suggesting an index on any column that `group_by` is being called on regularly? I haven't seen those kinds of tips anywhere else in the documentation, but think it might be beneficial.