module Mongoid::Relations::Touchable

Public Instance Methods

touch(field = nil) click to toggle source

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.

@example Update the updated_at timestamp.

document.touch

@example Update the updated_at and provided timestamps.

document.touch(:audited)

@note This will not autobuild relations if those options are set.

@param [ Symbol ] field The name of an additional field to update.

@return [ true/false ] false if record is new_record otherwise true.

@since 3.0.0

# File lib/mongoid/relations/touchable.rb, line 23
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))
  end
  run_callbacks(:touch)
  true
end