From 774160b9ad6908435bf3485e7ac98633deff76c6 Mon Sep 17 00:00:00 2001 From: Arthur Neves Date: Fri, 28 Feb 2014 17:00:38 -0500 Subject: Remove unnecessary db call when replacing. When replacing a has_many association with the same one, there is no need to do a round-trip to the db to create/and drop a new transaction. [fixes #14220] --- .../lib/active_record/associations/collection_association.rb | 4 +++- .../test/cases/associations/has_many_associations_test.rb | 10 ++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/activerecord/lib/active_record/associations/collection_association.rb b/activerecord/lib/active_record/associations/collection_association.rb index 270871c866..9a2900843e 100644 --- a/activerecord/lib/active_record/associations/collection_association.rb +++ b/activerecord/lib/active_record/associations/collection_association.rb @@ -359,7 +359,9 @@ module ActiveRecord if owner.new_record? replace_records(other_array, original_target) else - transaction { replace_records(other_array, original_target) } + if other_array != original_target + transaction { replace_records(other_array, original_target) } + end end end diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb index a86fb15719..49d3301044 100644 --- a/activerecord/test/cases/associations/has_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_associations_test.rb @@ -1242,6 +1242,16 @@ class HasManyAssociationsTest < ActiveRecord::TestCase assert_equal orig_accounts, firm.accounts end + def test_replace_with_same_content + firm = Firm.first + firm.clients = [] + firm.save + + assert_queries(0, ignore_none: true) do + firm.clients = [] + end + end + def test_transactions_when_replacing_on_persisted good = Client.new(:name => "Good") bad = Client.new(:name => "Bad", :raise_on_save => true) -- cgit v1.2.3