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

Defined in:
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
# File '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)
            options = persistence_options || {}
            if :belongs_to == .macro
              relation.with(options).save if changed_for_autosave?(relation)
            else
              Array(relation).each { |d| d.with(options).save if changed_for_autosave?(d) }
            end
          end
        end
      end
    end

    after_save save_method, unless: :autosaved?
  end
end