【问题标题】:Rails chart.js data coffee scriptRails chart.js 数据咖啡脚本
【发布时间】:2015-04-09 22:16:43
【问题描述】:

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

我需要用我的表销售数据替换静态数据。 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"}

我该如何从这里开始?

谢谢。

【问题讨论】:

    标签: ruby-on-rails database activerecord dynamic chart.js


    【解决方案1】:

    好的,问题是没有数据传递到咖啡脚本中。

    我设法使用 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"}
    

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

    【讨论】:

      【解决方案2】:

      您需要按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

      祝你好运!

      【讨论】:

      • 嗨,拉吉,谢谢。但我还没有。当我使用此代码时,图表不再显示:
      • sales = sale.select(month, SUM(amount) as sum_of_amount) months = orders.collect(month) amts = orders.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 } ] } myNewChart = new Chart($("#canvas").get(0).getContext("2d")).Line(data)
      • 您能否以格式化的方式将此代码添加到您的原始帖子中?
      • 告诉我你传递的monthsamts的最终值
      • 抱歉,我是 rails 和 coffeescript 的新手,但我如何打印输出?
      猜你喜欢
      • 2011-11-08
      • 1970-01-01
      • 1970-01-01
      • 2013-06-19
      • 2017-06-22
      • 1970-01-01
      • 1970-01-01
      • 2013-01-09
      • 1970-01-01
      相关资源
      最近更新 更多