我正在尝试通过模型方法构建一个看起来像这样的数组:
[['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
但是,它不会准确返回计数(所有值都为零)。似乎有一些类似的问题,我已经检查过,但似乎无法让它们工作。
有人可以提供帮助(1)让我知道这是否是最好的方法,(2)就上述代码的问题提供一些指导,如果有的话?谢谢!
答案 0 :(得分:7)
如果您愿意,可以将其用作模板
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
这将返回一个哈希,其中日期为关键,计数为值。 (Rails 3.2.x)
答案 1 :(得分: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
答案 2 :(得分: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
答案 3 :(得分: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
答案 4 :(得分:0)
建立在@kiddorails答案,
所以不要向DataBase发出大量请求,从ActiveRecord创建一个哈希
&安培;将组从.group(&#39; created_at&#39;)更改为.group(&#39; DATE(created_at)&#39;)以日期为基础
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