Ricky Mason
Ricky Mason

Reputation: 1828

update a column without changing updated_at

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

Upvotes: 10

Views: 14871

Answers (4)

nico_lrx
nico_lrx

Reputation: 280

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

Upvotes: 6

Frederick Cheung
Frederick Cheung

Reputation: 84114

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.

Upvotes: 6

Shalev Shalit
Shalev Shalit

Reputation: 1963

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

Upvotes: 3

Jimmy
Jimmy

Reputation: 37081

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

Upvotes: 17

Related Questions