Module: ActiveRecordExtensions::DetachedCounterCache::Base::ClassMethods

Defined in:
lib/detached_counter_cache.rb

Instance Method Summary collapse

Instance Method Details

#belongs_to_with_detached_counters(association_id, options = {}) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/detached_counter_cache.rb', line 18

def belongs_to_with_detached_counters(association_id, options = {})
  if add_detached_counter_cache = options.delete(:detached_counter_cache)
    placeholder = DetachedCounterCachePlaceholder.new
    options[:counter_cache] = true
  end

  belongs_to_without_detached_counters(association_id, options)

  if add_detached_counter_cache
    reflection = reflections[association_id.to_s]
    placeholder.reflection = reflection

    klass = reflection.klass
    klass.detached_counter_cache_table_names += [placeholder.detached_counter_cache_table_name]
    klass.detached_counter_cache_placeholders = klass.detached_counter_cache_placeholders.merge(reflection.counter_cache_column.to_s => placeholder)
  end
end

#update_counters_with_detached_counters(id, counters) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/detached_counter_cache.rb', line 36

def update_counters_with_detached_counters(id, counters)
  detached_counters = []
  counters.each do |column_name, value|
    if detached_counter_cache_placeholders.has_key? column_name.to_s
      detached_counters << [detached_counter_cache_placeholders[column_name.to_s], value]
      counters.delete(column_name)
    end
  end

  detached_counters.each do |placeholder, value|
    self.connection.execute(<<-SQL
      INSERT INTO `#{placeholder.detached_counter_cache_table_name}` (#{placeholder.reflection.foreign_key}, count) VALUES (#{id}, #{value})
      ON DUPLICATE KEY UPDATE count = count + #{value}
    SQL
    )
  end

  update_counters_without_detached_counters(id, counters) unless counters.blank?
end