Module: Mongoid::Relations::AutoSave::ClassMethods

Defined in:
build/mongoid-6.1/lib/mongoid/relations/auto_save.rb

Instance Method Summary collapse

Instance Method Details

#autosave(metadata) ⇒ Object

Set up the autosave behaviour for references many and references one relations. When the option is set to true, these relations will get saved automatically when the parent saved, if they are dirty.

Examples:

Set up autosave options.

Person.autosave()

Parameters:

  • metadata (Metadata)

    The relation metadata.

Since:

  • 2.0.0.rc.1



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'build/mongoid-6.1/lib/mongoid/relations/auto_save.rb', line 58

def autosave()
  if .autosave? && !.embedded?
    save_method = :"autosave_documents_for_#{.name}"
    define_method(save_method) do
      if before_callback_halted?
        self.before_callback_halted = false
      else
        __autosaving__ do
          if relation = ivar(.name)
            if :belongs_to == .macro
              if changed_for_autosave?(relation)
                relation.with(persistence_context) do |_relation|
                  _relation.save
                end
              end
            else
              Array(relation).each do |doc|
                if changed_for_autosave?(doc)
                  doc.with(persistence_context) do |d|
                    d.save
                  end
                end
              end
            end
          end
        end
      end
    end

    after_save save_method, unless: :autosaved?
  end
end