This blog is part of our Rails 5 series.
update_all method when called on an
ActiveRecord::Relation object updates all the
records without invoking
any callbacks and validations on the records being updated.
Rails 5 supports
update method on an ActiveRecord::Relation object
that runs callbacks and validations on all the records in the relation.
Internally, the above code runs
update method on each
Person record whose country is
Let’s see what happens when
update is called
on a relation in which validations fail on few records.
We have a Note model.
For simplicity let’s add a validation that
note_text field cannot be blank for
first three records.
Now let’s try and update all the records with blank
We can see that failure of validations on records in the relation
does not stop us from updating the valid records.
Also the return value of update on AR Relation
is an array of records in the relation.
We can see that the attributes in these records
hold the values that we wanted to have after the update.
For example in the above mentioned case, we can see
that in the returned array, the records with ids 1, 2 and 3
note_text values even though those records weren’t updated.
Hence we may not be able to rely on the return value to know if the
update is successful on any particular record.
For scenarios where running validations and callbacks is not important and/or
where performance is a concern it is advisable to use
update_all method instead of