Jordan Schwartz
Jordan Schwartz

Reputation: 105

Update attribute without altering the updated_at field

I'm running rails 3.0. I have a object I want to change a boolean field on but do not want to change the updated_at timestamp. We won't be upgrading rails any time soon, so update_column is out of the question. I'd rather not make model-level changes to support this (like in this post: http://blog.bigbinary.com/2009/01/21/override-automatic-timestamp-in-activerecord-rails.html), since many of objects of this type may have methods called on them at the same time.

Upvotes: 4

Views: 5688

Answers (3)

Subhash Chandra
Subhash Chandra

Reputation: 3265

Rails 5 allows updating 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

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 = User.new(name: 'David', email: '[email protected]')
>> user.save
   INSERT INTO "users" ("name", "created_at", "updated_at", "email") VALUES (?, ?, ?, ?) 
   [["name", "John"], ["created_at", 2016-05-12 05:10:22 UTC], ["updated_at", 2016-05-12 05:10:22 UTC], ["email", "[email protected]"]]
=> true

>> user.updated_at
=> Thu, 12 May 2016 05:10:22 UTC +00:00
>> user.name = "John"
>> user.save(touch: false)
  UPDATE "users" SET "name" = ? WHERE "users"."id" = ?  [["name", "John"], ["id", 12]]
=> true

>> user.updated_at
=> Thu, 12 May 2016 05:10:22 UTC +00:00

Upvotes: 9

Gazza
Gazza

Reputation: 3141

You could use .update_all:

User.where(:id => @user.id).update_all(:your_bool_field => true)

Upvotes: 8

Firoz Ansari
Firoz Ansari

Reputation: 2515

You can set record_timestamps attribute as false before updating.

User.record_timestamps=false
User.first.update_attributes(:field1 => "Test")
User.record_timestamps=true

For more: http://blog.bigbinary.com/2009/01/21/override-automatic-timestamp-in-activerecord-rails.html

Upvotes: 9

Related Questions