Class: Mongoid::Persistence::Update

Inherits:
Command show all
Defined in:
lib/mongoid/persistence/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 inherited from Command

#collection, #document, #klass, #options, #selector, #suppress, #validate

Instance Method Summary collapse

Methods inherited from Command

#initialize

Methods included from Safe

#safe_mode?

Constructor Details

This class inherits a constructor from Mongoid::Persistence::Command

Instance Method Details

#persistObject

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

Example:

Update.persist

Returns:

true or false, depending on validation.



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

def persist
  return false if validate && document.invalid?(:update)
  document.run_callbacks(:save) do
    document.run_callbacks(:update) do
      if update
        document.move_changes
        document._children.each do |child|
          child.move_changes
          child.new_record = false if child.new_record?
        end
        true
      else
        return false
      end
    end
  end
end