Method: Mongoid::Relations::CounterCache::ClassMethods#reset_counters

Defined in:
lib/mongoid/relations/counter_cache.rb

#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.

Examples:

Reset the given counter cache

Post.reset_counters('50e0edd97c71c17ea9000001', :comments)

Parameters:

  • The (String)

    id of the object that will be reset.

  • One (Symbol, Array)

    or more counter caches to reset

Since:

  • 3.1.0


34
35
36
37
38
39
40
41
42
# File 'lib/mongoid/relations/counter_cache.rb', line 34

def reset_counters(id, *counters)
  document = id.is_a?(Document) ? id : find(id)
  counters.each do |name|
    meta = reflect_on_association(name)
    inverse = meta.klass.reflect_on_association(meta.inverse)
    counter_name = inverse.counter_cache_column_name
    document.update_attribute(counter_name, document.send(name).count)
  end
end