Rails 3.从数组中获取总数
我正在打印一个包含行总数的表格,但我也希望获得总列数。 以下代码不起作用,而不是总计,它只打印出最后一次迭代的值。
Totals
您的代码不起作用的原因是您的变量是在块中定义的,因此它们被视为块本地变量。 退出块后,这些变量将被标记为清除; 每次迭代都会重新定义这些变量。 在每次迭代中将它们重新分配给0也没有帮助,但这在这里甚至没有生效,因为每次都没有定义变量。
您可以在块之前简单地定义变量,但这仍然非常混乱。 由于Ruby习语和惯例强调清晰且组织良好的代码,我会偏离它,而是分别计算这些数字,可能在你的控制器中。
@totals = { :overall => @shipments.reduce(0) { |total, shipment| total + shipment.invoice.customer_total }, :paid => @shipments.reduce(0) { |total, shipment| total + shipment.invoice.customer_amount_paid }, :balance => @shipments.reduce(0) { |total, shipment| total + shipment.invoice.customer_open_balance } }
然后,您可以在装运表输出后执行以下操作,而不是使用@shipments.last
比较:
Totals <%= number_to_currency @totals[:overall] %> <%= number_to_currency @totals[:paid] %> <%= number_to_currency @totals[:balance] %>
每次循环都将总计设置为零。 在循环之前移动初始化。
你可以使用rubyinject
就像是
@shipments.inject(0) { |sum, shipment| sum + shipment.invoice.customer_total }
或者为了保持代码布局,只需在@shipments.each
循环之外初始化grand_customer_*
对象,因为每次都要重置它们
<% grand_customer_total = 0 grand_customer_amount_paid = 0 grand_customer_open_balance = 0 %> <% @shipments.each do |shipment| %> <%= shipment.file_number %> <%= shipment.shipper.company_name %> <%= shipment.hbl %> <%= shipment.status %> <%= shipment.age %> <%= shipment.invoice.read_issued_at unless shipment.invoice.nil? %> <%= number_to_currency shipment.invoice.customer_total unless shipment.invoice.nil? %> <%= number_to_currency shipment.invoice.customer_amount_paid unless shipment.invoice.nil? %> <%= number_to_currency shipment.invoice.customer_open_balance unless shipment.invoice.nil? %> <% grand_customer_total += shipment.invoice.customer_total grand_customer_amount_paid += shipment.invoice.customer_amount_paid grand_customer_open_balance += shipment.invoice.customer_open_balance %> <% if @shipments.last == shipment %> Totals <%= number_to_currency grand_customer_total %> <%= number_to_currency grand_customer_amount_paid %> <%= number_to_currency grand_customer_open_balance %> <% end %>