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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With