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)
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)

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


Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s