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


Running local server as production server

Rails doesn’t serve static assets in production mode by default. If you want to disable this and serve the static assets, update your config/environments/production.rb file with this:

config.serve_static_assets = true

The reasoning behind Rails’ default configuration is that it assumes you’ll be running behind a standard web server in production mode (Apache, Nginx, etc.) which will then proxy the requests to your Rails app. Since the assets are precompiled, Apache/Nginx/etc. can directly serve them without needing to talk to your Rails processes.

Precompile your assets on local server using the below cmd from app

$>rake assets:precompile RAILS_ENV=production

Then edit your config/environments/roductions.rb and set the below flag to true, so that rails server sends assets from server

config.serve_static_assets = false

then start your local server as production

$>rails server -e production

Post your usage u can remove the precompiled assets from the local env using

     $>rake assets:clean