method
add_counter_cache_callbacks
v4.0.2 -
Show latest stable
-
0 notes -
Class: BelongsTo
- 1.0.0
- 1.1.6
- 1.2.6
- 2.0.3
- 2.1.0
- 2.2.1
- 2.3.8
- 3.0.0
- 3.0.9
- 3.1.0 (0)
- 3.2.1 (0)
- 3.2.8 (0)
- 3.2.13 (0)
- 4.0.2 (0)
- 4.1.8
- 4.2.1
- 4.2.7
- 4.2.9
- 5.0.0.1
- 5.1.7
- 5.2.3
- 6.0.0
- 6.1.3.1
- 6.1.7.7
- 7.0.0
- 7.1.3.2
- 7.1.3.4
- What's this?
add_counter_cache_callbacks(reflection)
public
Hide source
# File activerecord/lib/active_record/associations/builder/belongs_to.rb, line 22 def add_counter_cache_callbacks(reflection) cache_column = reflection.counter_cache_column foreign_key = reflection.foreign_key mixin.class_eval def belongs_to_counter_cache_after_create_for_#{name} if record = #{name} record.class.increment_counter(:#{cache_column}, record.id) @_after_create_counter_called = true end end def belongs_to_counter_cache_before_destroy_for_#{name} unless destroyed_by_association && destroyed_by_association.foreign_key.to_sym == #{foreign_key.to_sym.inspect} record = #{name} if record && !self.destroyed? record.class.decrement_counter(:#{cache_column}, record.id) end end end def belongs_to_counter_cache_after_update_for_#{name} if (@_after_create_counter_called ||= false) @_after_create_counter_called = false elsif self.#{foreign_key}_changed? && !new_record? && defined?(#{name.to_s.camelize}) model = #{name.to_s.camelize} foreign_key_was = self.#{foreign_key}_was foreign_key = self.#{foreign_key} if foreign_key && model.respond_to?(:increment_counter) model.increment_counter(:#{cache_column}, foreign_key) end if foreign_key_was && model.respond_to?(:decrement_counter) model.decrement_counter(:#{cache_column}, foreign_key_was) end end end, __FILE__, __LINE__ + 1 model.after_create "belongs_to_counter_cache_after_create_for_#{name}" model.before_destroy "belongs_to_counter_cache_before_destroy_for_#{name}" model.after_update "belongs_to_counter_cache_after_update_for_#{name}" klass = reflection.class_name.safe_constantize klass.attr_readonly cache_column if klass && klass.respond_to?(:attr_readonly) end