Rails 7.1 adds ActiveRecord regroup
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.