How to add up an array's element with a rails way?

Hi,

I have a method like this, calculating the sub_total in an order model:

def sub_total
result = 0
for item in self.order_items
result += item.price
end
result
end

Is there a rails way to make the method more simple and concise?

Thank you :slight_smile:

–
regards,
Kai Fu

Material Science and Engineering
Huazhong University of Science and Technology
Wuhan Hubei Province P.R.China
E-mail: [email protected]

On Jun 5, 5:01 am, Kevin Fu [email protected] wrote:

end

Is there a rails way to make the method more simple and concise?

Have a peak at the sum method :slight_smile:

Fred

use active record sum method

self.order_items.sum( :price )

-Sandip

On Fri, Jun 5, 2009 at 12:50 PM, Frederick C. <
[email protected]> wrote:

for item in self.order_items
Fred

–
Ruby on Rails Developer