我不能创建我的每个循环来使用Rails实例的jQuery图表

时间:2017-10-24 21:22:04

标签: jquery ruby-on-rails ruby-on-rails-4

大家好,我正在尝试显示玩家的名字和他赚的钱,不幸的是,如果我输入玩家只是一次只显示一个玩家,我知道我需要创建每个循环,但我不能制作它有效,请你帮我。第一行{y:"<%= result.FTAG%>",标签:"<%= result.HomeTeam%>" }不起作用,但第二行有效但每次都显示相同的名称,因为它不在循环中。如何解决?

<div id="chartContainer" style="height: 370px; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
</form>

<% @results.each do |result| %>
<script>
window.onload = function () {

var chart = new CanvasJS.Chart("chartContainer", {
  animationEnabled: true,
  theme: "light2", // "light1", "light2", "dark1", "dark2"
  title:{
    text: "Top Oil Reserves"
  },
  axisY: {
    title: "Reserves(MMbbl)"
  },
  data: [{        
    type: "column",  
    showInLegend: true, 
    legendMarkerColor: "grey",
    legendText: "MMbbl = one million barrels",
    dataPoints: [      
      { y: "<%= result.FTAG %>", label: "<%= result.HomeTeam %>" },
      { y: 266455,  label: "<%= @player %>" },
      { y: 169709,  label: "<%= @player %>" },
      { y: 158400,  label: "<%= @player %>" },
      { y: 142503,  label: "<%= @player %>" },
      { y: 101500, label: "Kuwait" },
      { y: 97800,  label: "UAE" },
      { y: 80000,  label: "Russia" }
    ]
  }]
});
chart.render();

}
</script> <% end %>

2 个答案:

答案 0 :(得分:1)

您正在每次循环迭代中创建并设置一个新图表,然后将其全部抛弃。如果您查看呈现的HTML源代码,您会看到尽可能多的window.onload() { ....}次调用@results中的条目。

您真的只想循环遍历@results一次数组并构建一个内部数据点有效负载 - 您只需将其传递一次到图表构建函数。

这样的事情:

<script>
var datapoints = [];
<% @results.each do |result| %>
  datapoints.push({y: "<%= result.FTAG %>", label: "<%= result.HomeTeam %>"});
<% end %>
</script>

<script>
window.onload = function () {

var chart = new CanvasJS.Chart("chartContainer", {
  animationEnabled: true,
  theme: "light2", // "light1", "light2", "dark1", "dark2"
  title:{
    text: "Top Oil Reserves"
  },
  axisY: {
    title: "Reserves(MMbbl)"
  },
  data: [{        
    type: "column",  
    showInLegend: true, 
    legendMarkerColor: "grey",
    legendText: "MMbbl = one million barrels",
    dataPoints: datapoints
  }]
});
chart.render();

}
</script>

答案 1 :(得分:0)

看起来你没有正确设置@player。没有看到控制器,我不能肯定地说,但我猜你想要result.HomeTeam.players而不是@player。