Getting count of elements by `created_at` by day in a given month

activerecord, ruby, ruby-on-rails

Solution

I think separation trumps the minimal performance gains here:

# Controller
@users = User.all(:conditions => ["created_at >= ?", Date.today.at_beginning_of_month])

# View
Date.today.at_beginning_of_month.upto(Date.today).each do |date|
  <%= date %>: <%= @users.select{|u| u.created_at == date }.size %>
end

Problem

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?

Original source