1

我正在尝试通过模型方法构建一个看起来像这样的数组:

[['3/25/13', 2], ['3/26/13', 1], ['3/27/13', 2]]

其中,日期是字符串,后面的数字是count表/对象的。

我现在有以下模型方法:

def self.weekly_count_array
  counts = count(group: "date(#{table_name}.created_at)", conditions: { created_at: 1.month.ago.to_date..Date.today }, order: "date(#{table_name}.created_at) DESC")
  (1.week.ago.to_date).upto(Date.today) do |x|
    counts[x.to_s] ||= 0
  end
  counts.sort
end

但是,它不会准确返回计数(所有值都为零)。我已经检查过关于 SO 的一些类似问题,但似乎也无法让它们工作。

有人可以帮助(1)让我知道这是否是最好的方法,并且(2)就上述代码可能存在的问题提供一些指导,如果是的话?谢谢!

4

5 回答 5

8

如果您愿意,可以将其用作模板

def self.period_count_array(from = (Date.today-1.month).beginning_of_day,to = Date.today.end_of_day)
  where(created_at: from..to).group('date(created_at)').count
end

这将返回一个哈希值,其中日期为键,计数为值。(轨道 3.2.x)

于 2013-03-27T18:45:04.153 回答
1

也许这就是你想要做的?

class YourActiveRecordModel < ActiveRecord::Base

  def.self weekly_count_array
    records = self.select("COUNT(id) AS record_count, DATE(created_at) AS created")
      .group("DATE(created_at)")
      .where("created_at >= ?", 1.month.ago.to_date) 
      .where("created_at <= ?", Date.current)

    records.each do |x|
      puts x.record_count
      puts x.created # 2013-03-14

      # use I18n.localize(x.created, format: :your_format) 
      # where :your_format is defined in config/locales/en.yml (or other .yml)
    end        
  end
end
于 2013-03-27T18:39:41.873 回答
1

@Aditya Sanghi 的精彩回答。

如果您有确切的要求,您可以选择:

def self.weekly_count_array
  records = select('DATE(created_at) created_at, count(id) as id').group('created_at')
  1.week.ago.to_date.upto(Date.today).map do |d| 
    [d, records.where('DATE(created_at) = ?', d.to_date).first.try(:id) || 0]
  end 
end
于 2013-03-27T19:03:50.500 回答
0

您不需要进程来执行计数。只需为此执行查询。

def self.weekly_count_array
    select("created_at, COUNT(created_at) AS count")
    where(created_at: 1.month.ago.to_date..Date.today)
    group("created_at")
    order("created_at DESC")
end
于 2013-03-27T18:09:49.033 回答
0

建立在@kiddorails 答案之上,

所以不要对数据库提出很多请求,从 ActiveRecord 创建了一个哈希

& 将组从 .group('created_at') 更改为 .group('DATE(created_at)') 以基于日期

def self.weekly_count_array
   # records = select('DATE(created_at) created_at, count(id) as id').group('created_at')
   records_hash = Hash[Download.select('DATE(created_at) created_at, count(id) as id').group('DATE(created_at)').map{|d|[d.created_at, d.id] }]
   1.month.ago.to_date.upto(Date.today).map do |d| 
     [ d, records_hash[d.to_date] || 0 ]
   end 
end
于 2014-04-08T15:29:45.633 回答