9

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

1

4 Answers 4

16

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

2
  • Thanks! is it possible to do this while using increment method? or do i just have to do a manual increment (+1)? May 21, 2015 at 14:35
  • thank you, I got it with : @topic.update_columns(exp:@topic.increment(:exp, 1).exp) May 21, 2015 at 14:39
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.

2
  • i get an undefined method
    – daslicious
    May 31, 2016 at 5:10
  • @topic.record_timestamps = false @topic.increment(:exp, 1).save Dec 8, 2016 at 21:00
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

5
  • Doesn't look thread-safe, but maybe AR is using thread locals internally?
    – Jimmy
    May 21, 2015 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, 2015 at 3:29
  • here is a thread-safe version: ck.kennt-wayne.de/2013/oct/… May 22, 2015 at 6:06
  • Ha! Nice find. Seems like something that will probably break from some future Rails update, though.
    – Jimmy
    May 22, 2015 at 7: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). Sep 20, 2017 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.