在我的模特中,我有:
def self.chart_data(start, slut)
if start.nil?
start = 2.weeks.ago
end
if slut.nil?
slut = Date.today
end
range = start.to_date..(slut.to_date + 1.day)
if start.to_date.beginning_of_month.to_s != slut.to_date.beginning_of_month.to_s
kliks = count(
:group => 'date(month)',
:conditions => { :created_at => range }
)
# CREATE JSON DATA FOR EACH MONTH - PROBLEM HERE
(range).map(&:beginning_of_month).uniq.map(&:to_s).each do |month|
{
created_at: month,
clicks: kliks[month] || 0
}
end
else
kliks = count(
:group => 'date(created_at)',
:conditions => { :created_at => range }
)
#WORKS FINE DATA FOR EACH DAY
(start.to_date..slut.to_date).map do |date|
{
created_at: date.strftime("%F"),
clicks: kliks[date] || 0
}
end
end
end
我在表格中添加了一个列月份。这是created_at列的begin_of_month。这样很容易按月分组。但是,如何为每个月创建JSON数据?目前它不起作用。但是每天的数据都很好。
Klik.chart_data("1/8/2012", "22/9/2012")
<div data-clicks="[{"created_at":"2012-09-08","clicks":0},{"created_at":"2012-09-09","clicks":0},{"created_at":"2012-09-10","clicks":0},{"created_at":"2012-09-11","clicks":0},{"created_at":"2012-09-12","clicks":0},{"created_at":"2012-09-13","clicks":0},{"created_at":"2012-09-14","clicks":0},{"created_at":"2012-09-15","clicks":0},{"created_at":"2012-09-16","clicks":0},{"created_at":"2012-09-17","clicks":0},{"created_at":"2012-09-18","clicks":0},{"created_at":"2012-09-19","clicks":0},{"created_at":"2012-09-20","clicks":0},{"created_at":"2012-09-21","clicks":0},{"created_at":"2012-09-22","clicks":11}]" id="click_chart">
第一个回答结果:
<div data-clicks="[{"created_at":"2012-09-08","clicks":0},{"created_at":"2012-09-09","clicks":0},{"created_at":"2012-09-10","clicks":0},{"created_at":"2012-09-11","clicks":0},{"created_at":"2012-09-12","clicks":0},{"created_at":"2012-09-13","clicks":0},{"created_at":"2012-09-14","clicks":0},{"created_at":"2012-09-15","clicks":0},{"created_at":"2012-09-16","clicks":0},{"created_at":"2012-09-17","clicks":0},{"created_at":"2012-09-18","clicks":0},{"created_at":"2012-09-19","clicks":0},{"created_at":"2012-09-20","clicks":0},{"created_at":"2012-09-21","clicks":0},{"created_at":"2012-09-22","clicks":11}]" id="click_chart">
答案 0 :(得分:1)
尝试使用
(start.to_date..slut.to_date).map(&:beginning_of_month).uniq.map do |date|
{
created_at: date.strftime("%F"),
clicks: kliks[date] || 0
}
end
或
(start.to_date.beginning_of_month..slut.to_date).reject{|date| date.day !=1}.map do |date|
{
created_at: date.strftime("%F"),
clicks: kliks[date] || 0
}
end