views:

32

answers:

3

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.


Example:

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.

A: 

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

Matt
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
A: 

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
klochner
Cheers - its much appreciated!
vectran
A: 
kit_costs = order.kits.map { |k| k.cost }
@revenue = kit_costs.inject(0) { |sum, n| sum += n }
arnab