1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

Revert "Remove counter_cache_target which is no longer called"

This reverts commit 376ffe0ea2.

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.
This commit is contained in:
Ryuta Kamizono 2018-09-26 23:02:14 +09:00
parent 38fae1f250
commit 52e11e462f
2 changed files with 11 additions and 2 deletions

View file

@ -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

View file

@ -1205,7 +1205,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
reply1 = Reply.create!(title: "re: zoom", content: "speedy quick!")
reply2 = Reply.create!(title: "re: zoom 2", content: "OMG lol!")
assert_queries(6) do
assert_queries(4) do
topic.replies << [reply1, reply2]
end