Caching in Rails 4

For caching based on ActiveRecord array i.e. single key for all restaurants

Your helper function which is available throughout the app

module RestaurantsHelper
def restaurant_promotion_key # to use this check file pages/home.html.erb
count = Restaurant.order_by_fee_plans.count
max_updated_at = Restaurant.order_by_fee_plans.maximum(:updated_at).try(:utc).try(:to_s, :number)
“restaurants/restaurant_promotion-#{count}-#{max_updated_at}”
end
def all_restaurant_key # to use this check file shared/_header_banner.html.erb
count = Restaurant.count
max_updated_at = Restaurant.maximum(:updated_at).try(:utc).try(:to_s, :number)
“restaurants/all-#{count}-#{max_updated_at}”
end
end

Using this in your view

<% cache(all_restaurant_key) do %>

<!– Your UI logic goes here–>

<% end %>

For caching for single row in ActiveRecord

<% cache(restaurant) do %>

<!–Your UI code on ActiveRecord: restaurant goes here–>

<% end %>

The key will be made by by rails and maintained automatically by Rails

Advertisements