【问题标题】:Adding model data to Charts.js in Rails在 Rails 中将模型数据添加到 Charts.js
【发布时间】:2016-10-16 21:35:47
【问题描述】:

我正在尝试在 Rails 中使用 Chart.js 创建条形图。我需要使用模型数据而不是静态内容。我有一个名为“日志”的表,其属性名为“媒体类型”,我需要在图表栏中显示它,以显示每种媒体类型显示了多少次。我怎样才能做到这一点?我的图表的基本结构如下:

    var ctx0 = document.getElementById("myChart0");
    var myChart0 = new Chart(ctx0, {
    type: 'bar',
    data: {
      labels:       ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
      datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        backgroundColor: [
          'rgba(255, 99, 132, 0.2)',
          'rgba(54, 162, 235, 0.2)',
          'rgba(255, 206, 86, 0.2)',
          'rgba(75, 192, 192, 0.2)',
          'rgba(153, 102, 255, 0.2)',
          'rgba(255, 159, 64, 0.2)'
        ],
        borderColor: [
          'rgba(255,99,132,1)',
          'rgba(54, 162, 235, 1)',
          'rgba(255, 206, 86, 1)',
          'rgba(75, 192, 192, 1)',
          'rgba(153, 102, 255, 1)',
          'rgba(255, 159, 64, 1)'
        ],
        borderWidth: 1
      }]
    },
    options: {
      scales: {
        yAxes: [{
          ticks: {
            beginAtZero:true
          }
        }]
      }
    }
    });

那里的内容只是静态和示例。我需要用模型中的内容替换它。

