In this short tutorial, I’ll show you how to update attributes for ActiveRecord model with:
- Validations are skipped.
- Callbacks are skipped.
updated_onare not updated.
Solutions for both Rails 3 and 4 are provided.
Rails 4 comes with method
update_columns which takes in a hash parameter.
Here is one example how to use it:
At the background, one SQL UPDATE is run and will update both two attributes.
Rails 3 does not have
update_columns method, however there is
update_column method, so we could loop through the parameters like below:
1 2 3
However this solution sucks because there are 2 SQL UPDATE queries involved!
There is a work-around by using
Which only generate only 1 SQL UPDATE query.