ruby - Rails Iteration by month given range of dates -
i'm trying follow railscast , create morris.js line chart enquiry model.
i've grouped counts using date_trunc
months, i'm not quite sure @ how x-axis iterate on months (e.g jun 2012, jul 2013) opposed date in railscasts notes.
i've tried range#step method here, graph displays 1 date (2012-07-01) without count , nothing else. commenting out .step(1.month)
method range variable , graph works fine x-axis iterates date.
class enquiry < activerecord::base def self.chart_data(start = 1.year.ago) total_count = total_count_by_month(start) start = start.to_date.beginning_of_month today = date.today.beginning_of_month range = (start..today).step(1.month) range.map |month| { created_at: month, total_enquiries: total_count[] || 0 } end end def self.total_count_by_month(start) enquiries = unscoped.where(created_at: start.beginning_of_month..time.now) enquiries = enquiries.group("date_trunc('month', created_at)") enquiries = enquiries.select("date_trunc('month', created_at) created_at, count(*) count") enquiries.each_with_object({}) |enquiry, counts| counts[enquiry.created_at.to_date] = enquiry.count end end end
how chart's x-axis iterate months (jun 2013, jul 2013 ....) instead of dates?
for else facing same problem, solution outlined below:
def self.chart_data(start = 1.year.ago) total_count = total_count_by_month(start) ############################################## start = start.to_date.beginning_of_month today = date.today.beginning_of_month range = (start..today).select {|d| d.day == 1} ############################################## range.map |month| { created_at: month, total_enquiries: total_count[] || 0 } end end
the chart's x-axis iterates month.
the solution found here.
i'm still looking solutions on how chart dates might display (%b %y) opposed current format of (yyyy-mm-dd).
Comments
Post a Comment