Rails. Sum a specific attribute on a collection

ruby, ruby-on-rails

Solution

Here's a Rails way, using ActiveRecord's `sum` method:

@invoices_1_week.sum("total")

Here are the docs.

Problem

I have a list of invoices... ``` @invoices_1_week = Invoice.order("due_date DESC").where("status != 'paid' AND due_date >= ? AND due_date < ?", Date.today, 1.week.from_now) ``` The invoices model has a total attribute. How can I get a sum of the totals in the @invoice_1_week collection? I know I can do it in the view like this... ``` <% week_1_total = 0 %> <% @invoices_1_week.each do |invoice| %> <% week_1_total = week_1_total + invoice.total %> <% end %> <%= week_1_total %> ``` But I'm wondering if there is a more Railsy way of doing it.

Original source