views:

56

answers:

1

I'm trying to generate a chart in my Rails 3 project using the canvasXpress HTML5 / JavaScript library. Their charting API uses JSON as one of the parameters in their constructor. For example:

new CanvasXpress('canvas', /* JSON here */);

In Rails I'll have a view which renders the chart as part of it's overall output. So, the JavaScript to create the chart will live in the view.

I'm not quite sure how to have Rails generate the JSON the JavaScript needs. Should the JSON be generated in a partial view?

In any case, an example would be nice.

A: 

The route I took in a similar situation was to use two view files (one action) and two requests to render 1st the page, then 2nd the json/data for a graph. (I am using using the wonderful HighCharts library)

In our case ensuring that the page loaded (with all nav, options etc) before the potentially heavy/long data processing required to provide the json was important. It also gave us the benefit of a view just for the JSON.

Controller:

def show
  @graph = Graph.find(id)
  respond_to do |format|
    format.html do
      @variable_needed_for_html_layout = current_user.graphs
    end

    format.js do 
      @data = @graph.process_data
    end
  end
end

The html view(show.html.erb) just renders all the html markup and makes an ajax request(jquery) for the js:

  <script type='text/javascript'>
    $(document).ready(function(){
      $.getScript('<%= graph_path(@graph, :js) -%>');
    });
  </script>
  <div id="highchart"></div>

The js view(show.js.erb) then does all the heavy lifting:

 var chart = new Highcharts.Chart({
    chart: {
      renderTo: 'highchart',
    }
    ...
 });
Alan Peabody
@Alan Thanks for the example. Is there something missing from the JQuery getScript evaluation? Mine is blowing up there...
Edward J. Stembler
@Alan Never mind. I found out via "rake routes" that Rails 3 doesn't need _show_, so mine worked with report_path instead of report_show_path
Edward J. Stembler
Ha, sorry. Probably should have noted that that was Rails 2.3.
Alan Peabody
Actually, I realize that the show was because I had to use a custom route. I change the model name for the example to graph, but it is actually analysis which results in some funky path I can never remember (so I overrode it).
Alan Peabody