Ruby: totalling amounts
Posted
by
Michael
on Stack Overflow
See other posts from Stack Overflow
or by Michael
Published on 2012-03-26T05:07:16Z
Indexed on
2012/03/26
5:29 UTC
Read the original article
Hit count: 166
ruby-on-rails
|ruby
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.
© Stack Overflow or respective owner