From 9798a11c2bc9cef5d66efe5006b607c9d858da76 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Thu, 12 Dec 2013 14:13:51 -0800 Subject: extract methods out of the cache update method --- .../associations/belongs_to_association.rb | 36 +++++++++++++--------- 1 file changed, 22 insertions(+), 14 deletions(-) (limited to 'activerecord') diff --git a/activerecord/lib/active_record/associations/belongs_to_association.rb b/activerecord/lib/active_record/associations/belongs_to_association.rb index 2fd2cba8fc..2c5ad9d1c0 100644 --- a/activerecord/lib/active_record/associations/belongs_to_association.rb +++ b/activerecord/lib/active_record/associations/belongs_to_association.rb @@ -42,20 +42,28 @@ module ActiveRecord return unless counter_cache_name && owner.persisted? - diff_target = if record - different_target?(record) - else - owner[reflection.foreign_key] - end - - if diff_target - if record - record.class.increment_counter(counter_cache_name, record.id) - end - - if foreign_key_present? - klass.decrement_counter(counter_cache_name, target_id) - end + if record + update_with_record record, counter_cache_name + else + update_without_record counter_cache_name + end + end + + def update_with_record record, counter_cache_name + return unless different_target? record + + record.class.increment_counter(counter_cache_name, record.id) + + decrement_counter counter_cache_name + end + + def update_without_record counter_cache_name + decrement_counter counter_cache_name + end + + def decrement_counter counter_cache_name + if foreign_key_present? + klass.decrement_counter(counter_cache_name, target_id) end end -- cgit v1.2.3