Track sum of some fields in the association - "sum_cache"

Viewed 1659

I have tables 'orders' and 'items' with has_many association in the model.

class Order < ActiveRecord::Base
has_many :items

class Item < ActiveRecord::Base
belongs_to :order

Item consists of 'quantity' field, and Order consists of 'quantity_sum' field to track sum of associated items quantity.

For eg:

Order 1 : name='Toms shopping cart', quantity_sum=12
Item 1 : name='T-shirt', quantity=10
Itme 2 : name='Shoes',   quantity=2

I have been looking for a way so that whenever new item is added/edited/deleted, the field 'quantity_sum' of Order gets updated automatically. Presently I have been using after_save method in Item, to update 'quantity_sum' field of Order.

Is there any other neat way of doing this besides 'after_save' ???

Similar to "counter_cache" for tracking count of associations, does rails have support for automatically keeping track of sum of some fields in the association?

Thanks

2 Answers
Related