Module: Mongoid::Relations::CounterCache::ClassMethods

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

Instance Method Summary collapse

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 enable

Examples:

Decrement comments counter

Post.decrement_counter(:comments_count, '50e0edd97c71c17ea9000001')

Parameters:

  • Counter (Symbol)

    cache name

  • The (String)

    id of the object that will be reset.

Since:

  • 3.1.0



72
73
74
# File 'lib/mongoid/relations/counter_cache.rb', line 72

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 enable

Examples:

Increment comments counter

Post.increment_counter(:comments_count, '50e0edd97c71c17ea9000001')

Parameters:

  • Counter (Symbol)

    cache name

  • The (String)

    id of the object that will be reset.

Since:

  • 3.1.0



57
58
59
# File 'lib/mongoid/relations/counter_cache.rb', line 57

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.

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



20
21
22
23
24
25
26
27
28
# File 'lib/mongoid/relations/counter_cache.rb', line 20

def reset_counters(id, *counters)
  object = 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
    object.update_attribute(counter_name, object.send(name).count)
  end
end

#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
# File 'lib/mongoid/relations/counter_cache.rb', line 42

def update_counters(id, counters)
  where(:_id => id).inc(counters)
end