Posted over 5 years ago. Visible to the public.

Update a record without updating timestamps

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

Copy
>> user = User.new(name: 'John', email: 'john@example.com') >> user.save => true >> user.updated_at => Wed, 16 Mar 2016 09:12:44 UTC +00:00 >> user.name = "Mark" >> user.save => 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.

Copy
>> user.updated_at => Wed, 16 Mar 2016 09:15:30 UTC +00:00 >> user.name = "Dan" >> user.save(touch: false) => 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.

Copy
>> user = User.new(name: 'Tom', email: 'tom@example.com') >> user.save(touch: false) >> user.updated_at => Mon, 21 Mar 2016 07:04:04 UTC +00:00

Owner of this card:

Avatar
Alexander M
Last edit:
over 5 years ago
by Alexander M
Tags:
Rails-5-0
Posted by Alexander M to Ruby and RoR knowledge base
This website uses short-lived cookies to improve usability.
Accept or learn more