rails 4 cache expiration not working

2019-08-14 10:31发布

In my rails app I'm trying to use nested caches, but my cache-key is not expiring when user.profile.full_name is changed. So when user changes his/her name the full_name displayed by _profile_product.html.erb remains the old one.

How should I change the key?

profiles/show.html.erb

<% cache(@profile) do %> #this is the profile info and the cache key expires properly when @profile.full_name changes
  <%= @profile.full_name %>
  .....
<% end %>
<% if @profile.user.products.any? %> #not nested in the previous cache; 
  #products belonging to the profile are listed with this code under the profile info
  <%= render 'products/profile_products' %>
<% end %>

_profile_products.html.erb

<% cache(['profile-products', @profile_products.map(&:id), @profile_products.map(&:updated_at).max]) do %>
  <%= render partial: "products/profile_product", collection: @profile_products, as: :product %>
<% end %>

_profile_product.html.erb

<% cache (['profile-product-single', product, product.user.profile]) do %>
  <%= product.name %>
  <%= product.user.profile.full_name %> #if I change profile name this one won't change thanks to the cache
<% end %>

1条回答
甜甜的少女心
2楼-- · 2019-08-14 11:05

Try changing the cache key in

_profile_products.html.erb

<% cache(['profile-products', @profile_products.map(&:id), @profile_products.map(&:updated_at).max, @profile_products.map{|pp| pp.user.profile.updated_at.to_i }.max]) do %>
  <%= render partial: "products/profile_product", collection: @profile_products, as: :product %>
<% end %>

The problem is that the cachefragment that contain the whole list doesn't expire when a user updated their profile name.

By adding the max of the associated user-profile´s updated_at to the cache key, the cache fragment will expire when a user updates their profile.

查看更多
登录 后发表回答