sum product of 2 fields ?

I have a db Orders with fields qty and amount, and another linked db
Person that has many Orders. I've been using this to sum all of the
products of qty and amount:

Person.find( person ).orders.inject( 0 ){ |sum, order| sum +
( order.qty * order.amount ) }

Is there another/better way to do this in ActiveRecord?

Many TIA,
Craig

Dudebot wrote:

I have a db Orders with fields qty and amount, and another linked db
Person that has many Orders. I've been using this to sum all of the
products of qty and amount:

Person.find( person ).orders.inject( 0 ){ |sum, order| sum +
( order.qty * order.amount ) }

Is there another/better way to do this in ActiveRecord?

Yes: use the DB's sum() function. ActiveRecord::Calculations could help
you with this if you were summing a single field, but since you're
summing a complex expression, you may have to use raw SQL.

Many TIA,
Craig

Best,

Thanks--I tried a bunch of different incarnations using sum() without
luck, and as I was starting to write raw SQL, I decided it would be
easier to read/more maintainable code just to use Ruby. The db is
small, and performance degradation should not be an issue.

Dudebot wrote:

Thanks--I tried a bunch of different incarnations using sum() without
luck, and as I was starting to write raw SQL, I decided it would be
easier to read/more maintainable code just to use Ruby.

You got it backwards. In this case, doing the calculation on the DB
side will be more maintainable.

The db is
small, and performance degradation should not be an issue.

I wonder. What you're doing now sends lots of unnecessary data from the
DB to the app. Doing it on the DB side will avoid this problem.

I don't see a single good reason for doing the calculation in Ruby in
this case.

On Sep 28, 8:23´┐Żam, Marnen Laibow-Koser <rails-mailing-l...@andreas-

Best,