From 5a57cfb14b67b470948cf3aab036842af357b8f7 Mon Sep 17 00:00:00 2001 From: =?utf-8?q?Tarmo=20T=C3=A4nav?= Date: Wed, 10 Jun 2009 16:24:32 +0300 Subject: [PATCH] Don't increment and then decrement the same counter when re-assigning a belongs_to association --- .../associations/belongs_to_association.rb | 2 +- .../associations/belongs_to_associations_test.rb | 4 ++++ 2 files changed, 5 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 c885750..b1309a2 100644 --- a/activerecord/lib/active_record/associations/belongs_to_association.rb +++ b/activerecord/lib/active_record/associations/belongs_to_association.rb @@ -21,7 +21,7 @@ module ActiveRecord else raise_on_type_mismatch(record) - if counter_cache_name && !@owner.new_record? + if counter_cache_name && !@owner.new_record? && (record.id != @owner[@reflection.primary_key_name]) @reflection.klass.increment_counter(counter_cache_name, record.id) @reflection.klass.decrement_counter(counter_cache_name, @owner[@reflection.primary_key_name]) if @owner[@reflection.primary_key_name] end diff --git a/activerecord/test/cases/associations/belongs_to_associations_test.rb b/activerecord/test/cases/associations/belongs_to_associations_test.rb index 13a78a1..6058fef 100644 --- a/activerecord/test/cases/associations/belongs_to_associations_test.rb +++ b/activerecord/test/cases/associations/belongs_to_associations_test.rb @@ -134,6 +134,10 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase r1.topic = Topic.find(t2.id) + assert_no_queries do + r1.topic = t2 + end + assert r1.save assert_equal 0, Topic.find(t1.id).replies.size assert_equal 1, Topic.find(t2.id).replies.size -- 1.6.3.1