I wanted to make a simple chart of users that have been created in the past month in my app. Like basically for each day in the past month I want to show the count of users that have registered that day. What I have so far:
# Controller
@users = User.count(:order => 'DATE(created_at) DESC', :group => ["DATE(created_at)"])
# View
<% @users.each do |user| %>
<%= user[0] %><br />
<%= user[1] %>
<% end %>
# Output
2010-01-10 2
2010-01-08 11
2010-01-07 23
2010-01-02 4
Which is ok, but if no users were created on a given day, it should say "0" instead of not being there at all. How can I loop through each day in the last 30 days and show the count of users created on that day?
date = Date.today-30
# Controller
@users = User.count(:conditions=>["created_at >= ?", date], :order => 'DATE(created_at) DESC', :group => ["DATE(created_at)"])
date.upto(Date.today) do |x|
@users[x.to_s] ||= 0
end
@users.sort!
# View
<% @users.each do |user| %>
<%= user[0] %><br />
<%= user[1] %>
<% end %>
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