Rails 5 Updating a record without updating timestamps

Abhishek Jain

By Abhishek Jain

on 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.

1
2>> user = User.new(name: 'John', email: 'john@example.com')
3>> user.save
4 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", "john@example.com"]]
5=> true
6
7>> user.updated_at
8=> Wed, 16 Mar 2016 09:12:44 UTC +00:00
9
10>> user.name = "Mark"
11>> user.save
12  UPDATE "users" SET "name" = ?, "updated_at" = ? WHERE "users"."id" = ?  [["name", "Mark"], ["updated_at", 2016-03-16 09:15:30 UTC], ["id", 12]]
13=> true
14
15>> user.updated_at
16=> Wed, 16 Mar 2016 09:15:30 UTC +00:00
17

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.

1
2>> user.updated_at
3=> Wed, 16 Mar 2016 09:15:30 UTC +00:00
4
5>> user.name = "Dan"
6>> user.save(touch: false)
7  UPDATE "users" SET "name" = ? WHERE "users"."id" = ?  [["name", "Dan"], ["id", 12]]
8=> true
9
10>> user.updated_at
11=> Wed, 16 Mar 2016 09:15:30 UTC +00:00
12

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

1
2>> user = User.new(name: 'Tom', email: 'tom@example.com')
3>> user.save(touch: false)
4 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", "tom@example.com"]])
5
6>> user.updated_at
7=> Mon, 21 Mar 2016 07:04:04 UTC +00:00
8

Stay up to date with our blogs. Sign up for our newsletter.

We write about Ruby on Rails, ReactJS, React Native, remote work,open source, engineering & design.