Rails 7.1 adds ActiveRecord regroup

railsDecember 27, 2023Dotby Alkesh Ghorpade

ActiveRecord group method organizes records in a database query into groups based on specified attributes. It is helpful for aggregations, calculations, and displaying data in a structured way. It generates a SQL query with a GROUP BY clause.

A generic syntax for group method in Rails is:

ModelName.group(column1, column2, ...)

To group Post based on author, you need to write the code as below:

# Group posts by author
posts = Post.group(:author)

SELECT `posts`.`*` FROM `posts` GROUP BY `posts`.`author`

Before Rails 7.1

Rails 6 added the ActiveRecord#reselect method a short-hand for unscope(:select).select(fields). Rails has reorder and rewhere methods in ActiveRecord relation. You can use them to override existing order and where clauses on an ActiveRecord::Relation.

To reset the group clause, you need to use the unscope method.

posts = Post.group(:author).unscope(:group).group(:status)

SELECT `posts`.`*` FROM `posts` GROUP BY `posts`.`status`

In Rails 7.1

Rails 7.1 introduces ActiveRecord regroup & regroup! methods to reset previously set group statements.

posts = Post.group(:author).regroup(:status)

SELECT `posts`.`*` FROM `posts` GROUP BY `posts`.`status`

The regroup method simplifies resetting a query's grouping by conveniently combining unscope(:group) and group(fields) in a single step.

In summary, the regroup method offers:

  • Flexibility: Dynamically adjust query groupings for greater adaptability.

  • Readability: Improve code clarity with concise and expressive syntax.

  • Efficiency: Streamline query building and potentially enhance performance.

To know more about this feature, please refer to this PR.

Closing Remark

Could your team use some help with topics like this and others covered by ShakaCode's blog and open source? We specialize in optimizing Rails applications, especially those with advanced JavaScript frontends, like React. We can also help you optimize your CI processes with lower costs and faster, more reliable tests. Scraping web data and lowering infrastructure costs are two other areas of specialization. Feel free to reach out to ShakaCode's CEO, Justin Gordon, at justin@shakacode.com or schedule an appointment to discuss how ShakaCode can help your project!
Are you looking for a software development partner who can
develop modern, high-performance web apps and sites?
See what we've doneArrow right