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.

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

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


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.

SELECT COUNT(*) AS "count_all", "projects"."billable" AS "projects_billable" FROM "projects" GROUP BY "projects"."billable"

=> {true=>4}


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

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