Jack Bracken
Jack Bracken

Reputation: 1283

Count daily signups over n days with Rails ActiveRecord

I need to get the number of signups each day to a rails application over a period of days, and stick them in an array. I currently have a working solution, but I'm sure there's a much better way to do this than having to query the database n times.

My current solution:

signups = []

30.times.do |i|
  day = Time.current - (29.days - i.days)
  todays_signups = User.where(time_joined: day.beginning_of_day..day.end_of_day).count
  signups << todays_signups
end

User.time_joined is a DATETIME column.

I'm sure there's a much better way to do this than hitting the database 30 times, and I'd like to avoid using raw SQL queries if possible.

Upvotes: 0

Views: 168

Answers (1)

Ilya
Ilya

Reputation: 13487

You can do it just via SQL-query:

User.where(time_joined: your_interval).group("DATE(time_joined)").count

Upvotes: 1

Related Questions