Different ways to set attributes in ActiveRecord

Updated . Posted . Visible to the public. Repeats.

Rails 5 / 6 / 7

Method Uses Default Accessor Saves to Database Runs Validations Runs Callbacks Updates updated_at/updated_on Respects Readonly
attribute= Yes No n/a n/a n/a n/a
attributes= Yes No n/a n/a n/a n/a
assign_attributes Yes No n/a n/a n/a n/a
write_attribute No No n/a n/a n/a n/a
[]= No No n/a n/a n/a n/a
update Yes Yes Yes Yes Yes Yes
update_attribute Yes Yes No Yes Yes Yes
update_attributes Yes Yes Yes Yes Yes Yes
update_column Yes Yes No No No Yes
update_columns Yes Yes No No No Yes
User.update Yes Yes Yes Yes Yes Yes
User.update_all No Yes No No No No

Note that update_attributes is no longer available on Rails 7 (it was only an alias to update before anyway).

Rails 4

Method Uses Default Accessor Saved to Database Validations Callbacks Touches updated_at Readonly check
attribute= Yes No n/a n/a n/a n/a
write_attribute No No n/a n/a n/a n/a
update_attribute Yes Yes No Yes Yes Yes
attributes= Yes No n/a n/a n/a n/a
update Yes Yes Yes Yes Yes Yes
update_column No Yes No No No Yes
update_columns No Yes No No No Yes
User.update Yes Yes Yes Yes Yes Yes
User.update_all No Yes No No No No

Rails 3

Method Uses Default Accessor Mass Assignment Protection Saved to Database Validations
attribute= Yes No No n/a
write_attribute No No No n/a
update_attribute Yes No Yes No
attributes= Yes Yes* No n/a
update_attributes Yes Yes Yes Yes

* Mass Assignment Protection for attributes= is overridable.

Further reading: update_attributes vs. update_attribute in ActiveRecord

Last edit
Arne Hartherz
License
Source code in this card is licensed under the MIT License.
Posted by Emanuel to makandra dev (2016-10-06 07:45)