Module: Mongoid::CounterCache::ClassMethods
- Defined in:
- lib/mongoid_countercache/counter_cache.rb
Instance Method Summary collapse
-
#counter_cache(relation_name, options = {}) ⇒ Object
Defines a counter cache on the given relation.
Instance Method Details
#counter_cache(relation_name, options = {}) ⇒ Object
Defines a counter cache on the given relation
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
# File 'lib/mongoid_countercache/counter_cache.rb', line 15 def counter_cache(relation_name, = {}) field_name = ([:field_name] || "#{self.to_s.demodulize.underscore}_count").to_s [:variants].to_a.each do |key,proc| variant_name = "#{field_name}_#{key.to_s.strip}" after_create { update_parent_counter(self.send(relation_name), variant_name, 1, proc) } after_destroy { update_parent_counter(self.send(relation_name), variant_name, -1, proc) } after_update { update_parent_counter(self.send(relation_name), variant_name, 1, proc) } before_update do attributes = self.attributes.dup self.changes.each do |change, vals| self.attributes[change] = vals.first end update_parent_counter(self.send(relation_name), variant_name, -1, proc) self.attributes = attributes end end after_create { update_parent_counter(self.send(relation_name), field_name, 1) } after_destroy { update_parent_counter(self.send(relation_name), field_name, -1) } end |