Search code examples
ruby-on-railsactionviewruby-on-rails-5.2

How do I update the fragment caching when register is updated?


I just recently updated my project from Rails 4 to Rails 5.2. Going through tests, I noticed the caches aren't being updated where they should.

Going through the documentation, I noticed some differences in the way ActionView does the cache.

Rails 4 includes the updated_at value on the cache name. By doing this, every time the element is touched, the previous cache becomes obsolete and a new cache is created.

views/projects/123-20120806214154/7a1156131a6928cb0026877f8b749ac9
      ^class   ^id ^updated_at    ^template tree digest

Great. But Rails 5.2 came with some changes where the updated_at value isn't set in the cache name anymore. From the documentation:

views/template/action.html.erb:7a1156131a6928cb0026877f8b749ac9/projects/123
      ^template path           ^template tree digest            ^class   ^id

Still, the documentation states:

When the project updated_at is touched, the cache_version changes, even if the key stays stable. This means that unlike a traditional key-based cache expiration approach, you won't be generating cache trash, unused keys, simply because the dependent record is updated.

From this, I suppose that it does some under the hood magic to replace the value from the cache, but it doesn't.

My code:

<% cache ['tags', post] do %>
  <%= render "shared/tags", post: post %>
<% end %>

Even when I post.touch on my console, the cache still remains the old one and I have to remove the cache manually for it to work. Am I missing something? How do I make it to work again?

I know I can do something like

cache "tags/#{post.updated_at}" do
...

but from the documentation, it doesn't feel right.


Solution

  • I figured it out. My project uses redis to store the cache and I didn't delete the gem redis-rails from my Gemfile after the upgrade. The method that writes cache from redis-activesupport gem was overwriting the rails built in method for redis, which was incorporated since Rails 5.2.

    So the fix was simply to erase redis-rails gem.