Title: Ruby on Rails: Passing string array to highchart function
Tags: javascript;ruby-on-rails;arrays;string;highcharts
Question: I am new to Ruby on Rails and currently working on a graphic with highchart. I need a column chart with categories on the x-axis, where the categories should actually be the users' names (not many users, so that actually does make sense).
Unfortunately, my chart is not showing the string array categories which I define (or retreive from the data) before the chart function is called. Retreiving the names by something as categories: <%= @users.map { |i| i.name } %&gt; does not work either.
Here's a minimal example of what I try to do in show.html.erb:
<% quantities = [1,2,3] %&gt;
<% names = [5,6,7] %&gt;
<% names2 = ['A','B','C'] %&gt;
<div id="container" style="width:60%;height:300px;"&gt;</div&gt;
<script&gt;
$(function () {
$('#container').highcharts({
chart: {
type: 'column'
},
xAxis: {
categories: [ <%= names[0] %&gt;, <%= names[1] %&gt;, "test" ]
},
series: [{
showInLegend: false,
data: <%= quantities %&gt;
}]
});
});
</script&gt;
Using the integer array names for the chart is not a problem, but somehow the string array names2 does not get passed over and the chart is not shown at all when included instead of names. Defining the string array inside the function is not a problem either.
Is there any possibility to pass over a string array or retreive this from the data?
Thanks in advance!
Comment: Can you show the line of code you use when you pass in names2? It'll help rule syntax errors and stuff like that.

Comment: `categories: [ , , "test" ]` for example.        Or I could of course just use `categories: names2` directly, but that doesn't work either

Comment: Sorry, I meant `categories: `  :) - just as with the quantities array

Here is the accepted answer: I think the problem here is that you need to translate it from a ruby array to something that your javascript can handle. You may need to cast the array to json, and also mark it as safe. Something like this:
<%= escape_javascript names2.to_json %&gt;
If escape_javascript doesn't work, you can try raw as well.
Comment for this answer: Perfect!! I already tried `.to_json`, but now with `raw` it finally worked :) Thank you so, so much!!


{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 3, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2018:00:03/02/18', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<javascript><ruby-on-rails><arrays><string><highcharts>', 'Title': 'Ruby on Rails: Passing string array to highchart function', 'ViewCount': 160, 'id': 49072637, 'user_AboutMe': None, 'user_AccountId': 13055927.0, 'user_DisplayName': 'monkey123', 'user_Reputation': 43.0, 'user_Views': 3.0, 'user_id': 9434783.0}}