Home > Net >  How to get records created in each month in rails
How to get records created in each month in rails

Time:05-27

Looking for a way to get all the records that are created in each month for a table

For example i need to know how to get a result like:

January: 6,
Feb: 9,
March: 10

Ideally i'm looking at using the created_at field in the database to compare against.

CodePudding user response:

Imagine you have a Users table (my Rails application has one), like this:

id
name
.
.
.
created_at
updated_at

You could use this code, which would return a hash of months with the count:

users = User.all
users.group_by {|u| u.created_at.strftime("%B")}.transform_values {|v| v.count}

Returns something like:

{"September"=>33,
 "August"=>1,
 "October"=>1,
 "February"=>55,
 "January"=>185,
 "May"=>4,
 "December"=>145,
 "June"=>8,
 "November"=>19,
 "March"=>51,
 "April"=>27,
 "July"=>5}

Explanation

created_at.strftime("%B")

This converts the date to a Month, using strftime

users.group_by {|u| u.created_at.strftime("%B")}

Creates a hash that groups the user records by the Month name, using group_by

.transform_values {|v| v.count}

Instead of a collection of records, we just want the count. We leave the key alone in the hash, and use transform_values to count the values.

  • Related