Method: Mongoid::Relations::CounterCache::ClassMethods#update_counters

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

#update_counters(id, counters) ⇒ Object

Update the given counters by the value factor. It uses the atomic $inc command.

Examples:

Add 5 to comments counter and remove 2 from likes

counter.
Post.update_counters('50e0edd97c71c17ea9000001',
           :comments_count => 5, :likes_count => -2)

Parameters:

  • The (String)

    id of the object to update.

  • Key (Hash)

    counter_cahe and Value = factor.

Since:

  • 3.1.0



42
43
44
45
46
# File 'lib/mongoid/relations/counter_cache.rb', line 42

def update_counters(id, counters)
  counters.map do |key, value|
    where(:_id => id).inc(key, value)
  end
end