提交 dd58cc2e 编写于 作者: R Rafael França 提交者: GitHub

Merge pull request #29765 from lugray/fix_counter_cache

Fix `counter_cache` double increment
......@@ -34,9 +34,7 @@ def belongs_to_counter_cache_after_update(reflection)
foreign_key = reflection.foreign_key
cache_column = reflection.counter_cache_column
if (@_after_create_counter_called ||= false)
@_after_create_counter_called = false
elsif (@_after_replace_counter_called ||= false)
if (@_after_replace_counter_called ||= false)
@_after_replace_counter_called = false
elsif saved_change_to_attribute?(foreign_key) && !new_record?
if reflection.polymorphic?
......
......@@ -182,7 +182,6 @@ def _create_record(*)
each_counter_cached_associations do |association|
if send(association.reflection.name)
association.increment_counters
@_after_create_counter_called = true
end
end
......
......@@ -1171,6 +1171,17 @@ def test_reflect_the_most_recent_change
Column.create! record: record
assert_equal 1, Column.count
end
def test_multiple_counter_cache_with_after_create_update
post = posts(:welcome)
parent = comments(:greetings)
assert_difference "parent.reload.children_count", +1 do
assert_difference "post.reload.comments_count", +1 do
comment = CommentWithAfterCreateUpdate.create(body: "foo", post: post, parent: parent)
end
end
end
end
class BelongsToWithForeignKeyTest < ActiveRecord::TestCase
......
......@@ -77,3 +77,9 @@ class CommentWithDefaultScopeReferencesAssociation < Comment
default_scope -> { includes(:developer).order("developers.name").references(:developer) }
belongs_to :developer
end
class CommentWithAfterCreateUpdate < Comment
after_create do
update_attributes(body: "bar")
end
end
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册