Difference between update, update_columns, update_column, update_attributes, assign_attributes

1 Min. Read
Oct 8, 2014

 Rails Ruby Active Record Update update_columns update_column

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

1
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 updated
  • attributes fields with data to be inserted into the record in database

Updating one record

1
update(user_name: 'Samuel', group: 'expert')

Updating multiple records

1
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:

1
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:

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.

You might also like

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.


Read More..


Write To Me

Hire me shiva bhusal
We'll never share your email with anyone else.
I'll never share your email with anyone else.