Harsha M V
Harsha M V

Reputation: 54989

Calculate the number of records for each day

I have user sign up. I want to display a graph for the last 7 days with the number of sign ups on each day based on the created_at record

Can i use active record query to achieve this with some kind of grouping and count instead of calculating it manually through iteration?

Upvotes: 1

Views: 173

Answers (1)

Christian-G
Christian-G

Reputation: 2361

Use to_date which will get rid of all time information, effectively leaving you with just the days.

User.where('created_at >= ?', 1.week.ago).group_by { |u| u.created_at.to_date }.map { |_,v| [_, v.length]}.to_h

OR, if you don't care about the time portion, you could use this:

User.where('created_at >= ?', 1.week.ago).group(:created_at).count

This will get you a hash with the created_at and count.

Upvotes: 1

Related Questions