【问题标题】:Rails 4.0.0.0 Russian Doll Caching with belongs_to modelRails 4.0.0.0 俄罗斯娃娃缓存与 belongs_to 模型
【发布时间】:2013-07-24 06:45:58
【问题描述】:

我已经在我的模型中设置了一个缓存,比如

def self.latest(shop_id)
    Inventory.where(:shop_id => shop_id).order(:updated_at).last
end

在我看来

<% cache ['inventories', Inventory.latest(session[:shop_id])] do %>

   <% @inventories.each do |inventory| %>

      <% cache ['entry', inventory] do %>     

     <li><%= link_to inventory.item_name, inventory %></li>

所以,在这里我可以有很多商店,每个商店都有库存商品。上述缓存是否适用于不同的商店?

我认为即使在不同的商店中显示视图也可能会破坏缓存。或者,任何添加库存物品的商店都会破坏缓存。

我可以像这样使用俄罗斯娃娃缓存还是需要在我的模型中使用 Inventory.all?

【问题讨论】:

    标签: ruby-on-rails-3 russian-doll-caching


    【解决方案1】:

    您的想法很接近,但您需要将每个商店库存的shop_idcount 和最大updated_at 包含到您的缓存键中。当商店的商品也被删除时,您的外部缓存也需要被破坏,而这并没有单独包含在最大 idupdated_at 之下。

    您可以扩展您的自定义缓存键帮助器方法来完成这项工作。这允许您创建唯一的顶级缓存,只有在该集合的成员被添加、更新或删除时才会被破坏。实际上,这为每个shop_id 提供了唯一的外部缓存。因此,当一个商店的库存发生变化时,不会影响另一个商店的缓存。

    这是一个示例,基于edge rails documentation 中的想法:

    module InventoriesHelper
      def cache_key_for_inventories(shop_id)
        count          = Inventory.where(:shop_id => shop_id).count
        max_updated_at = Inventory.where(:shop_id => shop_id).maximum(:updated_at).try(:utc).try(:to_s, :number)
        "inventories/#{shop_id}-#{count}-#{max_updated_at}"
      end
    end
    

    那么在你看来:

    <% cache(cache_key_for_inventories(session[:shop_id])) do %>
      ...
    <% end %>
    

    【讨论】:

      猜你喜欢
      • 2014-03-19
      • 2016-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多