Rails chart.js 数据咖啡脚本

Rails chart.js data coffee script

我是 rails 的新手。我想用我的数据库 table 中的数据填充 chart.js 图表。我设法用静态数据设置图表。

我需要用 table 销售数据替换静态数据。 sales.month 应表示 x 轴,sales.amount 应表示 y 轴值。

我的 app.js.coffee 看起来像这样:

sales = sale.select(month, SUM(amount) as sum_of_amount)
months = sales.collect(month)
amts = sales.collect(sum_of_amount)

jQuery ->

  data = {
    labels : months,
    datasets : [
      {
        fillColor : "rgba(151,187,205,0.5)",
        strokeColor : "rgba(151,187,205,1)",
        pointColor : "rgba(151,187,205,1)",
        pointStrokeColor : "#fff",
        data : amts
      }
    ]
  }

我的 index.html.haml 看起来像这样,图表显示为静态值。

%canvas#canvas{:height => "400", :width => "600"}

我该如何从这里开始?

谢谢。

您需要按 created_at 月份分组来获取金额总和。

orders = Order.select("DATE_TRUNC('month', created_at) as month, SUM(amount) as sum_of_amount").group("month")
months = orders.collect(&:month)
amts = orders.collect(&:sum_of_amount)

现在您只需要在 labels: 中传递 months 并在 data: 中传递 amts

祝你好运!

好的,问题是没有数据传入 coffeescript。

我设法使用 gem 'gon' 完成了这项工作。这是我所做的:

我的 app.js.coffee 文件如下所示:

jQuery ->
months = $.map( gon.sales, ( val, i ) -> 
            val.month
          );
amts = $.map( gon.sales, ( val, i ) -> 
            val.amount
          );

data = {
  labels : months,
  datasets : [
    {
      fillColor : "rgba(151,187,205,0.5)",
      strokeColor : "rgba(151,187,205,1)",
      pointColor : "rgba(151,187,205,1)",
      pointStrokeColor : "#fff",
      data : amts
    }
  ]
}

在我的 sales_controller.rb 中,我添加了以下内容:

def index
  @sales = Sale.all
  gon.sales = @sales
end

在我的 application.html.haml 布局文件中:

= include_gon

当然在 Gemfile 中:

gem 'gon'

终于在 index.html.haml:

%canvas#canvas{:height => "400", :width => "600"}

现在图表中动态填充了我的销售数据 table。