Skip to content

Commit

Permalink
Fix autosaving for accepts_nested_attributes_for (only for non-embedded)
Browse files Browse the repository at this point in the history
  • Loading branch information
kodawill committed Sep 27, 2023
1 parent 8f74b68 commit 41dfff4
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
11 changes: 10 additions & 1 deletion lib/mongoid/attributes/nested.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 10 additions & 2 deletions spec/mongoid/attributes/nested_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down

0 comments on commit 41dfff4

Please sign in to comment.