问题描述
在我的Rails应用程序中,我试图使用嵌套缓存,但是当user.profile.full_name
更改时,我的缓存键没有过期.因此,当用户更改其姓名时,_profile_product.html.erb
显示的全名仍然是旧名称.
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.
我应该如何更改密钥?
profiles/show.html.erb
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
_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
_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 %>
推荐答案
尝试在其中更改缓存键
_profile_products.html.erb
_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.
通过将关联的用户配置文件的updated_at
的最大值添加到缓存键,当用户更新其配置文件时,缓存片段将过期.
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.
这篇关于rails 4缓存过期不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!