Module: Mongoid::Association::Referenced::CounterCache::ClassMethods
Relationships & Source Files | |
Extension / Inclusion / Inheritance Descendants | |
Extended In:
| |
Defined in: | lib/mongoid/association/referenced/counter_cache.rb |
Instance Method Summary
-
#decrement_counter(counter_name, id)
Decrement the counter name from the entries that match the id by one.
-
#increment_counter(counter_name, id)
Increment the counter name from the entries that match the id by one.
-
#reset_counters(id, *counters)
Reset the given counter using the .count() query from the db.
-
#update_counters(id, counters)
Update the given counters by the value factor.
Instance Method Details
#decrement_counter(counter_name, id)
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
# File 'lib/mongoid/association/referenced/counter_cache.rb', line 84
def decrement_counter(counter_name, id) update_counters(id, counter_name.to_sym => -1) end
#increment_counter(counter_name, id)
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
# File 'lib/mongoid/association/referenced/counter_cache.rb', line 71
def increment_counter(counter_name, id) update_counters(id, counter_name.to_sym => 1) end
#reset_counters(id, *counters)
Reset the given counter using the .count() query from the db. This method is useful in case that a counter got corrupted, or a new counter was added to the collection.
# File 'lib/mongoid/association/referenced/counter_cache.rb', line 39
def reset_counters(id, *counters) document = id.is_a?(Document) ? id : find(id) counters.each do |name| relation_association = relations[name] counter_name = relation_association.inverse_association.counter_cache_column_name document.update_attribute(counter_name, document.send(name).count) end end
#update_counters(id, counters)
Update the given counters by the value factor. It uses the atomic $inc command.
# File 'lib/mongoid/association/referenced/counter_cache.rb', line 58
def update_counters(id, counters) where(:_id => id).inc(counters) end