Jerome Jerome - 1 month ago 13
Ruby Question

Rails sum method returns undefined

Generating the following error

undefined method +' for #<Debit


where the controller action defines

@debits = Debit.order("vatunitid ASC").where('unit_id = ? AND folio_id = ?', session[:unit_id], @folio.id).to_a
@adhoc_folios = Folio.order("created_at asc").where(['checkout IS NULL AND unit_id = ? AND id != ?', session[:unit_id], @folio.id]).all
@vatunits = Vatunit.where(['unit_id = ?', session[:unit_id]]).to_a
@rates = @debits.map(&:vatunitid).uniq


and presently in the view (for testing purposes)

@rates.each do |rate|
@debits_for_rate = @debits.select{ |i| i.vatunitid == rate }
@debits_for_rate.count
@debits_for_rate.sum(:amount)


The count instruction returns a proper value

The call to sum is deemed at this point inexistent.

How did this come about and how to overcome it?

Answer

You are doing it in inefficient way by transforming AR into array and then performing Ruby operations while database level calculations could be used instead.

But to solve this particular issue you should go with:

@debits_for_rate.sum(&:amount) 
Comments