@@ -7,6 +7,7 @@ module CounterCache
7
7
8
8
included do
9
9
class_attribute :_counter_cache_columns , instance_accessor : false , default : [ ]
10
+ class_attribute :counter_cached_association_names , instance_writer : false , default : [ ]
10
11
end
11
12
12
13
module ClassMethods
@@ -180,14 +181,26 @@ def decrement_counter(counter_name, id, by: 1, touch: nil)
180
181
def counter_cache_column? ( name ) # :nodoc:
181
182
_counter_cache_columns . include? ( name )
182
183
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
183
196
end
184
197
185
198
private
186
199
def _create_record ( attribute_names = self . attribute_names )
187
200
id = super
188
201
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
191
204
end
192
205
193
206
id
@@ -197,7 +210,8 @@ def destroy_row
197
210
affected_rows = super
198
211
199
212
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 )
201
215
foreign_key = association . reflection . foreign_key . to_sym
202
216
unless destroyed_by_association && destroyed_by_association . foreign_key . to_sym == foreign_key
203
217
association . decrement_counters
@@ -207,11 +221,5 @@ def destroy_row
207
221
208
222
affected_rows
209
223
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
216
224
end
217
225
end
0 commit comments