Different Ways to Set Attributes in ActiveRecord (Rails 5)
Rails 5 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.
Over the years I came across a really helpful cheat sheet outlining the various methods available for Rails 4 so I figured I’d put together something similar for Rails 5!
Note: This article was written for Rails 5. See cheat sheets for other versions here:
Below is a cheat sheet with in-depth information for Rails 5:
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 |
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 |