How to update an attribute of record without updating updated_at attribute

Posted by : on

Category : Rails

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



About Ram Laxman Yadav
Ram Laxman Yadav

Senior Software Engineering Professional | Tech Enthusiast | Mentor | Payments | Hospitality | E-Commerce, based in NCR, India

Email : info@ramlaxman.co.in

Website : https://ramlaxman.co.in