0

このRailscastに従って、Inquiryモデルのmorris.js折れ線グラフを作成しようとしています。

カウントを月単位でグループ化date_truncしましたが、Railscasts のメモのように日付ごとではなく、X 軸を月単位 (2012 年 6 月、2013 年 7 月など) に繰り返す方法がよくわかりません。

ここで range#step メソッドを試してみましたが、グラフにはカウントなしで 1 つの日付 (2012-07-01) のみが表示され、他には何も表示されません。範囲変数からメソッドをコメントアウトする.step(1.month)と、グラフは正常に機能しますが、x 軸は日付ごとに繰り返されます。

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

グラフの x 軸を日付ではなく月 (2013 年 6 月、2013 年 7 月 ....) で繰り返すにはどうすればよいですか?

4

1 に答える 1

3

同じ問題に直面している他の人のために、解決策の概要を以下に示します。

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

グラフの x 軸が月ごとに繰り返されるようになりました。

解決策はここにあります

現在の形式 (yyyy-mm-dd) ではなく、チャートの日付が (%b %Y) に表示される方法についての解決策をまだ探しています。

于 2013-07-12T02:31:42.900 に答える