ActiveRecord的查询,为新用户按天计数 [英] ActiveRecord query for a count of new users by day
问题描述
我要生成一个表格,显示很多用户是如何每天创建的。
什么是最有效的还是高雅的ActiveRecord查询来做到这一点?
我的(简化)架构是这样的:
CREATE_TABLE用户做| T |
t.datetimecreated_at
t.string名
结束
我想看起来像这样,在这里的每一天的整数是新用户的计数表:
天新用户
2012-04-01 55
2012-04-02 63
2012-04-03 77
2012-04-04 88
我想从一个数组看起来像这样生成的表格:
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]
])
您可以通过使用ActiveRecord的做到这一点组
这样的方法:
@users_created_by_day = User.group(DATE(created_at))。算
这会给你的日期为关键和用户数的哈希创建这一天定为值。
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]
] )
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.
这篇关于ActiveRecord的查询,为新用户按天计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!