Rails 5 Updating a record without updating timestamps

Abhishek Jain

Abhishek Jain

May 9, 2016

This blog is part of our  Rails 5 series.

In Rails 4.x, when we save an ActiveRecord object then Rails automatically updates fields updated_at or updated_on.


>> user = User.new(name: 'John', email: '[email protected]')
>> user.save
 INSERT INTO "users" ("name", "created_at", "updated_at", "email") VALUES (?, ?, ?, ?)  [["name", "John"], ["created_at", 2016-03-16 09:12:44 UTC], ["updated_at", 2016-03-16 09:12:44 UTC], ["email", "[email protected]"]]
=> true

>> user.updated_at
=> Wed, 16 Mar 2016 09:12:44 UTC +00:00

>> user.name = "Mark"
>> user.save
  UPDATE "users" SET "name" = ?, "updated_at" = ? WHERE "users"."id" = ?  [["name", "Mark"], ["updated_at", 2016-03-16 09:15:30 UTC], ["id", 12]]
=> true

>> user.updated_at
=> Wed, 16 Mar 2016 09:15:30 UTC +00:00

Addition of touch option in ActiveRecord::Base#save

In Rails 5, by passing touch: false as an option to save, we can update the object without updating timestamps. The default option for touch is true.


>> user.updated_at
=> Wed, 16 Mar 2016 09:15:30 UTC +00:00

>> user.name = "Dan"
>> user.save(touch: false)
  UPDATE "users" SET "name" = ? WHERE "users"."id" = ?  [["name", "Dan"], ["id", 12]]
=> true

>> user.updated_at
=> Wed, 16 Mar 2016 09:15:30 UTC +00:00

This works only when we are updating a record and does not work when a record is created.


>> user = User.new(name: 'Tom', email: '[email protected]')
>> user.save(touch: false)
 INSERT INTO "users" ("name", "created_at", "updated_at", "email") VALUES (?, ?, ?, ?)  [["name", "Tom"], ["created_at", 2016-03-21 06:57:23 UTC], ["updated_at", 2016-03-21 06:57:23 UTC], ["email", "[email protected]"]])

>> user.updated_at
=> Mon, 21 Mar 2016 07:04:04 UTC +00:00

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.