1

Rails 7.1 Introduces ActiveRecord regroup Method

 7 months ago
source link: https://blog.saeloun.com/2024/02/19/rails-7-1-introduces-active-record-regroup-method/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Rails 7.1 Introduces ActiveRecord regroup Method

Feb 19, 2024

authorImg

Prasanth Chaduvula

I'm a React, Javascript & Rails full-stack Software Engineer. I have been working remotely for the past two years in a remote village. Before joining as a Software Engineer I founded kwiq - a hyperlocal delivery startup to deliver things in remote villages.

1 minute read

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.

Share this post!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK