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

Defined in:
lib/mongoid/relations/auto_save.rb

Instance Method Summary collapse

Instance Method Details

#autosavable?(metadata) ⇒ true, false

Can the autosave be added?

Examples:

Can the autosave be added?

Person.autosavable?()

Parameters:

  • metadata (Metadata)

    The relation metadata.

Returns:

  • (true, false)

    If the autosave is able to be added.

Since:

  • 3.0.0


100
101
102
# File 'lib/mongoid/relations/auto_save.rb', line 100

def autosavable?()
  !autosaved_relations.include?(.name) && !.embedded?
end

#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


70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/mongoid/relations/auto_save.rb', line 70

def autosave()
  if .autosave? && autosavable?()
    autosaved_relations.push(.name)
    set_callback :save, :after, unless: :autosaved? do |document|
      if before_callback_halted?
        self.before_callback_halted = false
      else
        __autosaving__ do
          if document.changed_for_autosave? || relation = document.relation_changed_for_autosave()
            relation = document.__send__(.name) unless relation
            (relation.do_or_do_not(:in_memory) || Array.wrap(relation)).each do |doc|
              doc.save
            end if relation
          end
        end
      end
    end
  end
end