Are you eager to elevate your security skills and safeguard your applications
against cyber threats? I created a Rails Security course is designed
specifically for developers like you who aim to build robust, secure Rails
applications!
Buy my course: Security for Rails Developers.
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:
Buy my course: Security for Rails Developers.
# app/views/products/index.html.erb
<% 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 %>
# app/helpers/products_helper.rb
module ProductsHelper
def cache_key_for_products(products)
ids = products.pluck(:id).join('-')
max_updated_at = products.pluck(:updated_at).max
"products/#{ids}-#{max_updated_at.to_i}"
end
end
# 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 %>
# app/helpers/products_helper.rb
module ProductsHelper
def cache_key_for_products(products, suffix = '')
ids = products.pluck(:id).join('-')
max_updated_at = products.pluck(:updated_at).max
"products/#{ids}-#{max_updated_at.to_i}#{suffix}"
end
end
cache_key_for_products(@products, "jewel=#{@search.jewel_eq}")
# app/helpers/products_helper.rb
module ProductsHelper
def cache_key_for_products(products, suffix = '')
ids = products.map(&:id).join('-')
max_updated_at = products.map(&id).max
"products/#{ids}-#{max_updated_at.to_i}#{suffix}"
end
end
Or follow me on Twitter
I run an indie startup providing vulnerability scanning for your Ruby on Rails app.
It is free to use at the moment, and I am grateful for any feedback about it.If you would like to give it a spin, you can do it here: Vulnerability Scanning for your Ruby on Rails app!