A
A
Alexander Grishin2015-11-11 22:40:52
Software testing
Alexander Grishin, 2015-11-11 22:40:52

Caching by RoR book. Can you help me figure it out?

Please help me understand this code

<% if notice %>
<p id="notice"><%= notice %></p>
<% end %>

<h1>Your Pragmatic Catalog</h1>

<% 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>
<!-- START_HIGHLIGHT -->
          <%= button_to 'Add to Cart', line_items_path(product_id: product) %>
<!-- END_HIGHLIGHT -->
        </div>
      </div>
    <% end %>
  <% end %>
<% end %>

According to the book, I didn’t understand anything at all, what and at what stage is cached?
And this is the code:
def self.latest
    Product.order(:updated_at).last
  end

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Korchagin, 2015-11-12
@beerdy

This caches snippets for each individual product and a snippet for the entire list of products.

def self.latest
  Product.order(:updated_at).last
end

- returns the last modified product (selection by update date).
Fragment for a single product, invalidated when product changes:
<% cache ['entry', product] do %>
  ...
<% end %>

Snippet for the whole list:
<% cache ['store', Product.latest] do %>
  ...
<% end %>

is invalidated when Product.latest changes, that is, in fact, when any product changes.
When you revisit the code, the last change to the product (Product.latest) is checked. If there were no changes after caching, the full list is taken from the cache. If there were, it is re-rendered, while the changes of each product are checked in a cycle and, if they are absent, a fragment for it is taken from the cache.

B
Boris Penkovsky, 2015-11-19
@Able1991

There is no point in caching erb, see for yourself the rendering time of the view - it will not be faster for you to access the cache store. Cache the data in the controller.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question