1
votes

In Rails, I am querying the database to build a data object for highcharts.

Here is my method from my controller:

def build_data_for_chart
data_array = Array.new
@data_array_as_json = ''

@issues.each { 
  |issue| 
  # returns an array of KeyIssue objects for a given issue
  given_issue_array = KeyIssues.where(issue: issue).all
  a = Array.new

  #loop through each element extracting the timedate and % and add to new array
  given_issue_array.each {
    |entry|
    a.push([entry.datetime.utc.to_date, entry.percentage])
  }

  #build the hash for an individual issue
  temp_hash = {:name => issue, :data => a, :animation => false}

  #add the individual issue and all its data to a final array that contains all the issues.
  data_array.push(temp_hash)
} 

@data_array_as_json = data_array.to_json.html_safe

end

Now I am trying to pull it out in a script in my view.

--- script ---

var data = $.parseJSON(<%= @data_array_as_json %>);

--- script ---

When I print to console, I can see the objects and all their data. Also when I print to html the output looks correct:

"[{\"name\":\"ABORIGINAL & NATIVE TITLE ISSUES\",\"data\":[[\"1993-11-01\",32],[\"1994-06-01\",27],[\"1994-09-01\",33],[\"1995-06-01\",26],[\"1995-09-01\",24],[\"1996-01-01\",20],[\"1996-09-01\",27],[\"1997-01-01\",33],[\"1997-06-01\",36],[\"1997-09-01\",36],[\"1998-01-01\",37],[\"1998-05-01\",33],[\"1998-09-01\",31],[\"1999-05-01\",30],[\"1999-09-01\",28],[\"2000-01-01\",30],[\"2000-05-01\",31],[\"2000-09-01\",34],[\"2001-01-01\",32],[\"2001-06-01\",29],[\"2001-09-01\",28],[\"2002-02-01\",25],[\"2002-06-01\",27],[\"2002-10-01\",25],[\"2003-02-01\",24],[\"2003-06-01\",26],[\"2003-10-01\",27],[\"2004-02-01\",27],[\"2004-06-01\",26],[\"2005-06-01\",30],[\"2006-06-01\",27],[\"2007-06-01\",31],[\"2008-07-01\",29]],\"animation\":false}]"

But when I go to print the data variable it is null (obviously due to not being valid input). What am I messing up?

2

2 Answers

1
votes

FYI..

I needed to wrap it in single quotes.. to make it work..

$.parseJSON(' <%= @data_array_as_json %> ');
0
votes

You can try this:

<script type="text/javascript">
  var data = <%== data_array.to_json %>
</script>