score:6

Accepted answer

In my opinion requesting the data via AJAX would be the "cleanest" way to do that. You could use jQuery's ajax method to do a GET request to say '/get_data.json' ( which you have to add to your routes.rb), which would return you a JSON with the data.

Something like this.

//your JS file
$.ajax({
            type: "GET",
            contentType: "application/json; charset=utf-8",
            url: '/get_data',
            dataType: 'json',
            data: "{}", 
            success: function (received_data) {
               var div_where_to_draw = "div.mygraph";
               your_d3_function(div_where_to_draw, received_data);
            },
            error: function (result) {
            }
    });
function draw_histogram(where_to_draw, data_to_draw){
  //Your d3js code here
}

(Note that this JS code is a remake of the answer here)

This is how your controller providing the data could look like(note I made a new controller, you might not want to do that and just use a new action in an existing controller):

#app/controllers/data_controller.rb
class DataController < ApplicationController
  def get_data
    respond_to do |format|
      format.json {}
    end
  end
end

And this is how your data could look like:

#app/views/data/get_data.json
[1,1,2,3,5,8,13,21,34,55]

Related Query