Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to conditionally avoid 'nil can't be coerced into Integer' error

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?

like image 569
Tony M Avatar asked Sep 05 '25 03:09

Tony M


1 Answers

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

like image 73
Rajdeep Singh Avatar answered Sep 07 '25 23:09

Rajdeep Singh