From 41dfff4acc30a73d4ee12577d546cc3761911a46 Mon Sep 17 00:00:00 2001 From: kodawill Date: Wed, 27 Sep 2023 15:15:56 +0800 Subject: [PATCH] Fix autosaving for accepts_nested_attributes_for (only for non-embedded) --- lib/mongoid/attributes/nested.rb | 11 ++++++++++- spec/mongoid/attributes/nested_spec.rb | 12 ++++++++++-- 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/lib/mongoid/attributes/nested.rb b/lib/mongoid/attributes/nested.rb index e57d07460a5..eaf988ec23b 100644 --- a/lib/mongoid/attributes/nested.rb +++ b/lib/mongoid/attributes/nested.rb @@ -83,11 +83,20 @@ def autosave_nested_attributes(association) # marked as autosave despite the fact that the option isn't present. Because the method # Association#autosave? is implemented by checking the autosave option, this is the most # straightforward way to mark it. - if association.autosave? || (association.options[:autosave].nil? && !association.embedded?) + # + # If autosave option for association is present but is set as false, then association will + # be checked if it is one of the values of `nested_attributes`. If existing, then association + # will be marked as autosave. + is_nested = is_association_nested_attribute?(association) + if association.autosave? || ((association.options[:autosave].nil? || is_nested) && !association.embedded?) association.options[:autosave] = true Association::Referenced::AutoSave.define_autosave!(association) end end + + def is_association_nested_attribute?(association) + !!nested_attributes[association.name.to_s + '_attributes'] + end end end end diff --git a/spec/mongoid/attributes/nested_spec.rb b/spec/mongoid/attributes/nested_spec.rb index 8943d382e3e..5226c44bfd9 100644 --- a/spec/mongoid/attributes/nested_spec.rb +++ b/spec/mongoid/attributes/nested_spec.rb @@ -49,6 +49,10 @@ context "when autosave is explicitly false" do + let(:account) do + Account.new + end + before do Account.accepts_nested_attributes_for :alerts end @@ -62,8 +66,12 @@ Account.reflect_on_association(:alerts) end - it "keeps autosave set to false" do - expect(association).to_not be_autosave + it "sets autosave to true" do + expect(association).to be_autosave + end + + it "autosaves if the association is not embedded" do + expect(account).to respond_to(:autosave_documents_for_alerts) end end end