Permalink
Browse files

Merge pull request #7286 from kennyj/fix_7191

Fix #7191. Remove unnecessary transaction when assigning has_one associations.
Conflicts:
	activerecord/test/cases/associations/has_one_associations_test.rb
  • Loading branch information...
1 parent ae2383d commit 2e000743801359c37e80cb2cc68ef5c4721ef780 @rafaelfranca rafaelfranca committed Aug 10, 2012
@@ -8,19 +8,21 @@ def replace(record, save = true)
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
@@ -472,4 +472,17 @@ def test_association_attributes_are_available_to_after_initialize
assert_equal car.id, bulb.attributes_after_initialize['car_id']
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

0 comments on commit 2e00074

Please sign in to comment.