Module: ConditionalCounterCache::BelongsTo

Defined in:
lib/conditional_counter_cache/belongs_to.rb

Overview

Overrides ActiveRecord 4.1.4’s counter cache implementation.

Instance Method Summary collapse

Instance Method Details

#add_counter_cache_methods(mixin) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/conditional_counter_cache/belongs_to.rb', line 4

def add_counter_cache_methods(mixin)
  return if mixin.method_defined? :belongs_to_counter_cache_after_create

  mixin.class_eval do
    def belongs_to_counter_cache_after_create(reflection)
      if record = send(reflection.name)
        return unless reflection.has_countable?(self)
        cache_column = reflection.counter_cache_column
        record.class.increment_counter(cache_column, record.id)
        @_after_create_counter_called = true
      end
    end

    def belongs_to_counter_cache_before_destroy(reflection)
      foreign_key = reflection.foreign_key.to_sym
      unless destroyed_by_association && destroyed_by_association.foreign_key.to_sym == foreign_key
        record = send reflection.name
        if record && !self.destroyed?
          return unless reflection.has_countable?(self)
          cache_column = reflection.counter_cache_column
          record.class.decrement_counter(cache_column, record.id)
        end
      end
    end

    def belongs_to_counter_cache_after_update(reflection)
      foreign_key  = reflection.foreign_key
      cache_column = reflection.counter_cache_column

      if (@_after_create_counter_called ||= false)
        @_after_create_counter_called = false
      elsif attribute_changed?(foreign_key) && !new_record? && reflection.constructable?
        return unless reflection.has_countable?(self)
        model           = reflection.klass
        foreign_key_was = attribute_was foreign_key
        foreign_key     = attribute foreign_key

        if foreign_key && model.respond_to?(:increment_counter)
          model.increment_counter(cache_column, foreign_key)
        end
        if foreign_key_was && model.respond_to?(:decrement_counter)
          model.decrement_counter(cache_column, foreign_key_was)
        end
      end
    end
  end
end