[Chartjs]-Rendering Rails json data in chartjs

1👍

Is this what you want?

You can pass data you get from rails database and insert it into your js code immediately (no need to put it to data attribute in canvas tag).

I see you are using chart js v2 so no need to get context I think.

Also I fixed your code a little bit.

in your js code

$(document).ready(function() {
  var positionsQuantity = <%= raw(@positions.map(&:quantity)) %>;
  var positionName = <%= raw(@positions.map(&:name)) %>;
  var ctx = $('#positions_chart');

  var pieData = {
    labels: positionName,
    datasets: [
    {
      label: "pie labels",
      data: positionsQuantity,
      backgroundColor: "rgba(220,220,220,1)",
      borderColor: "rgba(220,220,220,1)"
    }]
  }

  var chartInstance = new Chart(ctx, {
    type: 'pie',
    data: pieData,
    options: {
      responsive: true
    }
  });
});

Hope it works!

Leave a comment