diff options
author | Ryuta Kamizono <kamipo@gmail.com> | 2018-09-20 16:02:12 +0900 |
---|---|---|
committer | Ryuta Kamizono <kamipo@gmail.com> | 2018-09-27 22:59:12 +0900 |
commit | 688c27c8945b924c2f3ae42e86229336f85638b9 (patch) | |
tree | 2fdaee1d805ace61803d05d9a214fabad2a8a0e5 /activerecord/lib/active_record/associations/builder/belongs_to.rb | |
parent | 32da8c107a690987b78096acfef1d6ad26b35617 (diff) | |
download | rails-688c27c8945b924c2f3ae42e86229336f85638b9.tar.gz rails-688c27c8945b924c2f3ae42e86229336f85638b9.tar.bz2 rails-688c27c8945b924c2f3ae42e86229336f85638b9.zip |
Refactor counter cache to extract `decrement_counters_before_last_save` on the belongs_to association
Diffstat (limited to 'activerecord/lib/active_record/associations/builder/belongs_to.rb')
-rw-r--r-- | activerecord/lib/active_record/associations/builder/belongs_to.rb | 43 |
1 files changed, 6 insertions, 37 deletions
diff --git a/activerecord/lib/active_record/associations/builder/belongs_to.rb b/activerecord/lib/active_record/associations/builder/belongs_to.rb index 374247ffec..5e18f0e16f 100644 --- a/activerecord/lib/active_record/associations/builder/belongs_to.rb +++ b/activerecord/lib/active_record/associations/builder/belongs_to.rb @@ -21,47 +21,16 @@ module ActiveRecord::Associations::Builder # :nodoc: add_default_callbacks(model, reflection) if reflection.options[:default] end - def self.define_accessors(mixin, reflection) - super - add_counter_cache_methods mixin - end - - def self.add_counter_cache_methods(mixin) - return if mixin.method_defined? :belongs_to_counter_cache_after_update - - mixin.class_eval do - def belongs_to_counter_cache_after_update(reflection) - if association(reflection.name).target_changed? - if reflection.polymorphic? - model_was = attribute_before_last_save(reflection.foreign_type).try(:constantize) - else - model_was = reflection.klass - end - - foreign_key_was = attribute_before_last_save(reflection.foreign_key) - cache_column = reflection.counter_cache_column - - association(reflection.name).increment_counters - - if foreign_key_was && model_was < ActiveRecord::Base - counter_cache_target(reflection, model_was, foreign_key_was).update_counters(cache_column => -1) - end - end - end - - private - def counter_cache_target(reflection, model, foreign_key) - primary_key = reflection.association_primary_key(model) - model.unscoped.where!(primary_key => foreign_key) - end - end - end - def self.add_counter_cache_callbacks(model, reflection) cache_column = reflection.counter_cache_column model.after_update lambda { |record| - record.belongs_to_counter_cache_after_update(reflection) + association = association(reflection.name) + + if association.target_changed? + association.increment_counters + association.decrement_counters_before_last_save + end } klass = reflection.class_name.safe_constantize |