update_all vs update in Rails

This article will discuss key differences between update_all and update in Rails.

update_all

update_all is used when a mass update is required and callbacks, validations, and the updated_at column don’t need to be updated. For example, we have a Post model that has title and body attributes.

1
2
3
class Post < ApplicationRecord
 validates_uniqueness_of :title
end

Now run update_all - it will ignore the validation and update the title.

1
2
3
Post.update_all(title: 'Same title')

Post Update All (6.1ms)  UPDATE "posts" SET "title" = $1  [["title", "Same title"]]

Another important thing worth noticing is that it doesn’t update the updated_at column.

update

Another batch updating method is update which is almost opposite from update_all as it runs validations, callbacks, and also updates the updated_at column. With a similar Post model, if we run update:

1
Post.update(title: 'Same title')

This will roll back on the uniqueness validation. But if we remove the validation and run the above method, it will run the following query on every Post instance:

1
Post Update (0.5ms)  UPDATE "posts" SET "title" = $1, "updated_at" = $2 WHERE "posts"."id" = $3  [["title", "Same title with update jdsjds"], ["updated_at", "2020-11-22 19:37:34.021346"], ["id", 3]]

The difference between update_all and update in Rails is that with the update_all method, you can only use it on lists of objects. It’s important to know that update_all will not work on individual objects.

For example, if you have a controller called “users” and then make a call to User.update_all(name: ‘John Smith’), this will result in an error because you are trying to update multiple users at once, which is not possible. The same goes for other objects such as posts or comments as well.

Now you know the differences between update_all and update, and can utilize whichever best suits your needs.