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

前端 未结 3 1950
深忆病人
深忆病人 2021-01-13 19:28

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

3条回答
  •  孤街浪徒
    2021-01-13 20:02

    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] %>
    <%= user[1] %> <% end %>

提交回复
热议问题