【问题标题】:Rails: Fragment cache how to update when old data is not match with newRails:旧数据与新数据不匹配时如何更新片段缓存
【发布时间】:2020-11-02 15:10:00
【问题描述】:

问题是我在缓存片段中有一个函数调用,它依赖于当前时间,它第一次加载正确的数据,但并非总是如此。我需要显示的一些数据是基于时间的,但由于使用了缓存,它只是加载旧数据,因为记录没有更新。知道如何在仍然使用缓存的同时做到这一点。

<% cache "shop_items_page_#{@shop.cache_key}" do %>
 ...
   <% cache "item_list_page_#{item.cache_key}_#{shop_cache(item)}" do %>
     ...
     is_item_closed?(item) #a function returns true or false based on time
     ...
   <%end%>
 ...
<%end%>

【问题讨论】:

  • @showitem 是 ActiveRecord 模型的实例吗?
  • @Yakov 是的,它们是 ActiveRecord 模型的实例。
  • 请告诉我们is_item_closed? 做了什么。如果它是使用Time.now 的东西,它将不起作用。如果缓存块中的内容取决于模型之外的更改,在您的情况下,您需要将这些内容添加到缓存键中。例如:cache [:item_list_page, item, Date.current] do
  • @razvans yes is_item_closed? 依赖于 Time.now,它检查 Time.nowitem.end_time 。对我有帮助的是在缓存行 &lt;% cache "shop_items_page_#{@shop.cache_key}#{get_status_code(@shop)}" do %&gt;&lt;% cache "item_list_page_#{item.cache_key}_#{shop_cache(item)}#{get_status_code(item)}" do %&gt; 中附加一个 uniq 值以生成新密钥

标签: ruby-on-rails ruby caching server memcached


【解决方案1】:

根据documentation,您可以将模型的实例传递给cache方法:cache @shopcache item。然后 Rails 将基于updated_at 字段构建缓存键,确保您的表中有此字段。 如果您严格需要使用自定义缓存键,则直接在视图中或cache_key 方法中添加updated_at

<% cache "shop_items_page_#{@shop.cache_key}_#{@shop.updated_at}" do %>
 ...
   <% cache "item_list_page_#{item.cache_key}_#{item.updated_at}_#{shop_cache(item)}" do %>
     ...
     is_item_closed?(item) #a function returns true or false based on time
     ...
   <%end%>
 ...
<%end%>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-10
    • 1970-01-01
    • 1970-01-01
    • 2022-08-19
    • 2015-01-02
    • 1970-01-01
    相关资源
    最近更新 更多