Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord query for a count of new users by day

I want to generate a table showing how many users were created each day.

What's the most efficient or elegant ActiveRecord query to do this?

My (simplified) schema looks like this:

create_table "users" do |t|
  t.datetime "created_at"
  t.string   "name"
end

I want a table that looks like this, where the integers are a count of new users each day:

day              new users
2012-04-01       55
2012-04-02       63
2012-04-03       77
2012-04-04       88

I want to generate the table from an array that looks like this:

data_table.add_rows( [
  [ Date.parse("2012-04-01"), 55],
  [ Date.parse("2012-04-02"), 63],
  [ Date.parse("2012-04-03"), 77],
  [ Date.parse("2012-04-04"), 88]
] )
like image 557
Daniel Kehoe Avatar asked Dec 10 '22 00:12

Daniel Kehoe


1 Answers

You can do this by using the ActiveRecord group method like this:

@users_created_by_day = User.group("DATE(created_at)").count

This will give you a Hash with the dates as the key and the number of users created that day as the value.

like image 183
Paul Simpson Avatar answered Dec 26 '22 04:12

Paul Simpson