Module: Mongoid::CounterCache::ClassMethods

Defined in:
lib/mongoid_counter_cache.rb

Instance Method Summary collapse

Instance Method Details

#counter_cache(metadata) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/mongoid_counter_cache.rb', line 30

def counter_cache()
  counter_name = "#{[:inverse_of]}_count"

  set_callback(:create, :after) do |document|
    relation = document.send([:name])
    if relation
      relation.inc(counter_name.to_sym, 1) if relation.class.fields.keys.include?(counter_name)
    end
  end
  
  set_callback(:destroy, :after) do |document|
    relation = document.send([:name])
    if relation && relation.class.fields.keys.include?(counter_name)
      relation.inc(counter_name.to_sym, -1) 
    end
  end

end