4

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.

Jordan Schwartz
  • 105
  • 1
  • 8

3 Answers3

9

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

Firoz Ansari
  • 2,505
  • 1
  • 23
  • 36
  • right, I posted a link to that blog post in my original question. I'm looking for other ways to do it, that don't involve change the class properties. – Jordan Schwartz Aug 01 '12 at 19:47
  • This is very dangerous, while your update_attributes is being run any user updated will not be timestamped. For a single user that is not a problem for concurrent users that can easily break. – Batou99 Oct 13 '15 at 14:53
8

You could use .update_all:

User.where(:id => @user.id).update_all(:your_bool_field => true)
Gazza
  • 3,051
  • 1
  • 20
  • 22
8

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: 'david@example.com')
>> 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", "john@example.com"]]
=> 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
Subhash Chandra
  • 3,165
  • 1
  • 27
  • 30