Rails 4.0.0.0中的俄罗斯套娃缓存与belongs_to模型相关。

6

我在我的模型中设置了一个缓存,例如:

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?

1个回答

3
您的想法接近正确,但您需要在缓存键中包括每个商店库存的shop_idcount和最大的updated_at。当商店的商品被删除时,您的外部缓存也需要被清除,这不仅仅是通过单独的max 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 %>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接