Average Shoe size in rails
I have a model Shoe and Purchase which users make to buy a shoe.
each purchase has a size attribute. I am interested to list to my users the average shoe sizes of each Shoe.
Obviously, I can calculate this in real time and cache the results as long as no new purchases has been made. However, I have looked into counter_cache in rails and I realize it's KIND OF similar to what I want to achieve.
I did implement a counter_cache on purchases_count in Shoe. Is there an eleg开发者_如何转开发ant way to add in an extra field, total_sizes and override certain methods in the counter_cache implementation so that when the purchases_counter gets incremented total_sizes will also be updated accordingly?
Thanks!
You could use a callback. E.g.:
class Purchase < ActiveRecord::Base
belongs_to :shoe
after_create :update_total_sizes
def update_total_sizes
self.shoe.total_sizes += self.size
self.shoe.save
end
end
Don't know about overriding methods in the counter cache implementation, but this is pretty clean and straightforward IMO.
精彩评论