0

I'm new to RoR and web app development, Im using Rails 3.2.3 and I want to use a ruby array in Highcharts and I'm using Haml in my view files.

I have an array defined in the controller like so:

...
def show
  ...
  @close_array = DailyQuote.where(company_id: @company.id).map(&:closing_price)
end

and I've declared it in my Haml view file.

%body
  - close_array_j = "#{@close_array.inspect}"
  =javascript_include_tag :build_chart
  #container{:style => "min-width: 300px; height: 300px; margin: 0 auto"}

Now I want to use this array, close_array_j, in a Highcharts chart which I've written the code for in a separate file called build_chart.js:

$(function () {
  var chart;
  $(document).ready(function() {
  chart = new Highcharts.Chart({
    chart: {
      renderTo: 'container',
      },
...
    series: [{
      name: 'Closing Price',
      data: $('#close_array_j')
    }]
...

The highcharts chart is being rendered with no data. By the way, I dont know ruby or haml or js very well as you can probably tell...

2 Answers 2

4

You can print the variable like this in HAML

%script
  != "close_array_j = #{@close_array.to_json};"

and then use it in javascript

...
series: [{
    name: 'Closing Price',
    data: close_array_j
}]
...
Sign up to request clarification or add additional context in comments.

Comments

0

The variable assignment you do in your haml view file has no effect. It doesn't automagically apply itself in your javascript file.

You could wrap it up in a script tag. Here's the erb version:

<%= javascript_tag do %>
 close_array_j =  = '<%= j @close_array.to_json %>';
<% end %>

However, there are other, cleaner techniques. One would be to leverage the HTML5 data attribute to embed data such as yours. It's easy to access with Jquery.

I recommend you watch Ryan Bate's screencast on how to pass data to javascript in a variety of ways.

http://railscasts.com/episodes/324-passing-data-to-javascript?view=asciicast

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.