Rails + charts.js:如何使用数据库中的值填充Javascript数组?

时间:2013-09-16 15:10:39

标签: javascript jquery ruby-on-rails ruby charts

我想使用Google可视化图表将信息显示到图表中。

用于将值设置到图表中的javascript函数如下所示:

function drawLineChart(chartType) {

    if(chartType == undefined) {
        chartType = 'data1';
    }

    var data = {
        data1: [
            ['Year', 'Sales', 'Expenses'],
            ['2004',  1000,      400],
            ['2005',  1170,      460],
            ['2006',  660,       1120],
            ['2007',  1030,      540]
        ]
    };

    ...
}

我的问题是,我不知道如何使用数据库中的值填写这样的数组 - 任何提示?

非常感谢

3 个答案:

答案 0 :(得分:4)

您需要在erb中嵌入javascript。如果您将文件命名为chart.js.erb,则可以从javascript到erb访问Model逻辑。这种方法的缺点是必须在每个页面视图上编译javascript,而不是静态编译的资产。这可以减慢页面加载时间,如果这将是一个流量很大的页面,应该寻求替代路线。

实施例

chart.js.erb

function drawLineChart(chartType) {

  if(chartType == undefined) {
    chartType = 'data1';
  }

  var data = {
    data1: [
      <%= Model.all.map { |m| [m.year, m.sales, m.expenses] }.unshift(['Year', 'Sales', 'Expenses']) %>
    ]
  };

  ...
}

或者,您可以创建一个AJAX请求,通过API控制器在页面加载时填充数组。这种方法可以静态编译资产,但有点复杂。

答案 1 :(得分:2)

您可以使用'data'属性:

# statistics.js.coffee
jQuery ->
  data = {
    labels : $("#orders_chart").data('dates'),
    datasets : [
      {
        fillColor : "rgba(220,220,220,0.5)",
        strokeColor : "rgba(220,220,220,1)",
        pointColor : "rgba(220,220,220,1)",
        pointStrokeColor : "#fff",
        data : $("#orders_chart").data('orders')
    }
  ]
}

ordersChart = new Chart($("#orders_chart").get(0).getContext("2d")).Line(data)

#statistics/index.html.erb
<%= content_tag 'canvas', '', id: 'orders_chart', width: '1000', height: '600', data: {orders: (Order.week_ago.map &:total), dates: (Order.week_ago.map &:created_at)} %>

答案 2 :(得分:0)

这是我4个月前在我的项目中所做的。密切关注代码。如果您在rails上使用ruby,则可以通过键入&lt;%= @get_data_from_controller_here%&gt;

来从控制器获取数据
<html>
<head>
<title></title>
 <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
      google.load("visualization", "1", {packages:["corechart"]});
      google.setOnLoadCallback(drawChart1);
       google.setOnLoadCallback(drawChart2);
      function drawChart1() {
        var data = google.visualization.arrayToDataTable([

          ['Work',     <%= @get_data_from_controller_here1 %>],
          ['Eat',      <%= @get_data_from_controller_here2 %>],
          ['Commute',  <%= @get_data_from_controller_here3 %>],
          ['Watch TV', <%= @get_data_from_controller_here4 %>],
          ['Sleep',    <%= @get_data_from_controller_here5 %>]
        ]);

        var options = {
          title: 'My Daily Activities',
          chartArea:{left:5, top:20,width:"100%",height:"100%"},
          height: 500,
          width: 500,
          is3D: true
        };

        var chart = new google.visualization.PieChart(document.getElementById('piechart_3d1'));
        chart.draw(data, options);
      }

       function drawChart2() {
        var data = google.visualization.arrayToDataTable([

          ['Work',     <%= @get_data_from_controller_here11 %>],
          ['Eat',      <%= @get_data_from_controller_here22 %>],
          ['Commute',  <%= @get_data_from_controller_here33 %>],
          ['Watch TV', <%= @get_data_from_controller_here44 %>],
          ['Sleep',    <%= @get_data_from_controller_here55 %>]
        ]);

        var options = {
          title: 'My Daily Activities',
          chartArea:{left:5, top:20, width:"100%",height:"100%"},
          height: 500,
          width: 500,
          is3D: true
        };

        var chart = new google.visualization.PieChart(document.getElementById('piechart_3d2'));
        chart.draw(data, options);
      }
    </script>

</head>
<body>
  <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/redmond/jquery-ui.css" rel="stylesheet" type="text/css"/>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>


    <script type="text/javascript">
        $(document).ready(function () {

            $("#OpenDialog").click(function () {
                $('#dialog').css('overflow', 'hidden')
                $("#dialog").dialog({modal: true, 
                                    height: 450, 
                                    width: 850,
                                    resizable: true
                                    });
            });         
        });
    </script>

    <a id="OpenDialog" style="display:inline-block;" href="#" >Click here to open dialog</a>
    <div id="dialog" title="Dialog Title" style="display:none; overlay:hidden">
         <div id="piechart_3d1" style="width: 49%; height:49%; float:left;"></div>
         <div id="piechart_3d2" style="width: 49%; height:49%; float:right;"></div>
    </div>

</body>