Rails 7.1 Introduces ActiveRecord regroup Method

ActiveRecord::QueryMethods are methods provided by Rails to build and execute database queries.

The group method is used to perform grouping operations in a database query.

It allows us to group the retrieved data based on specific columns. It generates a SQL query with a GROUP BY clause.

Project.group(:name).count
SELECT COUNT(*) AS "count_all", "projects"."name" AS "projects_name" FROM "projects" GROUP BY "projects"."name"

=> {"Mac"=>1, "Azure.com"=>1, "Google"=>2}  

Before

Like we have ActiveRecord select and reselect methods to reset the previously set select statement, we don’t have method to reset the group statement.

To reset the group statement we have to use unscope method.

Project.group(:name).unscope(:group).group(:billable).count
SELECT COUNT(*) AS "count_all", "projects"."billable" AS "projects_billable" FROM "projects" GROUP BY "projects"."billable"

=> {true=>4}

After

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

Project.group(:name).regroup(:billable).count
SELECT COUNT(*) AS "count_all", "projects"."billable" AS "projects_billable" FROM "projects" GROUP BY "projects"."billable"

=> {true=>4}

Under the hood, regroup is short-hand for unscope(:group).group(fields). Basically we’re unscoping the entire group statement.

With this regroup method, we can easily reset the previously set group statement.

Need help on your Ruby on Rails or React project?

Join Our Newsletter