Ruby: totalling amounts
- by Michael
I have a Donation.rb model with an amount column that takes an integer. I want to sum all the individual donations together and show the total on the home page.
In the home_controller, I'm doing @donations = Donation.all and then in the view I do
<% sum = 0 %>
<% @donations.each do |donation| %>
<%= sum += donation.amount if donation.amount? %>
<% end %>
The problem is that this is printing the running sum each time a new donation is added to it. I just want the total sum at the end after they've all been added together.