Skip to content

Commit

Permalink
Use inheritance chain instead of callbacks to increment counter cache…
Browse files Browse the repository at this point in the history
…s after create
  • Loading branch information
byroot committed Apr 14, 2014
1 parent a1e2db2 commit 109d1b2
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 16 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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?
Expand All @@ -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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
}
Expand Down
16 changes: 16 additions & 0 deletions activerecord/lib/active_record/counter_cache.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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.