CINXE.COM

Caching with Rails: An Overview — Ruby on Rails Guides

<!doctype html> <html dir="ltr" lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Caching with Rails: An Overview — Ruby on Rails Guides</title> <link rel="stylesheet" type="text/css" href="stylesheets/style-071e355820fc155a5c40ef8a1c0c4971.css" data-turbo-track="reload"> <link rel="stylesheet" type="text/css" href="stylesheets/print-a87ee66d50ce96bb83ac082f1249fe3e.css" media="print"> <link rel="stylesheet" type="text/css" href="stylesheets/highlight-a0d2133dd0073968b2d33b1f1360a2a3.css" data-turbo-track="reload"> <link rel="icon" href="images/favicon.ico" sizes="any"> <link rel="apple-touch-icon" href="images/icon.png"> <script src="javascripts/@hotwired--turbo-764f59c7edbeb902a9068c0340dd274e.js" data-turbo-track="reload"></script> <script src="javascripts/clipboard-8b7aed6f069f0cf58eeae353cd2f898b.js" data-turbo-track="reload"></script> <script src="javascripts/guides-897790ae3777ddd81bd4953f7ec99835.js" data-turbo-track="reload"></script> <meta property="og:title" content="Caching with Rails: An Overview — Ruby on Rails Guides" /> <meta name="description" content="Caching with Rails: An OverviewThis guide is an introduction to speeding up your Rails application with caching.Caching means to store content generated during the request-response cycle and to reuse it when responding to similar requests.Caching is often the most effective way to boost an application&#39;s performance. Through caching, websites running on a single server with a single database can sustain a load of thousands of concurrent users.Rails provides a set of caching features out of the box. This guide will teach you the scope and purpose of each one of them. Master these techniques and your Rails applications can serve millions of views without exorbitant response times or server bills.After reading this guide, you will know: Fragment and Russian doll caching. How to manage the caching dependencies. Alternative cache stores. Conditional GET support." /> <meta property="og:description" content="Caching with Rails: An OverviewThis guide is an introduction to speeding up your Rails application with caching.Caching means to store content generated during the request-response cycle and to reuse it when responding to similar requests.Caching is often the most effective way to boost an application&#39;s performance. Through caching, websites running on a single server with a single database can sustain a load of thousands of concurrent users.Rails provides a set of caching features out of the box. This guide will teach you the scope and purpose of each one of them. Master these techniques and your Rails applications can serve millions of views without exorbitant response times or server bills.After reading this guide, you will know: Fragment and Russian doll caching. How to manage the caching dependencies. Alternative cache stores. Conditional GET support." /> <meta property="og:locale" content="en_US" /> <meta property="og:site_name" content="Ruby on Rails Guides" /> <meta property="og:image" content="https://avatars.githubusercontent.com/u/4223" /> <meta property="og:type" content="website" /> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Arabic:wght@100..900&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css2?family=Heebo:wght@100..900&family=Noto+Sans+Arabic:wght@100..900&display=swap" rel="stylesheet"> <meta name="theme-color" content="#C81418"> </head> <body dir="ltr" class="guide no-js"> <script> document.body.classList.remove('no-js') </script> <a id="main-skip-link" href="#main" class="skip-link" data-turbo="false"> Skip to main content </a> <div id="mobile-navigation-bar"> <div class="wrapper"> <strong class="more-info-label">More at <a href="https://rubyonrails.org/">rubyonrails.org:</a> </strong> <button type="button" class="js-only red-button more-info-button" id="more-info" aria-controls="more-info-links" aria-expanded="false"> More Ruby on Rails </button> <ul id="more-info-links" class="more-info-links hidden"> <li class="more-info"><a href="https://rubyonrails.org/blog">Blog</a></li> <li class="more-info"><a href="https://guides.rubyonrails.org/">Guides</a></li> <li class="more-info"><a href="https://api.rubyonrails.org/">API</a></li> <li class="more-info"><a href="https://discuss.rubyonrails.org/">Forum</a></li> <li class="more-info"><a href="https://github.com/rails/rails">Contribute on GitHub</a></li> </ul> </div> </div> <header id="page-header"> <div class="wrapper clearfix"> <nav id="feature-nav"> <div class="header-logo"> <a href="index.html" title="Guides home for v8.0.0 Guides">Guides</a> <span id="version-switcher" class="js-only"> <label for="version-switcher-select">Version: <span class="visibly-hidden">pick from the list to go to that Rails version's guides</span></label> <select id="version-switcher-select" class="guides-version"> <option value="https://edgeguides.rubyonrails.org/">Edge</option> <option value="https://guides.rubyonrails.org/v8.0/" selected>8.0</option> <option value="https://guides.rubyonrails.org/v7.2/">7.2</option> <option value="https://guides.rubyonrails.org/v7.1/">7.1</option> <option value="https://guides.rubyonrails.org/v7.0/">7.0</option> <option value="https://guides.rubyonrails.org/v6.1/">6.1</option> <option value="https://guides.rubyonrails.org/v6.0/">6.0</option> <option value="https://guides.rubyonrails.org/v5.2/">5.2</option> <option value="https://guides.rubyonrails.org/v5.1/">5.1</option> <option value="https://guides.rubyonrails.org/v5.0/">5.0</option> <option value="https://guides.rubyonrails.org/v4.2/">4.2</option> <option value="https://guides.rubyonrails.org/v4.1/">4.1</option> <option value="https://guides.rubyonrails.org/v4.0/">4.0</option> <option value="https://guides.rubyonrails.org/v3.2/">3.2</option> <option value="https://guides.rubyonrails.org/v3.1/">3.1</option> <option value="https://guides.rubyonrails.org/v3.0/">3.0</option> <option value="https://guides.rubyonrails.org/v2.3/">2.3</option> </select> </span> </div> <ul class="nav"> <li><a class="nav-item" id="home_nav" href="https://rubyonrails.org/">Home</a></li> <li class="guides-index guides-index-large"> <a href="index.html" id="guides-menu-button" data-aria-controls="guides" data-aria-expanded="false" class="guides-index-item nav-item">Guides Index</a> <div id="guides" class="clearfix" style="display: none;"> <hr /> <dl class="guides-section-container"> <div class="guides-section"> <dt>Start Here</dt> <dd><a href="getting_started.html">Getting Started with Rails</a></dd> </div> <div class="guides-section"> <dt>Models</dt> <dd><a href="active_record_basics.html">Active Record Basics</a></dd> <dd><a href="active_record_migrations.html">Active Record Migrations</a></dd> <dd><a href="active_record_validations.html">Active Record Validations</a></dd> <dd><a href="active_record_callbacks.html">Active Record Callbacks</a></dd> <dd><a href="association_basics.html">Active Record Associations</a></dd> <dd><a href="active_record_querying.html">Active Record Query Interface</a></dd> <dd><a href="active_model_basics.html">Active Model Basics</a></dd> </div> <div class="guides-section"> <dt>Views</dt> <dd><a href="action_view_overview.html">Action View Overview</a></dd> <dd><a href="layouts_and_rendering.html">Layouts and Rendering in Rails</a></dd> <dd><a href="action_view_helpers.html">Action View Helpers</a></dd> <dd><a href="form_helpers.html">Action View Form Helpers</a></dd> </div> <div class="guides-section"> <dt>Controllers</dt> <dd><a href="action_controller_overview.html">Action Controller Overview</a></dd> <dd><a href="routing.html">Rails Routing from the Outside In</a></dd> </div> <div class="guides-section"> <dt>Other Components</dt> <dd><a href="active_support_core_extensions.html">Active Support Core Extensions</a></dd> <dd><a href="action_mailer_basics.html">Action Mailer Basics</a></dd> <dd><a href="action_mailbox_basics.html">Action Mailbox Basics</a></dd> <dd><a href="action_text_overview.html">Action Text Overview</a></dd> <dd><a href="active_job_basics.html">Active Job Basics</a></dd> <dd><a href="active_storage_overview.html">Active Storage Overview</a></dd> <dd><a href="action_cable_overview.html">Action Cable Overview</a></dd> </div> <div class="guides-section"> <dt>Digging Deeper</dt> <dd><a href="i18n.html">Rails Internationalization (I18n) API</a></dd> <dd><a href="testing.html">Testing Rails Applications</a></dd> <dd><a href="security.html">Securing Rails Applications</a></dd> <dd><a href="error_reporting.html">Error Reporting in Rails Applications</a></dd> <dd><a href="debugging_rails_applications.html">Debugging Rails Applications</a></dd> <dd><a href="configuring.html">Configuring Rails Applications</a></dd> <dd><a href="command_line.html">The Rails Command Line</a></dd> <dd><a href="asset_pipeline.html">The Asset Pipeline</a></dd> <dd><a href="working_with_javascript_in_rails.html">Working with JavaScript in Rails</a></dd> <dd><a href="autoloading_and_reloading_constants.html">Autoloading and Reloading</a></dd> <dd><a href="caching_with_rails.html">Caching with Rails: An Overview</a></dd> <dd><a href="api_app.html">Using Rails for API-only Applications</a></dd> <dd><a href="tuning_performance_for_deployment.html">Tuning Performance for Deployment</a></dd> </div> <div class="guides-section"> <dt>Advanced Active Record</dt> <dd><a href="active_record_multiple_databases.html">Multiple Databases</a></dd> <dd><a href="active_record_composite_primary_keys.html">Composite Primary Keys</a></dd> </div> <div class="guides-section"> <dt>Extending Rails</dt> <dd><a href="rails_on_rack.html">Rails on Rack</a></dd> <dd><a href="generators.html">Creating and Customizing Rails Generators &amp; Templates</a></dd> </div> <div class="guides-section"> <dt>Contributing</dt> <dd><a href="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</a></dd> <dd><a href="api_documentation_guidelines.html">API Documentation Guidelines</a></dd> <dd><a href="ruby_on_rails_guides_guidelines.html">Guides Guidelines</a></dd> <dd><a href="development_dependencies_install.html">Installing Rails Core Development Dependencies</a></dd> </div> <div class="guides-section"> <dt>Policies</dt> <dd><a href="maintenance_policy.html">Maintenance Policy</a></dd> </div> <div class="guides-section"> <dt>Release Notes</dt> <dd><a href="upgrading_ruby_on_rails.html">Upgrading Ruby on Rails</a></dd> <dd><a href="7_2_release_notes.html">Version 7.2 - August 2024</a></dd> <dd><a href="7_1_release_notes.html">Version 7.1 - October 2023</a></dd> <dd><a href="7_0_release_notes.html">Version 7.0 - December 2021</a></dd> <dd><a href="6_1_release_notes.html">Version 6.1 - December 2020</a></dd> <dd><a href="6_0_release_notes.html">Version 6.0 - August 2019</a></dd> <dd><a href="5_2_release_notes.html">Version 5.2 - April 2018</a></dd> <dd><a href="5_1_release_notes.html">Version 5.1 - April 2017</a></dd> <dd><a href="5_0_release_notes.html">Version 5.0 - June 2016</a></dd> <dd><a href="4_2_release_notes.html">Version 4.2 - December 2014</a></dd> <dd><a href="4_1_release_notes.html">Version 4.1 - April 2014</a></dd> <dd><a href="4_0_release_notes.html">Version 4.0 - June 2013</a></dd> <dd><a href="3_2_release_notes.html">Version 3.2 - January 2012</a></dd> <dd><a href="3_1_release_notes.html">Version 3.1 - August 2011</a></dd> <dd><a href="3_0_release_notes.html">Version 3.0 - August 2010</a></dd> <dd><a href="2_3_release_notes.html">Version 2.3 - March 2009</a></dd> <dd><a href="2_2_release_notes.html">Version 2.2 - November 2008</a></dd> </div> </dl> </div> </li> <li><a class="nav-item" href="contributing_to_ruby_on_rails.html">Contribute</a></li> <li class="guides-index guides-index-small js-only"> <label for="guides-selector"> Navigate to a guide: </label> <select id="guides-selector" class="guides-index-item nav-item"> <option value="index.html">Guides Index</option> <optgroup label="Start Here"> <option value="getting_started.html">Getting Started with Rails</option> </optgroup> <optgroup label="Models"> <option value="active_record_basics.html">Active Record Basics</option> <option value="active_record_migrations.html">Active Record Migrations</option> <option value="active_record_validations.html">Active Record Validations</option> <option value="active_record_callbacks.html">Active Record Callbacks</option> <option value="association_basics.html">Active Record Associations</option> <option value="active_record_querying.html">Active Record Query Interface</option> <option value="active_model_basics.html">Active Model Basics</option> </optgroup> <optgroup label="Views"> <option value="action_view_overview.html">Action View Overview</option> <option value="layouts_and_rendering.html">Layouts and Rendering in Rails</option> <option value="action_view_helpers.html">Action View Helpers</option> <option value="form_helpers.html">Action View Form Helpers</option> </optgroup> <optgroup label="Controllers"> <option value="action_controller_overview.html">Action Controller Overview</option> <option value="routing.html">Rails Routing from the Outside In</option> </optgroup> <optgroup label="Other Components"> <option value="active_support_core_extensions.html">Active Support Core Extensions</option> <option value="action_mailer_basics.html">Action Mailer Basics</option> <option value="action_mailbox_basics.html">Action Mailbox Basics</option> <option value="action_text_overview.html">Action Text Overview</option> <option value="active_job_basics.html">Active Job Basics</option> <option value="active_storage_overview.html">Active Storage Overview</option> <option value="action_cable_overview.html">Action Cable Overview</option> </optgroup> <optgroup label="Digging Deeper"> <option value="i18n.html">Rails Internationalization (I18n) API</option> <option value="testing.html">Testing Rails Applications</option> <option value="security.html">Securing Rails Applications</option> <option value="error_reporting.html">Error Reporting in Rails Applications</option> <option value="debugging_rails_applications.html">Debugging Rails Applications</option> <option value="configuring.html">Configuring Rails Applications</option> <option value="command_line.html">The Rails Command Line</option> <option value="asset_pipeline.html">The Asset Pipeline</option> <option value="working_with_javascript_in_rails.html">Working with JavaScript in Rails</option> <option value="autoloading_and_reloading_constants.html">Autoloading and Reloading</option> <option value="caching_with_rails.html">Caching with Rails: An Overview</option> <option value="api_app.html">Using Rails for API-only Applications</option> <option value="tuning_performance_for_deployment.html">Tuning Performance for Deployment</option> </optgroup> <optgroup label="Advanced Active Record"> <option value="active_record_multiple_databases.html">Multiple Databases</option> <option value="active_record_composite_primary_keys.html">Composite Primary Keys</option> </optgroup> <optgroup label="Extending Rails"> <option value="rails_on_rack.html">Rails on Rack</option> <option value="generators.html">Creating and Customizing Rails Generators &amp; Templates</option> </optgroup> <optgroup label="Contributing"> <option value="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</option> <option value="api_documentation_guidelines.html">API Documentation Guidelines</option> <option value="ruby_on_rails_guides_guidelines.html">Guides Guidelines</option> <option value="development_dependencies_install.html">Installing Rails Core Development Dependencies</option> </optgroup> <optgroup label="Policies"> <option value="maintenance_policy.html">Maintenance Policy</option> </optgroup> <optgroup label="Release Notes"> <option value="upgrading_ruby_on_rails.html">Upgrading Ruby on Rails</option> <option value="7_2_release_notes.html">Version 7.2 - August 2024</option> <option value="7_1_release_notes.html">Version 7.1 - October 2023</option> <option value="7_0_release_notes.html">Version 7.0 - December 2021</option> <option value="6_1_release_notes.html">Version 6.1 - December 2020</option> <option value="6_0_release_notes.html">Version 6.0 - August 2019</option> <option value="5_2_release_notes.html">Version 5.2 - April 2018</option> <option value="5_1_release_notes.html">Version 5.1 - April 2017</option> <option value="5_0_release_notes.html">Version 5.0 - June 2016</option> <option value="4_2_release_notes.html">Version 4.2 - December 2014</option> <option value="4_1_release_notes.html">Version 4.1 - April 2014</option> <option value="4_0_release_notes.html">Version 4.0 - June 2013</option> <option value="3_2_release_notes.html">Version 3.2 - January 2012</option> <option value="3_1_release_notes.html">Version 3.1 - August 2011</option> <option value="3_0_release_notes.html">Version 3.0 - August 2010</option> <option value="2_3_release_notes.html">Version 2.3 - March 2009</option> <option value="2_2_release_notes.html">Version 2.2 - November 2008</option> </optgroup> </select> </li> </ul> </nav> </div> </header> <hr class="hide" /> <main id="main"> <article> <header id="feature"> <div class="wrapper"> <h1>Caching with Rails: An Overview</h1><p>This guide is an introduction to speeding up your Rails application with caching.</p><p>Caching means to store content generated during the request-response cycle and to reuse it when responding to similar requests.</p><p>Caching is often the most effective way to boost an application&#39;s performance. Through caching, websites running on a single server with a single database can sustain a load of thousands of concurrent users.</p><p>Rails provides a set of caching features out of the box. This guide will teach you the scope and purpose of each one of them. Master these techniques and your Rails applications can serve millions of views without exorbitant response times or server bills.</p><p>After reading this guide, you will know:</p> <ul> <li>Fragment and Russian doll caching.</li> <li>How to manage the caching dependencies.</li> <li>Alternative cache stores.</li> <li>Conditional GET support.</li> </ul> <nav id="column-side" aria-label="Chapter" class="guide-index" data-turbo="false"> <a id="chapter-nav-skip-link" href="#article-body" class="skip-link"> Skip to article body </a> <h2 class="chapter"> <picture aria-hidden="true"> <!-- Using the `source` HTML tag to set the dark theme image --> <source srcset="images/icon_book-close-bookmark-1-wht.svg" media="(prefers-color-scheme: dark)" /> <img src="images/icon_book-close-bookmark-1.svg" alt="Chapter Icon" /> </picture> Chapters </h2> <ol class="chapters"> <li><a href="#basic-caching">Basic Caching</a> <ul> <li><a href="#page-caching">Page Caching</a></li> <li><a href="#action-caching">Action Caching</a></li> <li><a href="#fragment-caching">Fragment Caching</a></li> <li><a href="#russian-doll-caching">Russian Doll Caching</a></li> <li><a href="#shared-partial-caching">Shared Partial Caching</a></li> <li><a href="#managing-dependencies">Managing Dependencies</a></li> <li><a href="#low-level-caching">Low-Level Caching</a></li> <li><a href="#sql-caching">SQL Caching</a></li> </ul></li> <li><a href="#cache-stores">Cache Stores</a> <ul> <li><a href="#configuration">Configuration</a></li> <li><a href="#activesupport-cache-store"><code>ActiveSupport::Cache::Store</code></a></li> <li><a href="#activesupport-cache-memorystore"><code>ActiveSupport::Cache::MemoryStore</code></a></li> <li><a href="#activesupport-cache-filestore"><code>ActiveSupport::Cache::FileStore</code></a></li> <li><a href="#activesupport-cache-memcachestore"><code>ActiveSupport::Cache::MemCacheStore</code></a></li> <li><a href="#activesupport-cache-rediscachestore"><code>ActiveSupport::Cache::RedisCacheStore</code></a></li> <li><a href="#activesupport-cache-nullstore"><code>ActiveSupport::Cache::NullStore</code></a></li> <li><a href="#custom-cache-stores">Custom Cache Stores</a></li> </ul></li> <li><a href="#cache-keys">Cache Keys</a></li> <li><a href="#conditional-get-support">Conditional GET Support</a> <ul> <li><a href="#strong-v-s-weak-etags">Strong v/s Weak ETags</a></li> </ul></li> <li><a href="#caching-in-development">Caching in Development</a></li> <li><a href="#references">References</a></li> </ol> </nav> </div> </header> <div class="wrapper"> <div id="column-main"> <section id="article-body"> <h2 id="basic-caching"><a class="anchorlink" href="#basic-caching" data-turbo="false"><span>1</span> Basic Caching</a></h2><p>This is an introduction to three types of caching techniques: page, action and fragment caching. By default Rails provides fragment caching. In order to use page and action caching you will need to add <code>actionpack-page_caching</code> and <code>actionpack-action_caching</code> to your <code>Gemfile</code>.</p><p>By default, Action Controller caching is only enabled in your production environment. You can play around with caching locally by running <code>rails dev:cache</code>, or by setting <a href="configuring.html#config-action-controller-perform-caching"><code>config.action_controller.perform_caching</code></a> to <code>true</code> in <code>config/environments/development.rb</code>.</p><div class="interstitial note"><p>Changing the value of <code>config.action_controller.perform_caching</code> will only have an effect on the caching provided by Action Controller. For instance, it will not impact low-level caching, that we address <a href="#low-level-caching">below</a>.</p></div><h3 id="page-caching"><a class="anchorlink" href="#page-caching" data-turbo="false"><span>1.1</span> Page Caching</a></h3><p>Page caching is a Rails mechanism which allows the request for a generated page to be fulfilled by the web server (i.e. Apache or NGINX) without having to go through the entire Rails stack. While this is super fast it can't be applied to every situation (such as pages that need authentication). Also, because the web server is serving a file directly from the filesystem you will need to implement cache expiration.</p><div class="interstitial info"><p>Page Caching has been removed from Rails 4. See the <a href="https://github.com/rails/actionpack-page_caching">actionpack-page_caching gem</a>.</p></div><h3 id="action-caching"><a class="anchorlink" href="#action-caching" data-turbo="false"><span>1.2</span> Action Caching</a></h3><p>Page Caching cannot be used for actions that have before filters - for example, pages that require authentication. This is where Action Caching comes in. Action Caching works like Page Caching except the incoming web request hits the Rails stack so that before filters can be run on it before the cache is served. This allows authentication and other restrictions to be run while still serving the result of the output from a cached copy.</p><div class="interstitial info"><p>Action Caching has been removed from Rails 4. See the <a href="https://github.com/rails/actionpack-action_caching">actionpack-action_caching gem</a>. See <a href="https://signalvnoise.com/posts/3113-how-key-based-cache-expiration-works">DHH's key-based cache expiration overview</a> for the newly-preferred method.</p></div><h3 id="fragment-caching"><a class="anchorlink" href="#fragment-caching" data-turbo="false"><span>1.3</span> Fragment Caching</a></h3><p>Dynamic web applications usually build pages with a variety of components not all of which have the same caching characteristics. When different parts of the page need to be cached and expired separately you can use Fragment Caching.</p><p>Fragment Caching allows a fragment of view logic to be wrapped in a cache block and served out of the cache store when the next request comes in.</p><p>For example, if you wanted to cache each product on a page, you could use this code:</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="cp">&lt;%</span> <span class="vi">@products</span><span class="p">.</span><span class="nf">each</span> <span class="k">do</span> <span class="o">|</span><span class="n">product</span><span class="o">|</span> <span class="cp">%&gt;</span> <span class="cp">&lt;%</span> <span class="n">cache</span> <span class="n">product</span> <span class="k">do</span> <span class="cp">%&gt;</span> <span class="cp">&lt;%=</span> <span class="n">render</span> <span class="n">product</span> <span class="cp">%&gt;</span> <span class="cp">&lt;%</span> <span class="k">end</span> <span class="cp">%&gt;</span> <span class="cp">&lt;%</span> <span class="k">end</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<% @products.each do |product| %> <% cache product do %> <%= render product %> <% end %> <% end %> ">Copy</button> </div> <p>When your application receives its first request to this page, Rails will write a new cache entry with a unique key. A key looks something like this:</p><div class="interstitial code"> <pre><code class="highlight plaintext">views/products/index:bea67108094918eeba42cd4a6e786901/products/1 </code></pre> <button class="clipboard-button" data-clipboard-text="views/products/index:bea67108094918eeba42cd4a6e786901/products/1 ">Copy</button> </div> <p>The string of characters in the middle is a template tree digest. It is a hash digest computed based on the contents of the view fragment you are caching. If you change the view fragment (e.g., the HTML changes), the digest will change, expiring the existing file.</p><p>A cache version, derived from the product record, is stored in the cache entry. When the product is touched, the cache version changes, and any cached fragments that contain the previous version are ignored.</p><div class="interstitial info"><p>Cache stores like Memcached will automatically delete old cache files.</p></div><p>If you want to cache a fragment under certain conditions, you can use <code>cache_if</code> or <code>cache_unless</code>:</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="cp">&lt;%</span> <span class="n">cache_if</span> <span class="n">admin?</span><span class="p">,</span> <span class="n">product</span> <span class="k">do</span> <span class="cp">%&gt;</span> <span class="cp">&lt;%=</span> <span class="n">render</span> <span class="n">product</span> <span class="cp">%&gt;</span> <span class="cp">&lt;%</span> <span class="k">end</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<% cache_if admin?, product do %> <%= render product %> <% end %> ">Copy</button> </div> <h4 id="collection-caching"><a class="anchorlink" href="#collection-caching" data-turbo="false"><span>1.3.1</span> Collection Caching</a></h4><p>The <code>render</code> helper can also cache individual templates rendered for a collection. It can even one up the previous example with <code>each</code> by reading all cache templates at once instead of one by one. This is done by passing <code>cached: true</code> when rendering the collection:</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="cp">&lt;%=</span> <span class="n">render</span> <span class="ss">partial: </span><span class="s1">'products/product'</span><span class="p">,</span> <span class="ss">collection: </span><span class="vi">@products</span><span class="p">,</span> <span class="ss">cached: </span><span class="kp">true</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<%= render partial: 'products/product', collection: @products, cached: true %> ">Copy</button> </div> <p>All cached templates from previous renders will be fetched at once with much greater speed. Additionally, the templates that haven't yet been cached will be written to cache and multi fetched on the next render.</p><p>The cache key can be configured. In the example below, it is prefixed with the current locale to ensure that different localizations of the product page do not overwrite each other:</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="cp">&lt;%=</span> <span class="n">render</span> <span class="ss">partial: </span><span class="s1">'products/product'</span><span class="p">,</span> <span class="ss">collection: </span><span class="vi">@products</span><span class="p">,</span> <span class="ss">cached: </span><span class="o">-&gt;</span><span class="p">(</span><span class="n">product</span><span class="p">)</span> <span class="p">{</span> <span class="p">[</span><span class="no">I18n</span><span class="p">.</span><span class="nf">locale</span><span class="p">,</span> <span class="n">product</span><span class="p">]</span> <span class="p">}</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<%= render partial: 'products/product', collection: @products, cached: ->(product) { [I18n.locale, product] } %> ">Copy</button> </div> <h3 id="russian-doll-caching"><a class="anchorlink" href="#russian-doll-caching" data-turbo="false"><span>1.4</span> Russian Doll Caching</a></h3><p>You may want to nest cached fragments inside other cached fragments. This is called Russian doll caching.</p><p>The advantage of Russian doll caching is that if a single product is updated, all the other inner fragments can be reused when regenerating the outer fragment.</p><p>As explained in the previous section, a cached file will expire if the value of <code>updated_at</code> changes for a record on which the cached file directly depends. However, this will not expire any cache the fragment is nested within.</p><p>For example, take the following view:</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="cp">&lt;%</span> <span class="n">cache</span> <span class="n">product</span> <span class="k">do</span> <span class="cp">%&gt;</span> <span class="cp">&lt;%=</span> <span class="n">render</span> <span class="n">product</span><span class="p">.</span><span class="nf">games</span> <span class="cp">%&gt;</span> <span class="cp">&lt;%</span> <span class="k">end</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<% cache product do %> <%= render product.games %> <% end %> ">Copy</button> </div> <p>Which in turn renders this view:</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="cp">&lt;%</span> <span class="n">cache</span> <span class="n">game</span> <span class="k">do</span> <span class="cp">%&gt;</span> <span class="cp">&lt;%=</span> <span class="n">render</span> <span class="n">game</span> <span class="cp">%&gt;</span> <span class="cp">&lt;%</span> <span class="k">end</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<% cache game do %> <%= render game %> <% end %> ">Copy</button> </div> <p>If any attribute of game is changed, the <code>updated_at</code> value will be set to the current time, thereby expiring the cache. However, because <code>updated_at</code> will not be changed for the product object, that cache will not be expired and your app will serve stale data. To fix this, we tie the models together with the <code>touch</code> method:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">Product</span> <span class="o">&lt;</span> <span class="no">ApplicationRecord</span> <span class="n">has_many</span> <span class="ss">:games</span> <span class="k">end</span> <span class="k">class</span> <span class="nc">Game</span> <span class="o">&lt;</span> <span class="no">ApplicationRecord</span> <span class="n">belongs_to</span> <span class="ss">:product</span><span class="p">,</span> <span class="ss">touch: </span><span class="kp">true</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class Product < ApplicationRecord has_many :games end class Game < ApplicationRecord belongs_to :product, touch: true end ">Copy</button> </div> <p>With <code>touch</code> set to <code>true</code>, any action which changes <code>updated_at</code> for a game record will also change it for the associated product, thereby expiring the cache.</p><h3 id="shared-partial-caching"><a class="anchorlink" href="#shared-partial-caching" data-turbo="false"><span>1.5</span> Shared Partial Caching</a></h3><p>It is possible to share partials and associated caching between files with different MIME types. For example shared partial caching allows template writers to share a partial between HTML and JavaScript files. When templates are collected in the template resolver file paths they only include the template language extension and not the MIME type. Because of this templates can be used for multiple MIME types. Both HTML and JavaScript requests will respond to the following code:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">render</span><span class="p">(</span><span class="ss">partial: </span><span class="s2">"hotels/hotel"</span><span class="p">,</span> <span class="ss">collection: </span><span class="vi">@hotels</span><span class="p">,</span> <span class="ss">cached: </span><span class="kp">true</span><span class="p">)</span> </code></pre> <button class="clipboard-button" data-clipboard-text="render(partial: &quot;hotels/hotel&quot;, collection: @hotels, cached: true) ">Copy</button> </div> <p>Will load a file named <code>hotels/hotel.erb</code>.</p><p>Another option is to include the <code>formats</code> attribute to the partial to render.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">render</span><span class="p">(</span><span class="ss">partial: </span><span class="s2">"hotels/hotel"</span><span class="p">,</span> <span class="ss">collection: </span><span class="vi">@hotels</span><span class="p">,</span> <span class="ss">formats: :html</span><span class="p">,</span> <span class="ss">cached: </span><span class="kp">true</span><span class="p">)</span> </code></pre> <button class="clipboard-button" data-clipboard-text="render(partial: &quot;hotels/hotel&quot;, collection: @hotels, formats: :html, cached: true) ">Copy</button> </div> <p>Will load a file named <code>hotels/hotel.html.erb</code> in any file MIME type, for example you could include this partial in a JavaScript file.</p><h3 id="managing-dependencies"><a class="anchorlink" href="#managing-dependencies" data-turbo="false"><span>1.6</span> Managing Dependencies</a></h3><p>In order to correctly invalidate the cache, you need to properly define the caching dependencies. Rails is clever enough to handle common cases so you don't have to specify anything. However, sometimes, when you're dealing with custom helpers for instance, you need to explicitly define them.</p><h4 id="implicit-dependencies"><a class="anchorlink" href="#implicit-dependencies" data-turbo="false"><span>1.6.1</span> Implicit Dependencies</a></h4><p>Most template dependencies can be derived from calls to <code>render</code> in the template itself. Here are some examples of render calls that <code>ActionView::Digestor</code> knows how to decode:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">render</span> <span class="ss">partial: </span><span class="s2">"comments/comment"</span><span class="p">,</span> <span class="ss">collection: </span><span class="n">commentable</span><span class="p">.</span><span class="nf">comments</span> <span class="n">render</span> <span class="s2">"comments/comments"</span> <span class="n">render</span> <span class="s2">"comments/comments"</span> <span class="n">render</span><span class="p">(</span><span class="s2">"comments/comments"</span><span class="p">)</span> <span class="n">render</span> <span class="s2">"header"</span> <span class="c1"># translates to render("comments/header")</span> <span class="n">render</span><span class="p">(</span><span class="vi">@topic</span><span class="p">)</span> <span class="c1"># translates to render("topics/topic")</span> <span class="n">render</span><span class="p">(</span><span class="n">topics</span><span class="p">)</span> <span class="c1"># translates to render("topics/topic")</span> <span class="n">render</span><span class="p">(</span><span class="n">message</span><span class="p">.</span><span class="nf">topics</span><span class="p">)</span> <span class="c1"># translates to render("topics/topic")</span> </code></pre> <button class="clipboard-button" data-clipboard-text="render partial: &quot;comments/comment&quot;, collection: commentable.comments render &quot;comments/comments&quot; render &quot;comments/comments&quot; render(&quot;comments/comments&quot;) render &quot;header&quot; # translates to render(&quot;comments/header&quot;) render(@topic) # translates to render(&quot;topics/topic&quot;) render(topics) # translates to render(&quot;topics/topic&quot;) render(message.topics) # translates to render(&quot;topics/topic&quot;) ">Copy</button> </div> <p>On the other hand, some calls need to be changed to make caching work properly. For instance, if you're passing a custom collection, you'll need to change:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">render</span> <span class="vi">@project</span><span class="p">.</span><span class="nf">documents</span><span class="p">.</span><span class="nf">where</span><span class="p">(</span><span class="ss">published: </span><span class="kp">true</span><span class="p">)</span> </code></pre> <button class="clipboard-button" data-clipboard-text="render @project.documents.where(published: true) ">Copy</button> </div> <p>to:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">render</span> <span class="ss">partial: </span><span class="s2">"documents/document"</span><span class="p">,</span> <span class="ss">collection: </span><span class="vi">@project</span><span class="p">.</span><span class="nf">documents</span><span class="p">.</span><span class="nf">where</span><span class="p">(</span><span class="ss">published: </span><span class="kp">true</span><span class="p">)</span> </code></pre> <button class="clipboard-button" data-clipboard-text="render partial: &quot;documents/document&quot;, collection: @project.documents.where(published: true) ">Copy</button> </div> <h4 id="explicit-dependencies"><a class="anchorlink" href="#explicit-dependencies" data-turbo="false"><span>1.6.2</span> Explicit Dependencies</a></h4><p>Sometimes you'll have template dependencies that can't be derived at all. This is typically the case when rendering happens in helpers. Here's an example:</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="cp">&lt;%=</span> <span class="n">render_sortable_todolists</span> <span class="vi">@project</span><span class="p">.</span><span class="nf">todolists</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<%= render_sortable_todolists @project.todolists %> ">Copy</button> </div> <p>You'll need to use a special comment format to call those out:</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="c">&lt;%# Template Dependency: todolists/todolist %&gt;</span> <span class="cp">&lt;%=</span> <span class="n">render_sortable_todolists</span> <span class="vi">@project</span><span class="p">.</span><span class="nf">todolists</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<%# Template Dependency: todolists/todolist %> <%= render_sortable_todolists @project.todolists %> ">Copy</button> </div> <p>In some cases, like a single table inheritance setup, you might have a bunch of explicit dependencies. Instead of writing every template out, you can use a wildcard to match any template in a directory:</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="c">&lt;%# Template Dependency: events/* %&gt;</span> <span class="cp">&lt;%=</span> <span class="n">render_categorizable_events</span> <span class="vi">@person</span><span class="p">.</span><span class="nf">events</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<%# Template Dependency: events/* %> <%= render_categorizable_events @person.events %> ">Copy</button> </div> <p>As for collection caching, if the partial template doesn't start with a clean cache call, you can still benefit from collection caching by adding a special comment format anywhere in the template, like:</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="c">&lt;%# Template Collection: notification %&gt;</span> <span class="cp">&lt;%</span> <span class="n">my_helper_that_calls_cache</span><span class="p">(</span><span class="n">some_arg</span><span class="p">,</span> <span class="n">notification</span><span class="p">)</span> <span class="k">do</span> <span class="cp">%&gt;</span> <span class="cp">&lt;%=</span> <span class="n">notification</span><span class="p">.</span><span class="nf">name</span> <span class="cp">%&gt;</span> <span class="cp">&lt;%</span> <span class="k">end</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<%# Template Collection: notification %> <% my_helper_that_calls_cache(some_arg, notification) do %> <%= notification.name %> <% end %> ">Copy</button> </div> <h4 id="external-dependencies"><a class="anchorlink" href="#external-dependencies" data-turbo="false"><span>1.6.3</span> External Dependencies</a></h4><p>If you use a helper method, for example, inside a cached block and you then update that helper, you'll have to bump the cache as well. It doesn't really matter how you do it, but the MD5 of the template file must change. One recommendation is to simply be explicit in a comment, like:</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="c">&lt;%# Helper Dependency Updated: Jul 28, 2015 at 7pm %&gt;</span> <span class="cp">&lt;%=</span> <span class="n">some_helper_method</span><span class="p">(</span><span class="n">person</span><span class="p">)</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<%# Helper Dependency Updated: Jul 28, 2015 at 7pm %> <%= some_helper_method(person) %> ">Copy</button> </div> <h3 id="low-level-caching"><a class="anchorlink" href="#low-level-caching" data-turbo="false"><span>1.7</span> Low-Level Caching</a></h3><p>Sometimes you need to cache a particular value or query result instead of caching view fragments. Rails' caching mechanism works great for storing any serializable information.</p><p>The most efficient way to implement low-level caching is using the <code>Rails.cache.fetch</code> method. This method does both reading and writing to the cache. When passed only a single argument, the key is fetched and value from the cache is returned. If a block is passed, that block will be executed in the event of a cache miss. The return value of the block will be written to the cache under the given cache key, and that return value will be returned. In case of cache hit, the cached value will be returned without executing the block.</p><p>Consider the following example. An application has a <code>Product</code> model with an instance method that looks up the product's price on a competing website. The data returned by this method would be perfect for low-level caching:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">Product</span> <span class="o">&lt;</span> <span class="no">ApplicationRecord</span> <span class="k">def</span> <span class="nf">competing_price</span> <span class="no">Rails</span><span class="p">.</span><span class="nf">cache</span><span class="p">.</span><span class="nf">fetch</span><span class="p">(</span><span class="s2">"</span><span class="si">#{</span><span class="n">cache_key_with_version</span><span class="si">}</span><span class="s2">/competing_price"</span><span class="p">,</span> <span class="ss">expires_in: </span><span class="mi">12</span><span class="p">.</span><span class="nf">hours</span><span class="p">)</span> <span class="k">do</span> <span class="no">Competitor</span><span class="o">::</span><span class="no">API</span><span class="p">.</span><span class="nf">find_price</span><span class="p">(</span><span class="nb">id</span><span class="p">)</span> <span class="k">end</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class Product < ApplicationRecord def competing_price Rails.cache.fetch(&quot;#{cache_key_with_version}/competing_price&quot;, expires_in: 12.hours) do Competitor::API.find_price(id) end end end ">Copy</button> </div> <div class="interstitial note"><p>Notice that in this example we used the <code>cache_key_with_version</code> method, so the resulting cache key will be something like <code>products/233-20140225082222765838000/competing_price</code>. <code>cache_key_with_version</code> generates a string based on the model's class name, <code>id</code>, and <code>updated_at</code> attributes. This is a common convention and has the benefit of invalidating the cache whenever the product is updated. In general, when you use low-level caching, you need to generate a cache key.</p></div><h4 id="avoid-caching-instances-of-active-record-objects"><a class="anchorlink" href="#avoid-caching-instances-of-active-record-objects" data-turbo="false"><span>1.7.1</span> Avoid Caching Instances of Active Record Objects</a></h4><p>Consider this example, which stores a list of Active Record objects representing superusers in the cache:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># super_admins is an expensive SQL query, so don't run it too often</span> <span class="no">Rails</span><span class="p">.</span><span class="nf">cache</span><span class="p">.</span><span class="nf">fetch</span><span class="p">(</span><span class="s2">"super_admin_users"</span><span class="p">,</span> <span class="ss">expires_in: </span><span class="mi">12</span><span class="p">.</span><span class="nf">hours</span><span class="p">)</span> <span class="k">do</span> <span class="no">User</span><span class="p">.</span><span class="nf">super_admins</span><span class="p">.</span><span class="nf">to_a</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="# super_admins is an expensive SQL query, so don't run it too often Rails.cache.fetch(&quot;super_admin_users&quot;, expires_in: 12.hours) do User.super_admins.to_a end ">Copy</button> </div> <p>You should <strong>avoid</strong> this pattern. Why? Because the instance could change. In production, attributes on it could differ, or the record could be deleted. And in development, it works unreliably with cache stores that reload code when you make changes.</p><p>Instead, cache the ID or some other primitive data type. For example:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># super_admins is an expensive SQL query, so don't run it too often</span> <span class="n">ids</span> <span class="o">=</span> <span class="no">Rails</span><span class="p">.</span><span class="nf">cache</span><span class="p">.</span><span class="nf">fetch</span><span class="p">(</span><span class="s2">"super_admin_user_ids"</span><span class="p">,</span> <span class="ss">expires_in: </span><span class="mi">12</span><span class="p">.</span><span class="nf">hours</span><span class="p">)</span> <span class="k">do</span> <span class="no">User</span><span class="p">.</span><span class="nf">super_admins</span><span class="p">.</span><span class="nf">pluck</span><span class="p">(</span><span class="ss">:id</span><span class="p">)</span> <span class="k">end</span> <span class="no">User</span><span class="p">.</span><span class="nf">where</span><span class="p">(</span><span class="ss">id: </span><span class="n">ids</span><span class="p">).</span><span class="nf">to_a</span> </code></pre> <button class="clipboard-button" data-clipboard-text="# super_admins is an expensive SQL query, so don't run it too often ids = Rails.cache.fetch(&quot;super_admin_user_ids&quot;, expires_in: 12.hours) do User.super_admins.pluck(:id) end User.where(id: ids).to_a ">Copy</button> </div> <h3 id="sql-caching"><a class="anchorlink" href="#sql-caching" data-turbo="false"><span>1.8</span> SQL Caching</a></h3><p>Query caching is a Rails feature that caches the result set returned by each query. 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.</p><p>For example:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">ProductsController</span> <span class="o">&lt;</span> <span class="no">ApplicationController</span> <span class="k">def</span> <span class="nf">index</span> <span class="c1"># Run a find query</span> <span class="vi">@products</span> <span class="o">=</span> <span class="no">Product</span><span class="p">.</span><span class="nf">all</span> <span class="c1"># ...</span> <span class="c1"># Run the same query again</span> <span class="vi">@products</span> <span class="o">=</span> <span class="no">Product</span><span class="p">.</span><span class="nf">all</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class ProductsController < ApplicationController def index # Run a find query @products = Product.all # ... # Run the same query again @products = Product.all end end ">Copy</button> </div> <p>The second time the same query is run against the database, it's not actually going to hit the database. The first time the result is returned from the query it is stored in the query cache (in memory) and the second time it's pulled from memory.</p><p>However, it's important to note that query caches are created at the start of an action and destroyed at the end of that action and thus persist only for the duration of the action. If you'd like to store query results in a more persistent fashion, you can with low-level caching.</p><h2 id="cache-stores"><a class="anchorlink" href="#cache-stores" data-turbo="false"><span>2</span> Cache Stores</a></h2><p>Rails provides different stores for the cached data (apart from SQL and page caching).</p><h3 id="configuration"><a class="anchorlink" href="#configuration" data-turbo="false"><span>2.1</span> Configuration</a></h3><p>You can set up your application's default cache store by setting the <code>config.cache_store</code> configuration option. Other parameters can be passed as arguments to the cache store's constructor:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">config</span><span class="p">.</span><span class="nf">cache_store</span> <span class="o">=</span> <span class="ss">:memory_store</span><span class="p">,</span> <span class="p">{</span> <span class="ss">size: </span><span class="mi">64</span><span class="p">.</span><span class="nf">megabytes</span> <span class="p">}</span> </code></pre> <button class="clipboard-button" data-clipboard-text="config.cache_store = :memory_store, { size: 64.megabytes } ">Copy</button> </div> <p>Alternatively, you can set <code>ActionController::Base.cache_store</code> outside of a configuration block.</p><p>You can access the cache by calling <code>Rails.cache</code>.</p><h4 id="connection-pool-options"><a class="anchorlink" href="#connection-pool-options" data-turbo="false"><span>2.1.1</span> Connection Pool Options</a></h4><p>By default, <a href="#activesupport-cache-memcachestore"><code>:mem_cache_store</code></a> and <a href="#activesupport-cache-rediscachestore"><code>:redis_cache_store</code></a> are configured to use connection pooling. This means that if you're using Puma, or another threaded server, you can have multiple threads performing queries to the cache store at the same time.</p><p>If you want to disable connection pooling, set <code>:pool</code> option to <code>false</code> when configuring the cache store:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">config</span><span class="p">.</span><span class="nf">cache_store</span> <span class="o">=</span> <span class="ss">:mem_cache_store</span><span class="p">,</span> <span class="s2">"cache.example.com"</span><span class="p">,</span> <span class="p">{</span> <span class="ss">pool: </span><span class="kp">false</span> <span class="p">}</span> </code></pre> <button class="clipboard-button" data-clipboard-text="config.cache_store = :mem_cache_store, &quot;cache.example.com&quot;, { pool: false } ">Copy</button> </div> <p>You can also override default pool settings by providing individual options to the <code>:pool</code> option:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">config</span><span class="p">.</span><span class="nf">cache_store</span> <span class="o">=</span> <span class="ss">:mem_cache_store</span><span class="p">,</span> <span class="s2">"cache.example.com"</span><span class="p">,</span> <span class="p">{</span> <span class="ss">pool: </span><span class="p">{</span> <span class="ss">size: </span><span class="mi">32</span><span class="p">,</span> <span class="ss">timeout: </span><span class="mi">1</span> <span class="p">}</span> <span class="p">}</span> </code></pre> <button class="clipboard-button" data-clipboard-text="config.cache_store = :mem_cache_store, &quot;cache.example.com&quot;, { pool: { size: 32, timeout: 1 } } ">Copy</button> </div> <ul> <li><p><code>:size</code> - This option sets the number of connections per process (defaults to 5).</p></li> <li><p><code>:timeout</code> - This option sets the number of seconds to wait for a connection (defaults to 5). If no connection is available within the timeout, a <code>Timeout::Error</code> will be raised.</p></li> </ul> <h3 id="activesupport-cache-store"><a class="anchorlink" href="#activesupport-cache-store" data-turbo="false"><span>2.2</span> <code>ActiveSupport::Cache::Store</code></a></h3><p><a href="https://api.rubyonrails.org/v8.0.0/classes/ActiveSupport/Cache/Store.html"><code>ActiveSupport::Cache::Store</code></a> provides the foundation for interacting with the cache in Rails. This is an abstract class, and you cannot use it on its own. Instead, you must use a concrete implementation of the class tied to a storage engine. Rails ships with several implementations, documented below.</p><p>The main API methods are <a href="https://api.rubyonrails.org/v8.0.0/classes/ActiveSupport/Cache/Store.html#method-i-read"><code>read</code></a>, <a href="https://api.rubyonrails.org/v8.0.0/classes/ActiveSupport/Cache/Store.html#method-i-write"><code>write</code></a>, <a href="https://api.rubyonrails.org/v8.0.0/classes/ActiveSupport/Cache/Store.html#method-i-delete"><code>delete</code></a>, <a href="https://api.rubyonrails.org/v8.0.0/classes/ActiveSupport/Cache/Store.html#method-i-exist-3F"><code>exist?</code></a>, and <a href="https://api.rubyonrails.org/v8.0.0/classes/ActiveSupport/Cache/Store.html#method-i-fetch"><code>fetch</code></a>.</p><p>Options passed to the cache store's constructor will be treated as default options for the appropriate API methods.</p><h3 id="activesupport-cache-memorystore"><a class="anchorlink" href="#activesupport-cache-memorystore" data-turbo="false"><span>2.3</span> <code>ActiveSupport::Cache::MemoryStore</code></a></h3><p><a href="https://api.rubyonrails.org/v8.0.0/classes/ActiveSupport/Cache/MemoryStore.html"><code>ActiveSupport::Cache::MemoryStore</code></a> keeps entries in memory in the same Ruby process. The cache store has a bounded size specified by sending the <code>:size</code> option to the initializer (default is 32Mb). When the cache exceeds the allotted size, a cleanup will occur and the least recently used entries will be removed.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">config</span><span class="p">.</span><span class="nf">cache_store</span> <span class="o">=</span> <span class="ss">:memory_store</span><span class="p">,</span> <span class="p">{</span> <span class="ss">size: </span><span class="mi">64</span><span class="p">.</span><span class="nf">megabytes</span> <span class="p">}</span> </code></pre> <button class="clipboard-button" data-clipboard-text="config.cache_store = :memory_store, { size: 64.megabytes } ">Copy</button> </div> <p>If you're running multiple Ruby on Rails server processes (which is the case if you're using Phusion Passenger or puma clustered mode), then your Rails server process instances won't be able to share cache data with each other. This cache store is not appropriate for large application deployments. However, it can work well for small, low traffic sites with only a couple of server processes, as well as development and test environments.</p><p>New Rails projects are configured to use this implementation in the development environment by default.</p><div class="interstitial note"><p>Since processes will not share cache data when using <code>:memory_store</code>, it will not be possible to manually read, write, or expire the cache via the Rails console.</p></div><h3 id="activesupport-cache-filestore"><a class="anchorlink" href="#activesupport-cache-filestore" data-turbo="false"><span>2.4</span> <code>ActiveSupport::Cache::FileStore</code></a></h3><p><a href="https://api.rubyonrails.org/v8.0.0/classes/ActiveSupport/Cache/FileStore.html"><code>ActiveSupport::Cache::FileStore</code></a> uses the file system to store entries. The path to the directory where the store files will be stored must be specified when initializing the cache.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">config</span><span class="p">.</span><span class="nf">cache_store</span> <span class="o">=</span> <span class="ss">:file_store</span><span class="p">,</span> <span class="s2">"/path/to/cache/directory"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="config.cache_store = :file_store, &quot;/path/to/cache/directory&quot; ">Copy</button> </div> <p>With this cache store, multiple server processes on the same host can share a cache. This cache store is appropriate for low to medium traffic sites that are served off one or two hosts. Server processes running on different hosts could share a cache by using a shared file system, but that setup is not recommended.</p><p>As the cache will grow until the disk is full, it is recommended to periodically clear out old entries.</p><p>This is the default cache store implementation (at <code>"#{root}/tmp/cache/"</code>) if no explicit <code>config.cache_store</code> is supplied.</p><h3 id="activesupport-cache-memcachestore"><a class="anchorlink" href="#activesupport-cache-memcachestore" data-turbo="false"><span>2.5</span> <code>ActiveSupport::Cache::MemCacheStore</code></a></h3><p><a href="https://api.rubyonrails.org/v8.0.0/classes/ActiveSupport/Cache/MemCacheStore.html"><code>ActiveSupport::Cache::MemCacheStore</code></a> uses Danga's <code>memcached</code> server to provide a centralized cache for your application. Rails uses the bundled <code>dalli</code> gem by default. This is currently the most popular cache store for production websites. It can be used to provide a single, shared cache cluster with very high performance and redundancy.</p><p>When initializing the cache, you should specify the addresses for all memcached servers in your cluster, or ensure the <code>MEMCACHE_SERVERS</code> environment variable has been set appropriately.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">config</span><span class="p">.</span><span class="nf">cache_store</span> <span class="o">=</span> <span class="ss">:mem_cache_store</span><span class="p">,</span> <span class="s2">"cache-1.example.com"</span><span class="p">,</span> <span class="s2">"cache-2.example.com"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="config.cache_store = :mem_cache_store, &quot;cache-1.example.com&quot;, &quot;cache-2.example.com&quot; ">Copy</button> </div> <p>If neither are specified, it will assume memcached is running on localhost on the default port (<code>127.0.0.1:11211</code>), but this is not an ideal setup for larger sites.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">config</span><span class="p">.</span><span class="nf">cache_store</span> <span class="o">=</span> <span class="ss">:mem_cache_store</span> <span class="c1"># Will fallback to $MEMCACHE_SERVERS, then 127.0.0.1:11211</span> </code></pre> <button class="clipboard-button" data-clipboard-text="config.cache_store = :mem_cache_store # Will fallback to $MEMCACHE_SERVERS, then 127.0.0.1:11211 ">Copy</button> </div> <p>See the <a href="https://www.rubydoc.info/gems/dalli/Dalli/Client#initialize-instance_method"><code>Dalli::Client</code> documentation</a> for supported address types.</p><p>The <a href="https://api.rubyonrails.org/v8.0.0/classes/ActiveSupport/Cache/MemCacheStore.html#method-i-write"><code>write</code></a> (and <code>fetch</code>) method on this cache accepts additional options that take advantage of features specific to memcached.</p><h3 id="activesupport-cache-rediscachestore"><a class="anchorlink" href="#activesupport-cache-rediscachestore" data-turbo="false"><span>2.6</span> <code>ActiveSupport::Cache::RedisCacheStore</code></a></h3><p><a href="https://api.rubyonrails.org/v8.0.0/classes/ActiveSupport/Cache/RedisCacheStore.html"><code>ActiveSupport::Cache::RedisCacheStore</code></a> takes advantage of Redis support for automatic eviction when it reaches max memory, allowing it to behave much like a Memcached cache server.</p><p>Deployment note: Redis doesn't expire keys by default, so take care to use a dedicated Redis cache server. Don't fill up your persistent-Redis server with volatile cache data! Read the <a href="https://redis.io/topics/lru-cache">Redis cache server setup guide</a> in detail.</p><p>For a cache-only Redis server, set <code>maxmemory-policy</code> to one of the variants of allkeys. Redis 4+ supports least-frequently-used eviction (<code>allkeys-lfu</code>), an excellent default choice. Redis 3 and earlier should use least-recently-used eviction (<code>allkeys-lru</code>).</p><p>Set cache read and write timeouts relatively low. Regenerating a cached value is often faster than waiting more than a second to retrieve it. Both read and write timeouts default to 1 second, but may be set lower if your network is consistently low-latency.</p><p>By default, the cache store will attempt to reconnect to Redis once if the connection fails during a request.</p><p>Cache reads and writes never raise exceptions; they just return <code>nil</code> instead, behaving as if there was nothing in the cache. To gauge whether your cache is hitting exceptions, you may provide an <code>error_handler</code> to report to an exception gathering service. It must accept three keyword arguments: <code>method</code>, the cache store method that was originally called; <code>returning</code>, the value that was returned to the user, typically <code>nil</code>; and <code>exception</code>, the exception that was rescued.</p><p>To get started, add the redis gem to your Gemfile:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">gem</span> <span class="s2">"redis"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="gem &quot;redis&quot; ">Copy</button> </div> <p>Finally, add the configuration in the relevant <code>config/environments/*.rb</code> file:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">config</span><span class="p">.</span><span class="nf">cache_store</span> <span class="o">=</span> <span class="ss">:redis_cache_store</span><span class="p">,</span> <span class="p">{</span> <span class="ss">url: </span><span class="no">ENV</span><span class="p">[</span><span class="s2">"REDIS_URL"</span><span class="p">]</span> <span class="p">}</span> </code></pre> <button class="clipboard-button" data-clipboard-text="config.cache_store = :redis_cache_store, { url: ENV[&quot;REDIS_URL&quot;] } ">Copy</button> </div> <p>A more complex, production Redis cache store may look something like this:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">cache_servers</span> <span class="o">=</span> <span class="sx">%w(redis://cache-01:6379/0 redis://cache-02:6379/0)</span> <span class="n">config</span><span class="p">.</span><span class="nf">cache_store</span> <span class="o">=</span> <span class="ss">:redis_cache_store</span><span class="p">,</span> <span class="p">{</span> <span class="ss">url: </span><span class="n">cache_servers</span><span class="p">,</span> <span class="ss">connect_timeout: </span><span class="mi">30</span><span class="p">,</span> <span class="c1"># Defaults to 1 second</span> <span class="ss">read_timeout: </span><span class="mf">0.2</span><span class="p">,</span> <span class="c1"># Defaults to 1 second</span> <span class="ss">write_timeout: </span><span class="mf">0.2</span><span class="p">,</span> <span class="c1"># Defaults to 1 second</span> <span class="ss">reconnect_attempts: </span><span class="mi">2</span><span class="p">,</span> <span class="c1"># Defaults to 1</span> <span class="ss">error_handler: </span><span class="o">-&gt;</span> <span class="p">(</span><span class="nb">method</span><span class="p">:,</span> <span class="n">returning</span><span class="p">:,</span> <span class="n">exception</span><span class="p">:)</span> <span class="p">{</span> <span class="c1"># Report errors to Sentry as warnings</span> <span class="no">Sentry</span><span class="p">.</span><span class="nf">capture_exception</span> <span class="n">exception</span><span class="p">,</span> <span class="ss">level: </span><span class="s2">"warning"</span><span class="p">,</span> <span class="ss">tags: </span><span class="p">{</span> <span class="ss">method: </span><span class="nb">method</span><span class="p">,</span> <span class="ss">returning: </span><span class="n">returning</span> <span class="p">}</span> <span class="p">}</span> <span class="p">}</span> </code></pre> <button class="clipboard-button" data-clipboard-text="cache_servers = %w(redis://cache-01:6379/0 redis://cache-02:6379/0) config.cache_store = :redis_cache_store, { url: cache_servers, connect_timeout: 30, # Defaults to 1 second read_timeout: 0.2, # Defaults to 1 second write_timeout: 0.2, # Defaults to 1 second reconnect_attempts: 2, # Defaults to 1 error_handler: -> (method:, returning:, exception:) { # Report errors to Sentry as warnings Sentry.capture_exception exception, level: &quot;warning&quot;, tags: { method: method, returning: returning } } } ">Copy</button> </div> <h3 id="activesupport-cache-nullstore"><a class="anchorlink" href="#activesupport-cache-nullstore" data-turbo="false"><span>2.7</span> <code>ActiveSupport::Cache::NullStore</code></a></h3><p><a href="https://api.rubyonrails.org/v8.0.0/classes/ActiveSupport/Cache/NullStore.html"><code>ActiveSupport::Cache::NullStore</code></a> is scoped to each web request, and clears stored values at the end of a request. It is meant for use in development and test environments. It can be very useful when you have code that interacts directly with <code>Rails.cache</code> but caching interferes with seeing the results of code changes.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">config</span><span class="p">.</span><span class="nf">cache_store</span> <span class="o">=</span> <span class="ss">:null_store</span> </code></pre> <button class="clipboard-button" data-clipboard-text="config.cache_store = :null_store ">Copy</button> </div> <h3 id="custom-cache-stores"><a class="anchorlink" href="#custom-cache-stores" data-turbo="false"><span>2.8</span> Custom Cache Stores</a></h3><p>You can create your own custom cache store by simply extending <code>ActiveSupport::Cache::Store</code> and implementing the appropriate methods. This way, you can swap in any number of caching technologies into your Rails application.</p><p>To use a custom cache store, simply set the cache store to a new instance of your custom class.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">config</span><span class="p">.</span><span class="nf">cache_store</span> <span class="o">=</span> <span class="no">MyCacheStore</span><span class="p">.</span><span class="nf">new</span> </code></pre> <button class="clipboard-button" data-clipboard-text="config.cache_store = MyCacheStore.new ">Copy</button> </div> <h2 id="cache-keys"><a class="anchorlink" href="#cache-keys" data-turbo="false"><span>3</span> Cache Keys</a></h2><p>The keys used in a cache can be any object that responds to either <code>cache_key</code> or <code>to_param</code>. You can implement the <code>cache_key</code> method on your classes if you need to generate custom keys. Active Record will generate keys based on the class name and record id.</p><p>You can use Hashes and Arrays of values as cache keys.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># This is a legal cache key</span> <span class="no">Rails</span><span class="p">.</span><span class="nf">cache</span><span class="p">.</span><span class="nf">read</span><span class="p">(</span><span class="ss">site: </span><span class="s2">"mysite"</span><span class="p">,</span> <span class="ss">owners: </span><span class="p">[</span><span class="n">owner_1</span><span class="p">,</span> <span class="n">owner_2</span><span class="p">])</span> </code></pre> <button class="clipboard-button" data-clipboard-text="# This is a legal cache key Rails.cache.read(site: &quot;mysite&quot;, owners: [owner_1, owner_2]) ">Copy</button> </div> <p>The keys you use on <code>Rails.cache</code> will not be the same as those actually used with the storage engine. They may be modified with a namespace or altered to fit technology backend constraints. This means, for instance, that you can't save values with <code>Rails.cache</code> and then try to pull them out with the <code>dalli</code> gem. However, you also don't need to worry about exceeding the memcached size limit or violating syntax rules.</p><h2 id="conditional-get-support"><a class="anchorlink" href="#conditional-get-support" data-turbo="false"><span>4</span> Conditional GET Support</a></h2><p>Conditional GETs are a feature of the HTTP specification that provide a way for web servers to tell browsers that the response to a GET request hasn't changed since the last request and can be safely pulled from the browser cache.</p><p>They work by using the <code>HTTP_IF_NONE_MATCH</code> and <code>HTTP_IF_MODIFIED_SINCE</code> headers to pass back and forth both a unique content identifier and the timestamp of when the content was last changed. If the browser makes a request where the content identifier (ETag) or last modified since timestamp matches the server's version then the server only needs to send back an empty response with a not modified status.</p><p>It is the server's (i.e. our) responsibility to look for a last modified timestamp and the if-none-match header and determine whether or not to send back the full response. With conditional-get support in Rails this is a pretty easy task:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">ProductsController</span> <span class="o">&lt;</span> <span class="no">ApplicationController</span> <span class="k">def</span> <span class="nf">show</span> <span class="vi">@product</span> <span class="o">=</span> <span class="no">Product</span><span class="p">.</span><span class="nf">find</span><span class="p">(</span><span class="n">params</span><span class="p">[</span><span class="ss">:id</span><span class="p">])</span> <span class="c1"># If the request is stale according to the given timestamp and etag value</span> <span class="c1"># (i.e. it needs to be processed again) then execute this block</span> <span class="k">if</span> <span class="n">stale?</span><span class="p">(</span><span class="ss">last_modified: </span><span class="vi">@product</span><span class="p">.</span><span class="nf">updated_at</span><span class="p">.</span><span class="nf">utc</span><span class="p">,</span> <span class="ss">etag: </span><span class="vi">@product</span><span class="p">.</span><span class="nf">cache_key_with_version</span><span class="p">)</span> <span class="n">respond_to</span> <span class="k">do</span> <span class="o">|</span><span class="n">wants</span><span class="o">|</span> <span class="c1"># ... normal response processing</span> <span class="k">end</span> <span class="k">end</span> <span class="c1"># If the request is fresh (i.e. it's not modified) then you don't need to do</span> <span class="c1"># anything. The default render checks for this using the parameters</span> <span class="c1"># used in the previous call to stale? and will automatically send a</span> <span class="c1"># :not_modified. So that's it, you're done.</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class ProductsController < ApplicationController def show @product = Product.find(params[:id]) # If the request is stale according to the given timestamp and etag value # (i.e. it needs to be processed again) then execute this block if stale?(last_modified: @product.updated_at.utc, etag: @product.cache_key_with_version) respond_to do |wants| # ... normal response processing end end # If the request is fresh (i.e. it's not modified) then you don't need to do # anything. The default render checks for this using the parameters # used in the previous call to stale? and will automatically send a # :not_modified. So that's it, you're done. end end ">Copy</button> </div> <p>Instead of an options hash, you can also simply pass in a model. Rails will use the <code>updated_at</code> and <code>cache_key_with_version</code> methods for setting <code>last_modified</code> and <code>etag</code>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">ProductsController</span> <span class="o">&lt;</span> <span class="no">ApplicationController</span> <span class="k">def</span> <span class="nf">show</span> <span class="vi">@product</span> <span class="o">=</span> <span class="no">Product</span><span class="p">.</span><span class="nf">find</span><span class="p">(</span><span class="n">params</span><span class="p">[</span><span class="ss">:id</span><span class="p">])</span> <span class="k">if</span> <span class="n">stale?</span><span class="p">(</span><span class="vi">@product</span><span class="p">)</span> <span class="n">respond_to</span> <span class="k">do</span> <span class="o">|</span><span class="n">wants</span><span class="o">|</span> <span class="c1"># ... normal response processing</span> <span class="k">end</span> <span class="k">end</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class ProductsController < ApplicationController def show @product = Product.find(params[:id]) if stale?(@product) respond_to do |wants| # ... normal response processing end end end end ">Copy</button> </div> <p>If you don't have any special response processing and are using the default rendering mechanism (i.e. you're not using <code>respond_to</code> or calling render yourself) then you've got an easy helper in <code>fresh_when</code>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">ProductsController</span> <span class="o">&lt;</span> <span class="no">ApplicationController</span> <span class="c1"># This will automatically send back a :not_modified if the request is fresh,</span> <span class="c1"># and will render the default template (product.*) if it's stale.</span> <span class="k">def</span> <span class="nf">show</span> <span class="vi">@product</span> <span class="o">=</span> <span class="no">Product</span><span class="p">.</span><span class="nf">find</span><span class="p">(</span><span class="n">params</span><span class="p">[</span><span class="ss">:id</span><span class="p">])</span> <span class="n">fresh_when</span> <span class="ss">last_modified: </span><span class="vi">@product</span><span class="p">.</span><span class="nf">published_at</span><span class="p">.</span><span class="nf">utc</span><span class="p">,</span> <span class="ss">etag: </span><span class="vi">@product</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class ProductsController < ApplicationController # This will automatically send back a :not_modified if the request is fresh, # and will render the default template (product.*) if it's stale. def show @product = Product.find(params[:id]) fresh_when last_modified: @product.published_at.utc, etag: @product end end ">Copy</button> </div> <p>When both <code>last_modified</code> and <code>etag</code> are set, behavior varies depending on the value of <code>config.action_dispatch.strict_freshness</code>. If set to <code>true</code>, only the <code>etag</code> is considered as specified by RFC 7232 section 6. If set to <code>false</code>, both are considered and the cache is considered fresh if both conditions are satisfied, as was the historical Rails behavior.</p><p>Sometimes we want to cache response, for example a static page, that never gets expired. To achieve this, we can use <code>http_cache_forever</code> helper and by doing so browser and proxies will cache it indefinitely.</p><p>By default cached responses will be private, cached only on the user's web browser. To allow proxies to cache the response, set <code>public: true</code> to indicate that they can serve the cached response to all users.</p><p>Using this helper, <code>last_modified</code> header is set to <code>Time.new(2011, 1, 1).utc</code> and <code>expires</code> header is set to a 100 years.</p><div class="interstitial warning"><p>Use this method carefully as browser/proxy won't be able to invalidate the cached response unless browser cache is forcefully cleared.</p></div><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">HomeController</span> <span class="o">&lt;</span> <span class="no">ApplicationController</span> <span class="k">def</span> <span class="nf">index</span> <span class="n">http_cache_forever</span><span class="p">(</span><span class="ss">public: </span><span class="kp">true</span><span class="p">)</span> <span class="k">do</span> <span class="n">render</span> <span class="k">end</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class HomeController < ApplicationController def index http_cache_forever(public: true) do render end end end ">Copy</button> </div> <h3 id="strong-v-s-weak-etags"><a class="anchorlink" href="#strong-v-s-weak-etags" data-turbo="false"><span>4.1</span> Strong v/s Weak ETags</a></h3><p>Rails generates weak ETags by default. Weak ETags allow semantically equivalent responses to have the same ETags, even if their bodies do not match exactly. This is useful when we don't want the page to be regenerated for minor changes in response body.</p><p>Weak ETags have a leading <code>W/</code> to differentiate them from strong ETags.</p><div class="interstitial code"> <pre><code class="highlight plaintext">W/"618bbc92e2d35ea1945008b42799b0e7" → Weak ETag "618bbc92e2d35ea1945008b42799b0e7" → Strong ETag </code></pre> <button class="clipboard-button" data-clipboard-text="W/&quot;618bbc92e2d35ea1945008b42799b0e7&quot; → Weak ETag &quot;618bbc92e2d35ea1945008b42799b0e7&quot; → Strong ETag ">Copy</button> </div> <p>Unlike weak ETag, strong ETag implies that response should be exactly the same and byte by byte identical. Useful when doing Range requests within a large video or PDF file. Some CDNs support only strong ETags, like Akamai. If you absolutely need to generate a strong ETag, it can be done as follows.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">ProductsController</span> <span class="o">&lt;</span> <span class="no">ApplicationController</span> <span class="k">def</span> <span class="nf">show</span> <span class="vi">@product</span> <span class="o">=</span> <span class="no">Product</span><span class="p">.</span><span class="nf">find</span><span class="p">(</span><span class="n">params</span><span class="p">[</span><span class="ss">:id</span><span class="p">])</span> <span class="n">fresh_when</span> <span class="ss">last_modified: </span><span class="vi">@product</span><span class="p">.</span><span class="nf">published_at</span><span class="p">.</span><span class="nf">utc</span><span class="p">,</span> <span class="ss">strong_etag: </span><span class="vi">@product</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class ProductsController < ApplicationController def show @product = Product.find(params[:id]) fresh_when last_modified: @product.published_at.utc, strong_etag: @product end end ">Copy</button> </div> <p>You can also set the strong ETag directly on the response.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">response</span><span class="p">.</span><span class="nf">strong_etag</span> <span class="o">=</span> <span class="n">response</span><span class="p">.</span><span class="nf">body</span> <span class="c1"># =&gt; "618bbc92e2d35ea1945008b42799b0e7"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="response.strong_etag = response.body # => &quot;618bbc92e2d35ea1945008b42799b0e7&quot; ">Copy</button> </div> <h2 id="caching-in-development"><a class="anchorlink" href="#caching-in-development" data-turbo="false"><span>5</span> Caching in Development</a></h2><p>By default, caching is <em>enabled</em> in development mode with <a href="#activesupport-cache-memorystore"><code>:memory_store</code></a>. This doesn't apply to Action Controller caching, which is disabled by default.</p><p>To enable Action Controller caching Rails provides the <code>bin/rails dev:cache</code> command.</p><div class="interstitial code"> <pre><code class="highlight console"><span class="gp">$</span><span class="w"> </span><span class="nb">bin/rails </span>dev:cache <span class="go">Development mode is now being cached. </span><span class="gp">$</span><span class="w"> </span><span class="nb">bin/rails </span>dev:cache <span class="go">Development mode is no longer being cached. </span></code></pre> <button class="clipboard-button" data-clipboard-text="bin/rails dev:cache bin/rails dev:cache ">Copy</button> </div> <p>To disable caching set <code>cache_store</code> to <a href="#activesupport-cache-nullstore"><code>:null_store</code></a></p><h2 id="references"><a class="anchorlink" href="#references" data-turbo="false"><span>6</span> References</a></h2> <ul> <li><a href="https://signalvnoise.com/posts/3113-how-key-based-cache-expiration-works">DHH's article on key-based expiration</a></li> <li><a href="http://railscasts.com/episodes/387-cache-digests">Ryan Bates' Railscast on cache digests</a></li> </ul> </section> <hr> <footer aria-labelledby="heading-feedback" role="region"> <h2 id="heading-feedback">Feedback</h2> <p> You're encouraged to help improve the quality of this guide. </p> <p> Please contribute if you see any typos or factual errors. To get started, you can read our <a href="https://edgeguides.rubyonrails.org/contributing_to_ruby_on_rails.html#contributing-to-the-rails-documentation">documentation contributions</a> section. </p> <p> You may also find incomplete content or stuff that is not up to date. Please do add any missing documentation for main. Make sure to check <a href="https://edgeguides.rubyonrails.org">Edge Guides</a> first to verify if the issues are already fixed or not on the main branch. Check the <a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</a> for style and conventions. </p> <p> If for whatever reason you spot something to fix but cannot patch it yourself, please <a href="https://github.com/rails/rails/issues">open an issue</a>. </p> <p>And last but not least, any kind of discussion regarding Ruby on Rails documentation is very welcome on the <a href="https://discuss.rubyonrails.org/c/rubyonrails-docs">official Ruby on Rails Forum</a>. </p> </footer> </div> </article> </main> <hr class="hide" /> <footer id="complementary"> <div class="wrapper"> <p>This work is licensed under a <a href="https://creativecommons.org/licenses/by-sa/4.0/">Creative Commons Attribution-ShareAlike 4.0 International</a> License</p> <p>"Rails", "Ruby on Rails", and the Rails logo are trademarks of David Heinemeier Hansson. All rights reserved.</p> </div> </footer> <a href="#main-skip-link" class="back-to-top" data-turbo="false"><span class="visibly-hidden">Back to top</span></a> </body> </html>

Pages: 1 2 3 4 5 6 7 8 9 10