In Rails' ActiveRecord, what is touch for?

I've heard of Rails' ActiveRecord/ActiveModel having something called "touch". However, I haven't found anything describing the purpose of this functionality.

What does it do, and what is it useful for?

1

6 Answers

As per the API Documentation, it is a method that only updates the specified timestamps of the model with the current time. So in order to update the updated_at field:

product.touch

or to update the updated_at and designed_at fields:

product.touch(:designed_at) 

Now, I have never used this method before, but I'd think it would be useful in a situation to "bump" a question (like on Stack Overflow) to the top of a search query without actually changing the contents.

3

Adding to Ryan's answer, don't forget to use touch in your models like so:

class Book < ActiveRecord::Base belongs_to :library, touch: true
end

Now when you add a book to the library, the library's updated_at time will reflect the time the latest book was added! Bonus!

touch can be useful if you're doing Russian Doll caching.

The advantage of Russian doll caching is that if a single product is updated, all the other inner fragments can be reused when regenerating the outer fragment.

If any attribute of [the inner fragment] is changed, the updated_at value will be set to the current time, thereby expiring the cache. However, because updated_at will not be changed for the [parent] object, that cache will not be expired and your app will serve stale data. To fix this, we tie the models together with the touch method.

Now in Rails 6 there is new method implemented called touch_all

By that you can update the timestamp of group of collection.

Example: If you want to update the timestamp of updated_at with current time of all the products then you can use touch_all method like this

Product.touch_all

In rails touch is used to update the updated_at field for persisted objects. But if we pass other attributes as arguments, it will update those fields too along with updated_at. Even it will update non-date-time fields if passed as arguments.

For example

product.touch(:price) #price is an integer

will update updated_at of product and set price value as Time.now.to_i

It's useful if you are using a front-end framework like flux (Alt/ Redux) or making async calls to the server, to update your model. In the case of multiple API calls made to your server, I used it to first check the 'updated_at' timing of a model before doing any saving or validations. Next, you can use 'touch' to update the 'updated_at' field accordingly.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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

You Might Also Like