Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails. Sum a specific attribute on a collection

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.

like image 252
leonel Avatar asked May 21 '12 20:05

leonel


1 Answers

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

@invoices_1_week.sum("total")

Here are the docs.

like image 150
Rob Davis Avatar answered Oct 18 '22 17:10

Rob Davis