Search code examples
elixirecto

How to assign zero to a nil result of Ecto query?


I'm trying to query a transactions list for the total amount and then add that to another amount. However, an error occurs if the user has no transactions. So I put a conditional to assign 0 if the result is nil, but it doesn't carry over

query = from t in Transactions, where: (t.user_id == ^user), select: sum(t.amount)
balance = Repo.one(query) # get value
if is_nil(balance) do
  balancevalue = 0
else 
  balancevalue = Decimal.to_float(balance) # convert value to decimal        
end
total = balancevalue + ^anotherbalance  # add with other value
IO.puts "total: #{total}"

How do I rewrite the condtional so that the query will return zero if the result is nil?


Solution

  • If you want to use elixir is_nil, guard, because you are not sure that balance is valid integer and not nil, you will:

    balancevalue = if is_nil(balance), do: 0, else: Decimal.to_float(balance)