Using the code below, I'm getting a 'nil can't be coerced into Integer' error in Rails.
In my view:
<%= account_totals %>
In a view helper:
def account_totals
if @user.accounts.any?
account_total = 0
@user.accounts.each do |account|
account_total += account.amount
end
account_total
end
end
It's happening because the user has no accounts associated with them, so 'account.percent' is nil. However, I'm first checking to see if the user has any accounts, so this code should not be running if they don't have any accounts.
What's the right way to sum up the total amounts from a user's accounts?
Because some of the account
records have nil
amount, you can convert them to integer
by calling to_i
or to float by to_f
, here account.amount
is returning nil somewhere, do this
account_total += account.amount.to_i
It will resolve the error. But since amount
is a numeric column, you should better set the default value as 0 in migrations at DB level.
or, use sum
account_total = @user.accounts.sum(:amount)
It avoids nil
values and runs a SQL sum
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With