Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails + charts.js: How to fill out the Javascript array with value from database?

I would like to use Google visualization charts for displaying information into a graph.

The javascript function for setting value into the graph looks like this:

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]
        ]
    };

    ...
}

My problem is, that I don't know how to fill out array like this with values from database - any tip?

Thanks a lot

like image 969
user984621 Avatar asked Sep 16 '13 15:09

user984621


2 Answers

You will need to embed the javascript in erb. If you name your file chart.js.erb, you will then be able to access Model logic from the javascript through erb. The downside to this method is that the javascript will have to be compiled on every page view, rather then being a statically compiled asset. This can slow down page load time, and an alternative route should be sought if this will be a heavily trafficked page.

Example

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']) %>
    ]
  };

  ...
}

Alternatively, you could create an AJAX request that populates the array on page load through an API controller. This method would allow the asset to be statically compiled, but is a bit more complex.

like image 94
Eugene Avatar answered Nov 19 '22 09:11

Eugene


You can use 'data' attribute:

# 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)} %>
like image 2
ryaz Avatar answered Nov 19 '22 08:11

ryaz