8

This may sound like an odd request, however, I have am using impressionist, and using a cached hit column. I am also updating another column everytime it gets a hit, which is a separate calculation.

I don't want to update updated_at at this time, is there a way to skip that?

if impressionist(@topic, "message...", :unique => [:session_hash])
  @topic.increment(:exp, 1).save
end

Thanks

Ricky Mason
  • 1,838
  • 6
  • 31
  • 60
  • 1
    possible duplicate of [Is there a way to avoid automatically updating Rails timestamp fields?](http://stackoverflow.com/questions/861448/is-there-a-way-to-avoid-automatically-updating-rails-timestamp-fields) – Shalev Shalit May 21 '15 at 14:36

4 Answers4

15

The update_columns method from ActiveRecord::Persistence will do what you want.

Jimmy
  • 35,686
  • 13
  • 80
  • 98
6

In addition to disabling timestamps for an entire class (which isn't thread safe), you can disable timestamps for an individual instance:

@topic.record_timestamps = false
@topic.increment(:exp, 1).save

This instance will not create or update timestamps until timestamps are re-enabled for it. This only affects this particular instance, other instances (even if they refer to the same row in the database) are not affected.

Frederick Cheung
  • 83,189
  • 8
  • 152
  • 174
4

Just disable record_timestamps before increment:

ActiveRecord::Base.record_timestamps = false

@topic.increment(:exp, 1).save

ActiveRecord::Base.record_timestamps = true

Is there a way to avoid automatically updating Rails timestamp fields?

Thread-safe version: update dataset without updating magic timestamp columns

Community
  • 1
  • 1
Shalev Shalit
  • 1,945
  • 4
  • 24
  • 34
  • Doesn't look thread-safe, but maybe AR is using thread locals internally? – Jimmy May 21 '15 at 14:26
  • It changes a global attribute on `ActiveRecord::Base`, so it will affect all threads that are running, not just the current one. – Jimmy May 22 '15 at 03:29
  • here is a thread-safe version: http://ck.kennt-wayne.de/2013/oct/rails-update-dataset-without-updating-magic-timestamp-columns – Shalev Shalit May 22 '15 at 06:06
  • Ha! Nice find. Seems like something that will probably break from some future Rails update, though. – Jimmy May 22 '15 at 07:05
  • @ShalevShalit You should consider the possibility that the code being executed may raise an error, so you should use an ensure block (as per the link in your answer). – Neil Atkinson Sep 20 '17 at 12:09
3

Since Rails 5, you can pass the touch argument to the save method in order to avoid updating the updated_at column:

user.name = "New Name"
user.save(touch: false) # doesn't update updated_at
nico_lrx
  • 715
  • 1
  • 19
  • 36