Ram Laxman Yadav bio photo

Ram Laxman Yadav

Ruby on Rails Developer

Email Twitter LinkedIn Github Stackoverflow

Hello There, We often need to update the records without make any changes in updated_at column. There are many ways to update a record my rails. You can use any of them. Here is an example of how to update a record without updating the updated_at column.

Use update_columns in place of update_attributes

write following code at the place you are updating the record

user.update_columns({name: 'Some name', updated_at: user.updated_at})
# assign updated_at to the record itself while updating the record.

Now you can see the record is updateed but the updated_at value remains the same. This is the fastest way to update a record in rails, but there are some points that needs to be keep in mind if we are using update_columns.

  • This is the fastest way to update attributes because it goes straight to the database, but take into account that in consequence the regular update.
  • Skip all validations
  • All callbacks will be skipped.
  • updated_at/updated_on are not updated.
  • However, attributes are serialized with the same rules as ActiveRecord::Relation#update_all
  • This method raises an ActiveRecord::ActiveRecordError when called on new objects, or when at least one of the attributes is marked as readonly.

Thanks for the reading!!