Nil being coerced to float

I was doing this:

     @line_items = LineItems.find_all_by_invoice_id(params[:id])
     @payments = Payments.find_all_by_invoice_id(params[:id])

    @total = @line_items.sum{ |item| item.cost }
    @payment_total = @payments.sum{ |payment| payment.value }

    @balance = @total - @payment_total

But when no payments had been made it was coming up with an error when
trying to sum nil, so I did this:

          @payment_total = @payments.sum{ |payment| payment.value }
          @payment_total = 0

So, when the sum failed it returned @payment_total as zero. Now, SURELY,
there's a better way to do this? I'm sure it's obvious when you know
how. Please, enlighten me.

All you need to do to your original code is add a condition to make
sure @payments is not null:
@payment_total = @payments.sum{ |payment| payment.value } unless

Or can payment.value be nil for some payments but not others? Inject
could help in that case:
@payment_totals = @payments.inject(0) { |sum, p| sum + p.value unless
p.value.nil? }

Before running either one of these, you can initialize both @total and
@payment_total to zero:
@total, @payment_total = 0, 0

Hope that helps.

PS: Wonder if you need all of these to be @instance_variables ?

I was doing this:

@line\_items = LineItems\.find\_all\_by\_invoice\_id\(params\[:id\]\)
@payments = Payments\.find\_all\_by\_invoice\_id\(params\[:id\]\)

@total = @line_items.sum{ |item| item.cost }
@payment_total = @payments.sum{ |payment| payment.value }

You can do

@payment_total = @payments.sum{ |payment| payment.value } if @payments


@payment_total = @payments.sum{ |payment| payment.value } rescue 0


@payment_total = @payments ? @payments.sum{ |payment| payment.value } : 0