Module: Mongoid::Touchable::InstanceMethods

Included in:
Document
Defined in:
build/mongoid-7.0/lib/mongoid/touchable.rb

Instance Method Summary collapse

Instance Method Details

#touch(field = nil) ⇒ true/false

Note:

This will not autobuild relations if those options are set.

Touch the document, in effect updating its updated_at timestamp and optionally the provided field to the current time. If any belongs_to relations exist with a touch option, they will be updated as well.

Examples:

Update the updated_at timestamp.

document.touch

Update the updated_at and provided timestamps.

document.touch(:audited)

Parameters:

  • field (Symbol) (defaults to: nil)

    The name of an additional field to update.

Returns:

  • (true/false)

    false if record is new_record otherwise true.

Since:

  • 3.0.0



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'build/mongoid-7.0/lib/mongoid/touchable.rb', line 25

def touch(field = nil)
  return false if _root.new_record?
  current = Time.now
  field = database_field_name(field)
  write_attribute(:updated_at, current) if respond_to?("updated_at=")
  write_attribute(field, current) if field

  touches = touch_atomic_updates(field)
  unless touches["$set"].blank?
    selector = atomic_selector
    _root.collection.find(selector).update_one(positionally(selector, touches), session: _session)
  end
  run_callbacks(:touch)
  true
end