Take the 2-minute tour ×

I have two models of concern, "Order" and "Kit"; each order has_one :kit

Each "Kit" has a 'cost' value. Within a controller I want to be able to sum together the costs for each 'order'.

Logically I thought this would make sense (but it doesn't work):

@revenue = Order.Kit.sum(:cost) 

Any help would be appreciated. Thanks.


A user creates a new order for a kit which has cost of 20. I would like the @revenue to be of hence value 20 (reflecting 'sales'). When someone else creates a new order for the same kit, @revenue should change to 40.

share|improve this question
so you're saying there is an order_id field in your kit model? –  klochner Feb 10 '10 at 0:25
add comment

3 Answers

up vote 0 down vote accepted

I'm guessing you have it backward, and each order has a kit_id.

. . . in which case you just need the number of orders for a given kit, multiplied by the kit cost:

kit = Kit.find(kit_id)
number_of_orders = Order.count(:all,:conditions=>['kit_id = ?',kit_id])
@revenue = kit.cost*number_of_orders
share|improve this answer
Cheers - its much appreciated! –  vectran Feb 10 '10 at 3:36
add comment

Assuming you don't have two kits per order...

@revenue = Kit.sum(:cost, :conditions => 'order_id is not null')

replacing order_id with your foreign_key

share|improve this answer
Thanks, but it doesn't do quite what I want it to do. It seems to add the cost of all the kits, but I want to add all the costs of the order's kits, Order -> Kit - (cost). I have updated the question to reflect this. –  vectran Feb 9 '10 at 23:51
add comment
kit_costs = order.kits.map { |k| k.cost }
@revenue = kit_costs.inject(0) { |sum, n| sum += n }
share|improve this answer
add comment

Your Answer


