aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib/active_record/associations
diff options
context:
space:
mode:
authorRyuta Kamizono <kamipo@gmail.com>2018-09-26 23:02:14 +0900
committerRyuta Kamizono <kamipo@gmail.com>2018-09-26 23:06:08 +0900
commit52e11e462f6114a4d12225c639c5f501f0ffec7a (patch)
tree6cf1ff6a3a1de741a9248be463f4125d0b581a29 /activerecord/lib/active_record/associations
parent38fae1f2505179123ce59cf19a3f5571559ead35 (diff)
downloadrails-52e11e462f6114a4d12225c639c5f501f0ffec7a.tar.gz
rails-52e11e462f6114a4d12225c639c5f501f0ffec7a.tar.bz2
rails-52e11e462f6114a4d12225c639c5f501f0ffec7a.zip
Revert "Remove `counter_cache_target` which is no longer called"
This reverts commit 376ffe0ea2e59dc51461122210729c05a10fb443. Since 38fae1f, `association.increment_counters` is called without inflated parent target if inverse_of is disabled. In that case, that commit would cause extra queries to inflate parent.
Diffstat (limited to 'activerecord/lib/active_record/associations')
-rw-r--r--activerecord/lib/active_record/associations/belongs_to_association.rb11
1 files changed, 10 insertions, 1 deletions
diff --git a/activerecord/lib/active_record/associations/belongs_to_association.rb b/activerecord/lib/active_record/associations/belongs_to_association.rb
index 11a89366aa..544aec5e8b 100644
--- a/activerecord/lib/active_record/associations/belongs_to_association.rb
+++ b/activerecord/lib/active_record/associations/belongs_to_association.rb
@@ -61,7 +61,11 @@ module ActiveRecord
def update_counters(by)
if require_counter_update? && foreign_key_present?
- reader.increment!(reflection.counter_cache_column, by, touch: reflection.options[:touch])
+ if target && !stale_target?
+ target.increment!(reflection.counter_cache_column, by, touch: reflection.options[:touch])
+ else
+ counter_cache_target.update_counters(reflection.counter_cache_column => by, touch: reflection.options[:touch])
+ end
end
end
@@ -92,6 +96,11 @@ module ActiveRecord
inverse && inverse.has_one?
end
+ def counter_cache_target
+ primary_key = reflection.association_primary_key(klass)
+ klass.unscoped.where!(primary_key => owner._read_attribute(reflection.foreign_key))
+ end
+
def stale_state
result = owner._read_attribute(reflection.foreign_key) { |n| owner.send(:missing_attribute, n, caller) }
result && result.to_s