Getting the number of created_at elements in a day for a given month

I wanted to create a simple diagram of the users that were created in the last month in my application. As basically for every day in the last month, I want to show the number of users registered on that day. What I still have:

# 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 good, but if no user was created on a specific day, he should say "0" and not be absent altogether. How can I scroll every day for the last 30 days and show the number of users created on that day?

+3
source share
3 answers

, :

# 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
+4
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 %>
+8

@floyd , SELECT :

class User < ActiveRecord::Base
  def self.count_new_users_per_day(cutoff_at)
    result = count(:all, :conditions => ["created_at >= ?", cutoff_at],
                         :group => "DATE(created_at)")
    # See http://ruby-doc.org/core-1.8.7/classes/Hash.html#M000163
    result.default = 0
    result
  end
end

:

class UsersController < ActionController::Base
  def index
    @cutoff_at = 30.days.ago.at_midnight
    @new_users_by_date = User.count_new_users_per_day(@cutoff_at)
    @dates = ((@cutoff_at.to_date) .. (@cutoff_at.to_date >> 1))
  end
end

, :

# Chose to move the code to a partial
<%= render :partial => "user_count", :collection => @dates, :as => :date %>

# _user_count.html.erb
<td><%=h date.to_s(:db) %></td>
<td><%= number_with_delimiter(@new_users_by_date[date.to_s(:db)]) %></td>

, SQL , Hash/ResultSet, . Hash , , .

+3

Source: https://habr.com/ru/post/1728059/


All Articles