Skip to content

Commit 76ccbe6

Browse files
authored
Merge pull request rails#49866 from Shopify/prebuild-counter-cache-association-names-after-schema-load
2 parents f7bc844 + 15deb7e commit 76ccbe6

File tree

2 files changed

+18
-9
lines changed

2 files changed

+18
-9
lines changed

activerecord/lib/active_record/associations/builder/belongs_to.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ def self.add_counter_cache_callbacks(model, reflection)
3838

3939
klass = reflection.class_name.safe_constantize
4040
klass._counter_cache_columns |= [cache_column] if klass && klass.respond_to?(:_counter_cache_columns)
41+
model.counter_cached_association_names |= [reflection.name]
4142
end
4243

4344
def self.touch_record(o, changes, foreign_key, name, touch) # :nodoc:

activerecord/lib/active_record/counter_cache.rb

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ module CounterCache
77

88
included do
99
class_attribute :_counter_cache_columns, instance_accessor: false, default: []
10+
class_attribute :counter_cached_association_names, instance_writer: false, default: []
1011
end
1112

1213
module ClassMethods
@@ -180,14 +181,26 @@ def decrement_counter(counter_name, id, by: 1, touch: nil)
180181
def counter_cache_column?(name) # :nodoc:
181182
_counter_cache_columns.include?(name)
182183
end
184+
185+
def load_schema # :nodoc:
186+
super
187+
188+
association_names = _reflections.filter_map do |name, reflection|
189+
next unless reflection.belongs_to? && reflection.counter_cache_column
190+
191+
name.to_sym
192+
end
193+
194+
self.counter_cached_association_names |= association_names
195+
end
183196
end
184197

185198
private
186199
def _create_record(attribute_names = self.attribute_names)
187200
id = super
188201

189-
each_counter_cached_associations do |association|
190-
association.increment_counters
202+
counter_cached_association_names.each do |association_name|
203+
association(association_name).increment_counters
191204
end
192205

193206
id
@@ -197,7 +210,8 @@ def destroy_row
197210
affected_rows = super
198211

199212
if affected_rows > 0
200-
each_counter_cached_associations do |association|
213+
counter_cached_association_names.each do |association_name|
214+
association = association(association_name)
201215
foreign_key = association.reflection.foreign_key.to_sym
202216
unless destroyed_by_association && destroyed_by_association.foreign_key.to_sym == foreign_key
203217
association.decrement_counters
@@ -207,11 +221,5 @@ def destroy_row
207221

208222
affected_rows
209223
end
210-
211-
def each_counter_cached_associations
212-
_reflections.each do |name, reflection|
213-
yield association(name.to_sym) if reflection.belongs_to? && reflection.counter_cache_column
214-
end
215-
end
216224
end
217225
end

0 commit comments

Comments
 (0)