Rails 4.0.0.0. Caching Russian dolls with property.

I set the cache in my model, for example

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

and in my opinion

 <% cache ['inventories', Inventory.latest(session[:shop_id])] do %> <% @inventories.each do |inventory| %> <% cache ['entry', inventory] do %> <li><%= link_to inventory.item_name, inventory %></li> 

So, here I can have many stores, each of which has an inventory of spare items. Will the above cache work for different stores at all?

I think it’s possible that even displaying the view in another store will break the cache. Or any store adding an inventory item breaks the cache.

Is it possible to use caching of a Russian doll like this, or do I need to use Inventory.all in my model?

+6
source share
1 answer

Your idea is close, but you need to include shop_id , count and the maximum updated_at each store inventory in your cache key. Your external cache should be damaged when the store item is also deleted, and this does not apply only to max id or updated_at .

You can expand your own helper caching method to make this work. This allows you to create unique top-level caches that only go broke when a member of this set is added, updated, or deleted. Essentially, this provides a unique external cache for each shop_id . Thus, when one inventory store is changed, it does not affect another store cache.

Here is an example based on ideas in regional rail 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 

Then, in your opinion:

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

Source: https://habr.com/ru/post/948606/


All Articles