How to Use update_all in Rails: Syntax and Examples
In Rails,
update_all updates one or more records in the database directly without running validations or callbacks. Use it with a hash of attributes to update, like Model.where(condition).update_all(attribute: value).Syntax
The update_all method updates all records matching the query with the given attributes in a single SQL statement. It skips validations, callbacks, and does not update timestamps automatically.
Model.where(condition): Selects records to update.update_all(attribute: value): Sets new values for the selected records.
ruby
Model.where(condition).update_all(attribute: value)
Example
This example updates the status of all users who are inactive to 'active' in one query.
ruby
User.where(active: false).update_all(status: 'active')
Output
=> number_of_records_updated (e.g., 5)
Common Pitfalls
Because update_all skips validations and callbacks, it can cause inconsistent data if used carelessly. It also does not update updated_at timestamps automatically, so you must update them manually if needed.
Wrong way (timestamps not updated):
User.where(active: false).update_all(status: 'active')
Right way (manually update timestamps):
User.where(active: false).update_all(status: 'active', updated_at: Time.current)
Quick Reference
| Method | Description |
|---|---|
| update_all(attributes) | Updates all matching records with given attributes in one SQL query. |
| Skips validations | Does not run model validations. |
| Skips callbacks | Does not trigger callbacks like before_save or after_update. |
| Does not update timestamps | You must update timestamps manually if needed. |
| Returns | Number of rows affected. |
Key Takeaways
Use
update_all to update multiple records efficiently in one query.It skips validations and callbacks, so use it only when safe.
Manually update timestamps if you want
updated_at to change.Returns the number of rows updated, not the updated objects.
Always filter records carefully to avoid unwanted updates.