In Rails, the methods update, update_columns, update_column, update_attributes,
and assign_attributes may sound similar but have distinct differences.
Some methods directly update the record in the database,
while others only set attributes without sending a query.
Here’s a detailed breakdown:
update(id, attributes) (public)
The update method updates one or more objects and saves them to the database
if validations pass.
The resulting object is returned regardless of whether the object was saved
successfully or not.
Parameters:
id: The ID or an array of IDs to be updated.
attributes: A hash of attributes to set on the object, or an array of hashes.
Examples:
# Updating one record:
Person.update(15, user_name: 'Samuel', group: 'expert')
# Updating multiple records:
people = { 1 => { "first_name" => "David" }, 2 => { "first_name" => "Jeremy" } }
Person.update(people.keys, people.values)
update_columns(attributes) (public)
The update_columns method updates the attributes directly in the database using
an UPDATE SQL statement.
It bypasses regular update procedures, making it the fastest way to update attributes.
However, it comes with several caveats:
Validations are skipped.
Callbacks are skipped.
updated_at/updated_on are not updated.
This method raises an ActiveRecord::ActiveRecordError if called on new objects or
if any of the attributes are marked as read-only.
Example:
user.update_columns(last_request_at: Time.current)
update_column(name, value) (public)
The update_column method is equivalent to update_columns(name => value).
It directly updates a single attribute in the database.
update_attributes(attributes) (public)
The update_attributes method updates all attributes from the passed-in hash
and saves the record. If the object is invalid, the save will fail and false
will be returned.
assign_attributes(new_attributes, options = {}) (public)
The assign_attributes method allows you to set all attributes for a particular
mass-assignment security role by passing in a hash of attributes with keys
matching the attribute names (which match the column names) and the role name
using the :as option. To bypass mass-assignment security,
use the :without_protection => true option.
Examples:
class User < ActiveRecord::Base
attr_accessible :name
attr_accessible :name, :is_admin, as: :admin
end
user = User.new
user.assign_attributes({ name: 'Josh', is_admin: true })
user.name # => "Josh"
user.is_admin? # => false
user = User.new
user.assign_attributes({ name: 'Josh', is_admin: true }, as: :admin)
user.name # => "Josh"
user.is_admin? # => true
user = User.new
user.assign_attributes({ name: 'Josh', is_admin: true }, without_protection: true)
user.name # => "Josh"
user.is_admin? # => true
Source: apidock.com/rails/ActiveRecord
By understanding these differences, you can choose the appropriate
method for your needs and ensure your Rails applications are both efficient and secure.