In Rails' ActiveRecord, what is touch for?
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.
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, becauseupdated_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.
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!