module Mongoid::Relations::AutoSave::ClassMethods

Public Instance Methods

autosave(metadata) click to toggle source

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.

@example Set up autosave options.

Person.autosave(metadata)

@param [ Metadata ] metadata The relation metadata.

@since 2.0.0.rc.1

# File lib/mongoid/relations/auto_save.rb, line 57
def autosave(metadata)
  if metadata.autosave? && !metadata.embedded?
    save_method = :"autosave_documents_for_#{metadata.name}"
    define_method(save_method) do
      if before_callback_halted?
        self.before_callback_halted = false
      else
        __autosaving__ do
          if relation = ivar(metadata.name)
            if :belongs_to == metadata.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