Class: Mongoid::Persistence::Operations::Update

Inherits:
Object
  • Object
show all
Includes:
Modification, Mongoid::Persistence::Operations
Defined in:
lib/mongoid/persistence/operations/update.rb

Overview

Update is a persistence command responsible for taking a document that has already been saved to the database and saving it, depending on whether or not the document has been modified.

Before persisting the command will check via dirty attributes if the document has changed, if not, it will simply return true. If it has it will go through the validation steps, run callbacks, and set the changed fields atomically on the document. The underlying query resembles the following MongoDB query:

collection.update(
  { "_id" : 1,
  { "$set" : { "field" : "value" },
  false,
  false
);

For embedded documents it will use the positional locator:

collection.update(
  { "_id" : 1, "addresses._id" : 2 },
  { "$set" : { "addresses.$.field" : "value" },
  false,
  false
);

Instance Attribute Summary

Attributes included from Mongoid::Persistence::Operations

#conflicts, #document

Instance Method Summary collapse

Methods included from Modification

#prepare

Methods included from Mongoid::Persistence::Operations

#collection, #deletes, #initialize, insert, #inserts, #notifying_parent?, #options, #parent, remove, #selector, update, #updates, #validating?

Instance Method Details

#persisttrue, false

Persist the document that is to be updated to the database. This will only write changed fields via MongoDB’s $set modifier operation.

Examples:

Update the document.

Update.persist

Returns:

  • (true, false)

    If the save passed.



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/mongoid/persistence/operations/update.rb', line 42

def persist
  prepare do
    unless updates.empty?
      # @todo Durran: This is a temporary fix for #791 until we rewrite
      # the dirty tracking to properly flag a document as changed if
      # only embedded documents have changed.
      if document.respond_to?(:updated_at)
        if document.timestamping? && !document.updated_at_changed?
          document.updated_at = Time.now
        end
      end

      collection.update(selector, updates, options)
      conflicts.each_pair do |key, value|
        collection.update(selector, { key => value }, options)
      end
    end
  end
end