Different Ways to Set Attributes in ActiveRecord (Rails 7)
Rails 7 has a rich API that allows you to update your ActiveRecord
objects in several ways.
Some methods have slightly different behavior which can sometimes result in unexpected consequences, so
it’s important to understand their differences.
Note: This cheat sheet is for Rails 7. 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 7:
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_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 | Yes/No1 | No |
User.insert |
No | Yes | No | No | No | No |
User.insert_all |
No | Yes | No | No | Yes/No1 | No |