Skip to content

Commit fc234b0

Browse files
committed
Don't load has_one associations during autosave
If the association has been accessed but is not currently loaded, there can't be any changes to save. This was previously fixed for belongs_to associations in a94fe29.
1 parent 55c4ade commit fc234b0

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

activerecord/lib/active_record/autosave_association.rb

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -433,7 +433,9 @@ def save_collection_association(reflection)
433433
# ActiveRecord::Base after the AutosaveAssociation module, which it does by default.
434434
def save_has_one_association(reflection)
435435
association = association_instance_get(reflection.name)
436-
record = association && association.load_target
436+
return unless association && association.loaded?
437+
438+
record = association.load_target
437439
return unless record && !record.destroyed?
438440

439441
autosave = reflection.options[:autosave]

activerecord/test/cases/autosave_association_test.rb

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -285,6 +285,12 @@ def test_not_resaved_when_unchanged
285285
assert_queries_count(4) { firm.save! }
286286
end
287287

288+
def test_should_not_load_the_associated_model
289+
firm = companies(:first_firm)
290+
firm.reset_unvalidated_account
291+
assert_no_queries { firm.save! }
292+
end
293+
288294
def test_callbacks_firing_order_on_create
289295
eye = Eye.create(iris_attributes: { color: "honey" })
290296
assert_equal [true, false], eye.after_create_callbacks_stack
@@ -562,6 +568,12 @@ def test_validation_does_not_validate_non_dirty_association_target
562568
Cpk::Order.create!(id: [1, 2], book: Cpk::Book.new(title: "Book", id: [3, 4]))
563569
end
564570
end
571+
572+
def test_should_not_load_the_associated_model
573+
tagging = taggings(:welcome_general)
574+
tagging.reset_tag
575+
assert_no_queries { tagging.save! }
576+
end
565577
end
566578

567579
class TestDefaultAutosaveAssociationOnAHasManyAssociationWithAcceptsNestedAttributes < ActiveRecord::TestCase
@@ -1048,6 +1060,12 @@ def test_replace_on_duplicated_object
10481060
assert_equal 2, firm.clients.length
10491061
assert_includes firm.clients, Client.find_by_name("New Client")
10501062
end
1063+
1064+
def test_should_not_load_the_associated_model
1065+
firm = companies(:first_firm)
1066+
firm.clients.reset
1067+
assert_no_queries { firm.save! }
1068+
end
10511069
end
10521070

10531071
class TestDefaultAutosaveAssociationOnNewRecord < ActiveRecord::TestCase

0 commit comments

Comments
 (0)