ruby-on-rails – Rails.对集合的特定属性求和

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – Rails.对集合的特定属性求和前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一张发票清单……
@invoices_1_week = Invoice.order("due_date DESC").where("status != 'paid' AND due_date >= ? AND due_date < ?",Date.today,1.week.from_now)

发票模型具有总属性.如何在@ invoice_1_week集合中获得总计的总和?

我知道我可以在这样的视图中做到这一点……

<% week_1_total = 0 %>
<% @invoices_1_week.each do |invoice| %>
  <% week_1_total = week_1_total + invoice.total %>
<% end %>
<%= week_1_total %>

但我想知道是否有更多的Railsy方式.

解决方法

这是一个Rails方式,使用ActiveRecord的sum方法
@invoices_1_week.sum("total")

Here是文档.

原文链接:https://www.f2er.com/ruby/271308.html

猜你在找的Ruby相关文章