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

Fix #7191. Remove unnecessary transaction when assigning has_one associations.

This commit is contained in:
kennyj 2012-08-08 02:13:02 +09:00
parent 485e655082
commit 42dd5d9f29
2 changed files with 28 additions and 13 deletions

View file

@ -7,19 +7,21 @@ module ActiveRecord
raise_on_type_mismatch(record) if record
load_target
reflection.klass.transaction do
if target && target != record
remove_target!(options[:dependent]) unless target.destroyed?
end
if record
set_owner_attributes(record)
set_inverse_instance(record)
if owner.persisted? && save && !record.save
nullify_owner_attributes(record)
set_owner_attributes(target) if target
raise RecordNotSaved, "Failed to save the new associated #{reflection.name}."
# If target and record are nil, or target is equal to record,
# we don't need to have transaction.
if (target || record) && target != record
reflection.klass.transaction do
remove_target!(options[:dependent]) if target && !target.destroyed?
if record
set_owner_attributes(record)
set_inverse_instance(record)
if owner.persisted? && save && !record.save
nullify_owner_attributes(record)
set_owner_attributes(target) if target
raise RecordNotSaved, "Failed to save the new associated #{reflection.name}."
end
end
end
end

View file

@ -535,4 +535,17 @@ class HasOneAssociationsTest < ActiveRecord::TestCase
ensure
ActiveRecord::Base.dependent_restrict_raises = option_before
end
def test_has_one_transaction
company = companies(:first_firm)
account = Account.find(1)
company.account # force loading
assert_no_queries { company.account = account }
company.account = nil
assert_no_queries { company.account = nil }
account = Account.find(2)
assert_queries { company.account = account }
end
end