Permalink
Browse files

Use inheritance chain instead of callbacks to increment counter cache…

…s after create
  • Loading branch information...
1 parent a1e2db2 commit 109d1b2b10ac8b602b6a1a9995c3fd9c63aefa22 @byroot byroot committed Apr 14, 2014
@@ -31,6 +31,14 @@ def updated?
@updated
end
+ def decrement_counters
+ with_cache_name { |name| decrement_counter name }
+ end
+
+ def increment_counters
+ with_cache_name { |name| increment_counter name }
+ end
+
private
def find_target?
@@ -51,13 +59,15 @@ def update_counters(record)
end
end
- def decrement_counters
- with_cache_name { |name| decrement_counter name }
+ def decrement_counter(counter_cache_name)
+ if foreign_key_present?
+ klass.decrement_counter(counter_cache_name, target_id)
+ end
end
- def decrement_counter counter_cache_name
+ def increment_counter(counter_cache_name)
if foreign_key_present?
- klass.decrement_counter(counter_cache_name, target_id)
+ klass.increment_counter(counter_cache_name, target_id)
end
end
@@ -26,16 +26,9 @@ def self.define_accessors(mixin, reflection)
private
def self.add_counter_cache_methods(mixin)
- return if mixin.method_defined? :belongs_to_counter_cache_after_create
+ return if mixin.method_defined? :belongs_to_counter_cache_after_update
mixin.class_eval do
- def belongs_to_counter_cache_after_create(reflection)
- if record = send(reflection.name)
- 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_after_destroy(reflection)
foreign_key = reflection.foreign_key.to_sym
@@ -74,10 +67,6 @@ def belongs_to_counter_cache_after_update(reflection)
def self.add_counter_cache_callbacks(model, reflection)
cache_column = reflection.counter_cache_column
- model.after_create lambda { |record|
- record.belongs_to_counter_cache_after_create(reflection)
- }
-
model.after_destroy lambda { |record|
record.belongs_to_counter_cache_after_destroy(reflection)
}
@@ -131,6 +131,16 @@ def clear_destroy_state
private
+ def _create_record(*)
+ id = super
+
+ each_counter_cached_associations do |association|
+ association.increment_counters
+ end
+
+ id
+ end
+
def destroy_row
affected_rows = super
@@ -139,5 +149,11 @@ def destroy_row
affected_rows
end
+ def each_counter_cached_associations
+ reflections.each do |name, reflection|
+ yield association(name) if reflection.belongs_to? && reflection.counter_cache_column
+ end
+ end
+
end
end

0 comments on commit 109d1b2

Please sign in to comment.