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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s