Using rails data collection in .js.erb -


i have books index page shows books using familiair structure:

@books.each |book|  .... end 

on same page want show google chart, using same @books data. chart triggered div:

<div id="chart_div"></div> 

and there chart.js.erb file:

if ($("#chart_div").length > 0){   google.load('visualization', '1.1', {packages: ['corechart']});    google.setonloadcallback(drawchart);   function drawchart() {     var data = google.visualization.arraytodatatable([       ['title', 'author'],       <%- @books.each |book| %>         <%= "['#{book.title}','#{book.author}']," %>       <%- end %>     ]);      var chart = new     google.visualization.areachart(document.getelementbyid('chart_div'));     chart.draw(data, options);   } } 

but returns error undefined methodeach' nil:nilclass, the@booksis not available in the.js.erb` file. how can make books available in javascript? , there better options use data in chart?

javascripts not compiled in context of controller action therefore cannot use instance variables assigned in controller. have possibly 2 options:

  1. load data via ajax server chart.js file
  2. store @book data dom during page rendering eg. json , read chart.js

second option little bit easier explain:

add code page cart:

<script id="chart_data" type="application/json" charset="uff-8>   <%= raw @books.map { |book| [h(book.title), h(book.author)] }.unshift(['title', 'author']).to_json %> </script> 

and draw_chart function in chart.js load data with

var data_array = json.parse($("#chart_data").html()); var data = google.visualization.arraytodatatable(data_array); 

you can remove erb extension chart.js not need compile javascripts erb.

i hope helps bit.


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -