Last Updated: February 25, 2016
·
1.665K
· icortex

"Invalidate" cached key when record/document change

Reading this blog post I found this way to expire a cache very useful.

Consider following example:

class Place < ActiveRecord::Base
  def flickr_place
    flickr = FlickRaw::Flickr.new
    @flickr_place ||= Rails.cache.fetch("places/#{self.id}-#{self.updated_at}/flickr/place_id", expires_in: 7.days) do
      # Some code here
    end
  end
end

"... By using self.updated_at inside the cache key we ensure that the cache is automatically invalidated if we update the place (which could include new co-ordinates)."