Difference between update, update_columns, update_column, update_attributes, assign_attributes
Though they look and sound similar, there is significant difference between
these method. Some forcefully update the record where some only set the
attributes but do not send the query to the database
.
Update
update(id, attributes)
Updates an object (or multiple objects) and saves it to the database, if validations pass. The resulting object is returned whether the object was saved successfully to the database or not.
Parameters
id
The id of the record to be updatedattributes
fields with data to be inserted into the record in database
Updating one record
update(user_name: 'Samuel', group: 'expert')
Updating multiple records
update({1: {name: 'shiva', age: 22}, 2: {name: 'hari', age: 23}})
Update Columns update_columns(attributes)
Updates the attributes directly in the database issuing an UPDATE SQL statement and sets them in the receiver:
user.update_columns(name: 'shiva', age: 29)
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 not updated.
This method raises an _ActiveRecord::ActiveRecordError+ when called on new objects, or when at least one of the attributes is marked as readonly.
Update Column update_column(name, value)
Equivalent to update_columns(name => value).
Updates a particular column of a record.
Update Attributes update_attributes(attributes)
Updates all the attributes from the passed-in Hash and saves the record. If the object is invalid, the saving will fail and false will be returned.
Assign Attributes assign_attributes(new_attributes, options = {})
Allows you to set all the attributes for a particular mass-assignment security role by passing in a hash ofattributes with keys matching the attribute names (which again matches the column names) and the role name using the :as option.
To bypass mass-assignment security you can use the :without_protection => true option.