Module: Mongoid::Relations::CounterCache::ClassMethods
- Defined in:
- build/mongoid-6.1/lib/mongoid/relations/counter_cache.rb
Instance Method Summary collapse
-
#decrement_counter(counter_name, id) ⇒ Object
Decrement the counter name from the entries that match the id by one.
-
#increment_counter(counter_name, id) ⇒ Object
Increment the counter name from the entries that match the id by one.
-
#reset_counters(id, *counters) ⇒ Object
Reset the given counter using the .count() query from the db.
-
#update_counters(id, counters) ⇒ Object
Update the given counters by the value factor.
Instance Method Details
#decrement_counter(counter_name, id) ⇒ Object
Decrement the counter name from the entries that match the id by one. This method is used on associations callbacks when counter_cache is enabled
88 89 90 |
# File 'build/mongoid-6.1/lib/mongoid/relations/counter_cache.rb', line 88 def decrement_counter(counter_name, id) update_counters(id, counter_name.to_sym => -1) end |
#increment_counter(counter_name, id) ⇒ Object
Increment the counter name from the entries that match the id by one. This method is used on associations callbacks when counter_cache is enabled
73 74 75 |
# File 'build/mongoid-6.1/lib/mongoid/relations/counter_cache.rb', line 73 def increment_counter(counter_name, id) update_counters(id, counter_name.to_sym => 1) end |
#reset_counters(id, *counters) ⇒ Object
Reset the given counter using the .count() query from the db. This method is usuful in case that a counter got corrupted, or a new counter was added to the collection.
36 37 38 39 40 41 42 43 44 |
# File 'build/mongoid-6.1/lib/mongoid/relations/counter_cache.rb', line 36 def reset_counters(id, *counters) document = id.is_a?(Document) ? id : find(id) counters.each do |name| = reflect_on_association(name) inverse = .klass.reflect_on_association(.inverse) counter_name = inverse.counter_cache_column_name document.update_attribute(counter_name, document.send(name).count) end end |
#update_counters(id, counters) ⇒ Object
Update the given counters by the value factor. It uses the atomic $inc command.
58 59 60 |
# File 'build/mongoid-6.1/lib/mongoid/relations/counter_cache.rb', line 58 def update_counters(id, counters) where(:_id => id).inc(counters) end |