Different Ways to Set Attributes in ActiveRecord (Rails 6)
Rails 6 has a rich API that allows you to update your ActiveRecord
objects in several different ways.
Some methods have slightly different behavior which can sometimes result in unexpected consequences so
it’s important to understand their differences.
Note: This article was written for Rails 6. See cheat sheets for other versions here:
Here’s a cheat sheet highlighting the differences between all the methods available for setting attributes in Rails 6:
Cheat Sheet
Method | Uses Default Accessor | Saves to Database | Runs Validations | Runs Callbacks | Updates updated_at/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 1 |
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 |
User.upsert |
No | Yes | No | No | No | No |
User.upsert_all |
No | Yes | No | No | No | No |
User.insert |
No | Yes | No | No | No | No |
User.insert_all |
No | Yes | No | No | No | No |
-
update_attributes
has been deprecated in favor ofupdate
in Rails 6. ↩