Module: Mongoid::Persistable::Updatable

Included in:
Mongoid::Persistable
Defined in:
build/mongoid-7.3/lib/mongoid/persistable/updatable.rb

Overview

Defines behavior for persistence operations that update existing documents.

Since:

  • 4.0.0

Instance Method Summary collapse

Instance Method Details

#update(attributes = {}) ⇒ true, false Also known as: update_attributes

Update the document attributes in the database.

Examples:

Update the document’s attributes

document.update(:title => "Sir")

Parameters:

  • attributes (Hash) (defaults to: {})

    The attributes to update.

Returns:

  • (true, false)

    True if validation passed, false if not.

Since:

  • 1.0.0



46
47
48
49
# File 'build/mongoid-7.3/lib/mongoid/persistable/updatable.rb', line 46

def update(attributes = {})
  assign_attributes(attributes)
  save
end

#update!(attributes = {}) ⇒ true, false Also known as: update_attributes!

Update the document attributes in the database and raise an error if validation failed.

Examples:

Update the document’s attributes.

document.update!(:title => "Sir")

Parameters:

  • attributes (Hash) (defaults to: {})

    The attributes to update.

Returns:

  • (true, false)

    True if validation passed.

Raises:

  • (Errors::Validations)

    If validation failed.

  • (Errors::Callbacks)

    If a callback returns false.

Since:

  • 1.0.0



66
67
68
69
70
71
72
73
# File 'build/mongoid-7.3/lib/mongoid/persistable/updatable.rb', line 66

def update!(attributes = {})
  result = update_attributes(attributes)
  unless result
    fail_due_to_validation! unless errors.empty?
    fail_due_to_callback!(:update_attributes!)
  end
  result
end

#update_attribute(name, value) ⇒ true, false

Update a single attribute and persist the entire document. This skips validation but fires the callbacks.

Examples:

Update the attribute.

person.update_attribute(:title, "Sir")

Parameters:

  • name (Symbol, String)

    The name of the attribute.

  • value (Object)

    The new value of the attribute.a

Returns:

  • (true, false)

    True if save was successfull, false if not.

Raises:

Since:

  • 2.0.0



28
29
30
31
32
33
34
# File 'build/mongoid-7.3/lib/mongoid/persistable/updatable.rb', line 28

def update_attribute(name, value)
  as_writable_attribute!(name, value) do |access|
    normalized = name.to_s
    process_attribute(normalized, value)
    save(validate: false)
  end
end