Permalink
Browse files

Use inheritance chain instead of callbacks to increment counter cache…

…s after destroy
  • Loading branch information...
1 parent 109d1b2 commit 7e28b4ed9a1dbd131877cf784aad7ace49073a52 @byroot byroot committed Apr 14, 2014
@@ -30,18 +30,6 @@ def self.add_counter_cache_methods(mixin)
mixin.class_eval do
- def belongs_to_counter_cache_after_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.actually_destroyed?
- cache_column = reflection.counter_cache_column
- record.class.decrement_counter(cache_column, record.id)
- self.clear_destroy_state
- end
- end
- end
-
def belongs_to_counter_cache_after_update(reflection)
foreign_key = reflection.foreign_key
cache_column = reflection.counter_cache_column
@@ -67,10 +55,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_destroy lambda { |record|
- record.belongs_to_counter_cache_after_destroy(reflection)
- }
-
model.after_update lambda { |record|
record.belongs_to_counter_cache_after_update(reflection)
}
@@ -134,17 +134,17 @@ def clear_destroy_state
def _create_record(*)
id = super
- each_counter_cached_associations do |association|
- association.increment_counters
- end
+ each_counter_cached_associations(&:increment_counters)
id
end
def destroy_row
affected_rows = super
- @_actually_destroyed = affected_rows > 0
+ if affected_rows > 0
+ each_counter_cached_associations(&:decrement_counters)
+ end
affected_rows
end

0 comments on commit 7e28b4e

Please sign in to comment.