简体   繁体   中英

Ruby on Rails: Passing string array to highchart function

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 } %> categories: <%= @users.map { |i| i.name } %> does not work either.

Here's a minimal example of what I try to do in show.html.erb :

<% quantities = [1,2,3] %>
<% names = [5,6,7] %>
<% names2 = ['A','B','C'] %>

<div id="container" style="width:60%;height:300px;"></div>
<script>
   $(function () {
      $('#container').highcharts({
         chart: {
            type: 'column'
         },
         xAxis: {
            categories: [ <%= names[0] %>, <%= names[1] %>, "test" ]
         },
         series: [{
            showInLegend: false,
            data: <%= quantities %>
         }]
      });
   });
</script> 

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!

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 %>

If escape_javascript doesn't work, you can try raw as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM