ActiveRecord query for a count of new users by day

橙三吉。 提交于 2020-01-02 07:22:07

问题


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]
] )

回答1:


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.



来源:https://stackoverflow.com/questions/10375501/activerecord-query-for-a-count-of-new-users-by-day

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!