【问题讨论】:

    标签: javascript ruby-on-rails charts erb chart.js


    【解决方案1】:

    你已经或多或少地自己回答了。您需要做的就是插入这些值。几年前我们不得不从事类似的任务 - Windhager Brennstoff Barometer

    这是作为参考的代码 - 它应该可以帮助您将相同的原则应用于您从事的任何任务:

    控制器:

    class FuelBarometersController < ApplicationController
      ...
    
      def show
        # Austria
        @austria = FuelBarometer.where("custom_country_id = ?", 1).order(date_entered: :asc)
        # Germany
        @germany = FuelBarometer.where("custom_country_id = ?", 2).order(date_entered: :asc)
        # Swiss
        @swiss = FuelBarometer.where("custom_country_id = ?", 3).order(date_entered: :asc)
        # France
        @france = FuelBarometer.where("custom_country_id = ?", 4).order(date_entered: :asc)
    
        @custom_countries = CustomCountry.where("barometer = ?", true).order(id: :asc)
        add_breadcrumb t('breadcrumb.home'), :welcome_path, :title => t('breadcrumb.home-title')
        add_breadcrumb t('mainnav.useful_information'), :knowledge_path, :options => { :title => t('mainnav.useful_information') }
        add_breadcrumb t('side_menus.knowledge_box.barometer'), :knowledge_barometer_path, :options => { :title => t('side_menus.knowledge_box.barometer') }
        respond_with(@fuel_barometer)
      end
    
    end
    

    以及相应的视图(忽略所有的混乱 - 这是一个匆忙的实现 - 你明白了):

    /Austria
    - tg_at = ((@austria.last.gas - @austria.offset(1).last.gas)/@austria.offset(1).last.gas)
    - to_at = ((@austria.last.heizoel - @austria.offset(1).last.heizoel)/@austria.offset(1).last.heizoel)
    - tp_at = ((@austria.last.pellets - @austria.offset(1).last.pellets)/@austria.offset(1).last.pellets)
    
    /Germany
    - tg_de = ((@germany.last.gas - @germany.offset(1).last.gas)/@germany.offset(1).last.gas)
    - to_de = ((@germany.last.heizoel - @germany.offset(1).last.heizoel)/@germany.offset(1).last.heizoel)
    - tp_de = ((@germany.last.pellets - @germany.offset(1).last.pellets)/@germany.offset(1).last.pellets)
    
    /Swiss
    - tg_ch = ((@swiss.last.gas - @swiss.offset(1).last.gas)/@swiss.offset(1).last.gas)
    - to_ch = ((@swiss.last.heizoel - @swiss.offset(1).last.heizoel)/@swiss.offset(1).last.heizoel)
    - tp_ch = ((@swiss.last.pellets - @swiss.offset(1).last.pellets)/@swiss.offset(1).last.pellets)
    
    /France
    - tg_fr = ((@france.last.gas - @france.offset(1).last.gas)/@france.offset(1).last.gas)
    - to_fr = ((@france.last.heizoel - @france.offset(1).last.heizoel)/@france.offset(1).last.heizoel)
    - tp_fr = ((@france.last.pellets - @france.offset(1).last.pellets)/@france.offset(1).last.pellets)
    
    / Setting default value for select
    - default_value = 0
    - if I18n.locale == :at
      - default_value = 1
    - elsif I18n.locale == :de
      - default_value = 2
    - elsif (I18n.locale == :ch_de) || (I18n.locale == :ch_fr)
      - default_value = 3
    - elsif  (I18n.locale == :fr) || (I18n.locale == :int_fr)
      / Default value has been changed from 4 to 1 since france is no longer available
      - default_value = 1
    - else
      - default_value = 1
    
    %div.header
      - myBackground = image_path "headers/" + device_type.to_s + "/blank_header.jpg"
      .container.responsive-header{:style => "background: url(" + myBackground + ")"}
        - if browser.ie8? || browser.ie7?
          %h2.blank_message= t('general.old-browser-message')
        - else
          .row
            .col-md-3.col-sm-12.col-xs-12.mt20.mb20
              / Display the homepage carousel
              %h2= t('fuel_barometers.show.pick-your-country')
              = select_tag "list", options_from_collection_for_select(@custom_countries, "id", "name", default_value), :class => "form-control"
              %h2= t('fuel_barometers.show.price-tendency')
              .col-md-4.col-sm-4.col-xs-4
                %h3.gas.center
                  = t('fuel_barometers.form.gas')
                %p.big_number.gas{:id => "i_gas"}
                  x
                %p.big_number.gas{:id => "a_gas"}
                  x
              .col-md-4.col-sm-4.col-xs-4
                %h3.heizoel.center
                  = t('fuel_barometers.form.heizoel')
                %p.big_number.heizoel{:id => "i_heizoel"}
                  x
                %p.big_number.heizoel{:id => "a_heizoel"}
                  x
              .col-md-4.col-sm-4.col-xs-4
                %h3.pellets.center
                  = t('fuel_barometers.form.pellets')
                %p.big_number.pellets{:id => "i_pellets"}
                  x
                %p.big_number.pellets{:id => "a_pellets"}
                  x
            .col-md-9.col-sm-12.col-xs-12.mt20.mb20
              %canvas#teaser4{:height => ((device_type == :desktop) ? "310" : "610"), :width => "818"}
              %br
              %p.source{:id => "source"}
    
    
    %div.content
      .container
        .col-md-3.col-sm-4.col-xs-12
          = render 'side_menus/knowledge_box'
        .col-md-7.col-sm-8.col-xs-12
          .col-md-12.col-sm-12.col-xs-12
            = t('.content_html')
        .col-md-2.col-sm-12.col-xs-12.topmargin30
          - if I18n.locale == :at
            = render "shared/pellets_supplier"
    
    / Create Labels for Austria
    - a_at = []
    - g_at = []
    - o_at = []
    - p_at = []
    - @austria.each do |at|
      - a_at << at.date_entered.strftime('%-m.%Y')
      - g_at << at.gas
      - o_at << at.heizoel
      - p_at << at.pellets
    
    / Create Labels for Germany
    - d_de = []
    - g_de = []
    - o_de = []
    - p_de = []
    - @germany.each do |de|
      - d_de << de.date_entered.strftime('%-m.%Y')
      - g_de << de.gas
      - o_de << de.heizoel
      - p_de << de.pellets
    
    / Create Labels for Swiss
    - c_ch = []
    - g_ch = []
    - o_ch = []
    - p_ch = []
    - @swiss.each do |ch|
      - c_ch << ch.date_entered.strftime('%-m.%Y')
      - g_ch << ch.gas
      - o_ch << ch.heizoel
      - p_ch << ch.pellets
    
    / Create Labels for France
    - f_fr = []
    - g_fr = []
    - o_fr = []
    - p_fr = []
    - @france.each do |fr|
      - f_fr << fr.date_entered.strftime('%-m.%Y')
      - g_fr << fr.gas
      - o_fr << fr.heizoel
      - p_fr << fr.pellets
    
    :javascript
    
      var selVal = $("#list").val();
    
      var source = document.getElementById("source");
    
      if (selVal == 1) {
        teaser4 = {
        labels : [#{a_at.join(', ')}],
        datasets : [
          {
            label: "Gas",
            fillColor: "rgba(0,0,0,0.0)",
            strokeColor: "rgba(0,148,220,1)",
            pointColor: "rgba(0,148,220,1)",
            pointStrokeColor: "#fff",
            pointHighlightFill: "#fff",
            pointHighlightStroke: "rgba(0,148,220,1)",
            data : [#{g_at.join(',')}]
          },
          {
            label: "Heizöl",
            fillColor: "rgba(0,0,0,0.0)",
            strokeColor: "rgba(222, 0, 24, 1)",
            pointColor: "rgba(222, 0, 24, 1)",
            pointStrokeColor: "#fff",
            pointHighlightFill: "#fff",
            pointHighlightStroke: "rgba(222, 0, 24, 1)",
            data : [#{o_at.join(',')}]
          },
          {
            label: "Pellets",
            fillColor: "rgba(0,0,0,0.0)",
            strokeColor: "rgba(82, 181, 23, 1)",
            pointColor: "rgba(82, 181, 23, 1)",
            pointStrokeColor: "#fff",
            pointHighlightFill: "#fff",
            pointHighlightStroke: "rgba(82, 181, 23, 1)",
            data : [#{p_at.join(',')}]
          }
        ]
        }
    
        var element = document.getElementById("i_gas");
        element.innerHTML = #{'%.2f' % tg_at};
    
        var element = document.getElementById("a_gas");
        if (#{tg_at} < 0)
        {
          element.innerHTML = "<i class=\"fa fa-chevron-circle-down fa-2x\"></i>";
        }
        else if (#{tg_at} > 0)
        {
          element.innerHTML = "<i class=\"fa fa-chevron-circle-up fa-2x\"></i>";
        }
        else
        {
          element.innerHTML = "<i class=\"fa fa-chevron-circle-right fa-2x\"></i>";
        }
    
        var element = document.getElementById("i_pellets");
        element.innerHTML = #{'%.2f' % tp_at};
    
        var element = document.getElementById("a_pellets");
        if (#{tp_at} < 0)
        {
          element.innerHTML = "<i class=\"fa fa-chevron-circle-down fa-2x\"></i>";
        }
        else if (#{tp_at} > 0)
        {
          element.innerHTML = "<i class=\"fa fa-chevron-circle-up fa-2x\"></i>";
        }
        else
        {
          element.innerHTML = "<i class=\"fa fa-chevron-circle-right fa-2x\"></i>";
        }
    
        var element = document.getElementById("i_heizoel");
        element.innerHTML = #{'%.2f' % to_at};
    
        var element = document.getElementById("i_heizoel");
        element.innerHTML = #{'%.2f' % to_at};
    
        var element = document.getElementById("a_heizoel");
        if (#{to_at} < 0)
        {
          element.innerHTML = "<i class=\"fa fa-chevron-circle-down fa-2x\"></i>";
        }
        else if (#{to_at} > 0)
        {
          element.innerHTML = "<i class=\"fa fa-chevron-circle-up fa-2x\"></i>";
        }
        else
        {
          element.innerHTML = "<i class=\"fa fa-chevron-circle-right fa-2x\"></i>";
        }
        source.innerHTML = "<p><em>Quelle: proPellets Austria; Bezugswert für die Berechnung ist der Heizwert der Energieträger, Wirkungsgrade der Heizsysteme nicht berücksichtigt</em></p>"
      } else if (selVal == 2) {
        ...
      }
      ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-14
      相关资源
      最近更新 更多