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



86
87
88
# File 'lib/mongoid/relations/auto_save.rb', line 86

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 is first saved, but not if the parent already exists in the database.

Examples:

Set up autosave options.

Person.autosave()

Parameters:

  • metadata (Metadata)

    The relation metadata.

Since:

  • 2.0.0.rc.1



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/mongoid/relations/auto_save.rb', line 60

def autosave()
  if .autosave? && autosavable?()
    autosaved_relations.push(.name)
    set_callback :save, :after, unless: :autosaved? do |document|
      begin_autosave
      relation = document.send(.name)
      if relation
        (relation.do_or_do_not(:in_memory) || Array.wrap(relation)).each do |doc|
          doc.save
        end
      end
      exit_autosave
    end
  end
end