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.

class Post < ApplicationRecord
 validates_uniqueness_of :title
end

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

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:

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:

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]]

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