Module: Mongoid::Persistence::Insertion

Included in:
Operations::Embedded::Insert, Operations::Insert
Defined in:
lib/mongoid/persistence/insertion.rb

Overview

Contains common logic for insertion operations.

Instance Method Summary collapse

Instance Method Details

#prepare(&block) ⇒ Document

Wrap all the common insertion logic for both root and embedded documents and then yield to the block.

Examples:

Execute common insertion logic.

prepare do |doc|
  collection.insert({ :field => "value })
end

Parameters:

  • block (Proc)

    The block to call.

Returns:

Since:

  • 2.1.0



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/mongoid/persistence/insertion.rb', line 21

def prepare(&block)
  document.tap do |doc|
    unless validating? && document.invalid?(:create)
      result = doc.run_callbacks(:save) do
        doc.run_callbacks(:create) do
          yield(doc)
          doc.new_record = false
          doc.reset_persisted_children and true
        end
      end

      unless result == false
        doc.move_changes
        Threaded.clear_options!
      end
    end
  end
end