Rails: what does the cache ['store', Product.latest] do in the fragment cache?

I am following a book called Agile Web Development With Rails 4 , and I had a problem understanding what cache ['store', Product.latest] in the view file.

 #static function latest is defined in the model def self.latest Product.order(:updated_at).last end #here is my view file <% cache['store',Product.latest] do %> <% @products.each do|product| %> <% cache['entry',product] do %> <div class="entry"> <%= image_tag(product.image_url) %> <h3><%= product.title %></h3> <%= sanitize(product.description) %> <div class="price_line"> <span class="price"><%= number_to_currency(product.price) %></span> </div> </div> <% end %> <% end %> <% end %> 
+5
source share
1 answer

cache(key) { ... } helper executes the contents of the block and caches the result with the given key for a certain period of time.

The documentation describes in detail all the various options and functions.

In your case ['store',Product.latest] are the parameters that create the cache key name. Array elements are combined to create a String , similar to store/products/100-20140101-163830 , which is then used as a cache key to store the result of the block.

The reason Product.latest is passed as an argument to the cache key is a trick to make sure the fragment has expired as soon as a new product is added to the database. This approach is often referred to as a key expiration model.

+1
source

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


All Articles