Friday, March 04, 2016

Caching Database Results in Rails 4.2.5

If you make the same database calls  within any one request, Rails will cache the database result. You don't need to use use ||= to cache the value.
  def show
    Article.find(params[:id])
    Article.find(params[:id])
  end

You can see that the cache is hit in the log file:

Started GET "/articles/1" for ::1 at 2016-03-03 16:42:13 -0800
Processing by ArticlesController#show as */*
  Parameters: {"id"=>"1"}
  Article Load (0.1ms)  SELECT  "articles".* FROM "articles" WHERE "articles"."id" = ? LIMIT 1  [["id", 1]]
  CACHE (0.0ms)  SELECT  "articles".* FROM "articles" WHERE "articles"."id" = ? LIMIT 1  [["id", "1"]]
  Rendered articles/show.html.erb within layouts/application (0.3ms)
Completed 200 OK in 25ms (Views: 24.0ms | ActiveRecord: 0.1ms)

From  the Caching with Rails guide.

SQL Caching

Query caching is a Rails feature that caches the result set returned by each query so that if Rails encounters the same query again for that request, it will use the cached result set as opposed to running the query against the database again.