In the previous post I covered how can you use Rails' Russian Doll caching to make you app super fast. I didn't cover though how to cache search result pages and paginated results, so here comes the second part of that article.
I made a sample application where I have a product listing page with pagination and a search form: (https://github.com/gregmolnar/rails-caching.
Caching of the individual products is simple:
But we want to cache the full list too so we need to generate a cache key by ourself. My solution to this problem is to pluck the ids, join them and add the max updated_at value to the end of the string:
# app/views/products/index.html.erb<%= cache(cache_key_for_products(@products)) do %>
<table>
<thead>
<tr>
<th>Name</th>
<th>Price</th>
<th colspan="2"></th>
</tr></thead>
<tbody>
<% @products.each do |product| %>
<% cache(product) do %>
<tr>
<td><%= product.name %></td><td><%= product.price %></td>
<td><%=link_to'Edit',edit_product_path(product)%></td>
<td><%= link_to 'Destroy', product, method: :delete, data: { confirm: 'Are you sure?' } %></td></tr>
<% end %>
<% end %>
</tbody></table>
<% end %>
This methods works for pagination and sorting too, since it relies on the order of the ids. If there is a search functionality too, all we have to do is to pass a suffix to the helper method:
That's it for now.
I hope you enjoyed the article.
## Update
David Patrick([dponrails](https://twitter.com/dponrails)) did some benchmarks and it turned out `pluck` is pretty slow so here is a better performing alternative would be the usage of map: