instance method update_columns

Ruby on Rails 8.1.2

Since v4.0.13

Available in: v4.0.13 v4.1.16 v4.2.9 v5.2.8.1 v6.0.6 v6.1.7.10 v7.0.10 v7.1.6 v7.2.3 v8.0.4 v8.1.2

Signature

update_columns(attributes)

Updates the attributes directly in the database issuing an UPDATE SQL statement and sets them in the receiver:

user.update_columns(last_request_at: Time.current)

This is the fastest way to update attributes because it goes straight to the database, but take into account that in consequence the regular update procedures are totally bypassed. In particular:

  • Validations are skipped.

  • Callbacks are skipped.

  • updated_at/updated_on are updated if the touch option is set to true.

  • However, attributes are serialized with the same rules as ActiveRecord::Relation#update_all

This method raises an ActiveRecord::ActiveRecordError when called on new objects, or when at least one of the attributes is marked as readonly.

Parameters

  • :touch option - Touch the timestamp columns when updating.

  • If attribute names are passed, they are updated along with updated_at/updated_on attributes.

Examples

# Update a single attribute.
user.update_columns(last_request_at: Time.current)

# Update with touch option.
user.update_columns(last_request_at: Time.current, touch: true)

Parameters

attributes req
Source
# File activerecord/lib/active_record/persistence.rb, line 619
    def update_columns(attributes)
      raise ActiveRecordError, "cannot update a new record" if new_record?
      raise ActiveRecordError, "cannot update a destroyed record" if destroyed?
      _raise_readonly_record_error if readonly?

      attributes = attributes.transform_keys do |key|
        name = key.to_s
        name = self.class.attribute_aliases[name] || name
        verify_readonly_attribute(name) || name
      end

      touch = attributes.delete("touch")
      if touch
        names = touch if touch != true
        names = Array.wrap(names)
        options = names.extract_options!
        touch_updates = self.class.touch_attributes_with_time(*names, **options)
        attributes.with_defaults!(touch_updates) unless touch_updates.empty?
      end

      update_constraints = _query_constraints_hash
      attributes = attributes.each_with_object({}) do |(k, v), h|
        h[k] = @attributes.write_cast_value(k, v)
        clear_attribute_change(k)
      end

      affected_rows = self.class._update_record(
        attributes,
        update_constraints
      )

      affected_rows == 1
    end

Defined in activerecord/lib/active_record/persistence.rb line 619 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ActiveRecord::Persistence

Type at least 2 characters to search.

↑↓ navigate · open · esc close