I'm following a book called Agile Web Development With Rails 4 and I'm having problem while understanding what does cache ['store', Product.latest]
do 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 %>
The cache(key) { ... }
helper performs the content of the block, and cached the result with the given key for a certain amount of time.
The documentation explain in details all the various options and features.
In your case, ['store',Product.latest]
are the parameters that build the cache key name. The items in the array are joined to produce a String
similar to store/products/100-20140101-163830
that is then used as the cache key to store the result of the block.
The reason why Product.latest
is passed as argument of the cache key, is a trick to make sure the fragment is expired as soon as a new product is added to the database. This approach is often referred as key-based expiration model.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With