Fix counter_cache double increment bug

This commit is contained in:
Tom Kadwill 2016-04-23 22:14:10 +01:00
parent 39144740e8
commit c3e3577f9d
3 changed files with 14 additions and 0 deletions

@ -61,6 +61,7 @@ def require_counter_update?
def update_counters_on_replace(record)
if require_counter_update? && different_target?(record)
owner.instance_variable_set :@_after_replace_counter_called, true
record.increment!(reflection.counter_cache_column)
decrement_counters
end

@ -33,6 +33,8 @@ def belongs_to_counter_cache_after_update(reflection)
if (@_after_create_counter_called ||= false)
@_after_create_counter_called = false
elsif (@_after_replace_counter_called ||= false)
@_after_replace_counter_called = false
elsif attribute_changed?(foreign_key) && !new_record?
if reflection.polymorphic?
model = attribute(reflection.foreign_type).try(:constantize)

@ -700,6 +700,17 @@ def test_custom_counter_cache
assert_equal 17, reply.replies.size
end
def test_replace_counter_cache
topic = Topic.create(title: "Zoom-zoom-zoom")
reply = Reply.create(title: "re: zoom", content: "speedy quick!")
reply.topic = topic
reply.save
topic.reload
assert_equal 1, topic.replies_count
end
def test_association_assignment_sticks
post = Post.first