Skip to content

Commit

Permalink
Extract condition as define_autosave_method?
Browse files Browse the repository at this point in the history
  • Loading branch information
kodawill committed Sep 27, 2023
1 parent 41dfff4 commit f1aeefa
Showing 1 changed file with 21 additions and 8 deletions.
29 changes: 21 additions & 8 deletions lib/mongoid/attributes/nested.rb
Original file line number Diff line number Diff line change
Expand Up @@ -83,19 +83,32 @@ 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 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?)
if define_autosave_method?(association)
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']
# Check if autosave method can be defined for the nested association.
#
# @api private
#
# @example Check if to define autosave method.
# Person.define_autosave_method?(metadata)
#
# @param [ Mongoid::Association::Relatable ] association The existing association metadata.
def define_autosave_method?(association)
# autosave method can be defined in one of these cases:
#
# 1. autosave is explicitly set in association
return true if association.autosave?

is_nested = !!nested_attributes[association.name.to_s + '_attributes']

# 2. association is referenced (non-embedded), and
# a. autosave is not set in association, or
# b. association is defined as nested attributes via `accepts_nested_attributes_for`
(association.options[:autosave].nil? || is_nested) && !association.embedded?
end
end
end
Expand Down

0 comments on commit f1aeefa

Please sign in to comment.