0

I'm trying to follow this Railscast and create a morris.js line chart for my Enquiry model.

I've grouped the counts using date_trunc into months, but now I'm not quite sure at how to get the X-axis to iterate over months (e.g Jun 2012, Jul 2013) as opposed to by date as in the railscasts notes.

I've tried the range#step method here, but now the graph displays only one date (2012-07-01) without a count and nothing else. Commenting out the .step(1.month) method from the range variable and the graph works fine but the x-axis iterates by 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 do |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) as created_at, count(*) as count")
    enquiries.each_with_object({}) do |enquiry, counts|
      counts[enquiry.created_at.to_date] = enquiry.count
    end
  end
end

How do I get the chart's x-axis to iterate by months (Jun 2013, Jul 2013 ....) instead of by dates?

Community
  • 1
  • 1
Ryan.lay
  • 1,741
  • 2
  • 17
  • 30
  • possible duplicate of [Iterate every month with date objects](http://stackoverflow.com/questions/1724639/iterate-every-month-with-date-objects) – oldergod Jul 11 '13 at 03:26
  • omg I feel like such an idiot! substituting .step(1.month) with .select {|d| d.day == 1} works like a charm. – Ryan.lay Jul 11 '13 at 03:35
  • 2
    irony is, I've actually tried making that solution work for a few hours before I gave up and posted my question. As always, the solution is always just one step ahead. Many thanks – Ryan.lay Jul 11 '13 at 03:39

1 Answers1

3

For anyone else facing the same problem, the solution is 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 do |month|
        {
          created_at: month,
          total_enquiries: total_count[] || 0
      }
    end
  end

The chart's x-axis now iterates by month.

The solution is found here.

I'm still looking for solutions on how the chart dates might display (%b %Y) as opposed to the current format of (yyyy-mm-dd).

Community
  • 1
  • 1
Ryan.lay
  • 1,741
  • 2
  • 17
  • 30