Method: ActiveRecord::Persistence#update_columns
- Defined in:
- activerecord/lib/active_record/persistence.rb
#update_columns(attributes) ⇒ Object
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_onare not updated. -
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.
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 |
# File 'activerecord/lib/active_record/persistence.rb', line 606 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 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 |