迭代内的数字总和 - rails

时间:2013-08-14 10:04:35

标签: mysql ruby-on-rails loops sum

我有四个团队,每个团队有四个人,我正在尝试为每个团队创建一个图表,@all按团队ID从团队和团队中选择每个人,因此这个循环将产生4次迭代,我试图用这个来总结每个团队的目标,预测和实现数字:

<% @all.each do |a| %>

<div style="width:100%; height: 900px; overflow: auto;">
<br>
<h1>
    <%= Date.today.strftime("%B")  %>
    Sales : <%= a.team.name %>
</h1>

<canvas id="<%= a.team.name %>" height="800" width="1000"></canvas>

<% @main = Individual.find(:all, :conditions => "team_id = '#{a.team_id}'")%>


<script>
    var target = <%= @main.sum(:target) %>;
    var forecast = <%= @main.sum(:forecast) %>;
    var achieved = <%= @main.sum(:achieved) %>;
    var barChartData = {
        labels : ["Target", "Forecast", "Achieved"],
        datasets : [{
            fillColor : "rgba(237,28,36,1)",
            strokeColor : "rgba(237,28,36,1)",
            data : [target, forecast, achieved]
        }]

    }
    var opt = {
        scaleFontFamily : "'Trebuchet'",
        scaleFontSize : 20,
        scaleFontColor : "#fff",

    }

    var myLine = new Chart(document.getElementById("<%= a.team.name %>").getContext("2d")).Bar(barChartData, opt);

</script>

</div>
<% end %>

但我收到此错误undefined method '+' for #<Individual:0x007ff08c8164e0>

如果我分别浏览每个人,它会显示正确的数字,但不会将它们相加。

1 个答案:

答案 0 :(得分:0)

您需要传递proc而不是符号,例如,替换:

@main.sum(:target)

@main.sum(&:target)

将nil值视为0:

@main.sum { |el| el.target.to_f } # use to_f or to_i depending on your data

旁注,请考虑使用gon在js中传递数据。