CINXE.COM

Upgrading Ruby on Rails — 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>Upgrading Ruby on Rails — 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="Upgrading Ruby on Rails — Ruby on Rails Guides" /> <meta name="description" content="Upgrading Ruby on RailsThis guide provides steps to be followed when you upgrade your applications to a newer version of Ruby on Rails. These steps are also available in individual release guides." /> <meta property="og:description" content="Upgrading Ruby on RailsThis guide provides steps to be followed when you upgrade your applications to a newer version of Ruby on Rails. These steps are also available in individual release guides." /> <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>Upgrading Ruby on Rails</h1><p>This guide provides steps to be followed when you upgrade your applications to a newer version of Ruby on Rails. These steps are also available in individual release guides.</p> <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="#general-advice">General Advice</a> <ul> <li><a href="#test-coverage">Test Coverage</a></li> <li><a href="#ruby-versions">Ruby Versions</a></li> <li><a href="#the-upgrade-process">The Upgrade Process</a></li> <li><a href="#the-update-task">The Update Task</a></li> <li><a href="#configure-framework-defaults">Configure Framework Defaults</a></li> </ul></li> <li><a href="#upgrading-from-rails-7-2-to-rails-8-0">Upgrading from Rails 7.2 to Rails 8.0</a></li> <li><a href="#upgrading-from-rails-7-1-to-rails-7-2">Upgrading from Rails 7.1 to Rails 7.2</a> <ul> <li><a href="#all-tests-now-respect-the-active-job-queue-adapter-config">All tests now respect the <code>active_job.queue_adapter</code> config</a></li> </ul></li> <li><a href="#upgrading-from-rails-7-0-to-rails-7-1">Upgrading from Rails 7.0 to Rails 7.1</a> <ul> <li><a href="#development-and-test-environments-secret-key-base-file-changed">Development and test environments secret_key_base file changed</a></li> <li><a href="#autoloaded-paths-are-no-longer-in-$load-path">Autoloaded paths are no longer in $LOAD_PATH</a></li> <li><a href="#config-autoload-lib-and-config-autoload-lib-once">config.autoload_lib and config.autoload_lib_once</a></li> <li><a href="#activestorage-basecontroller-no-longer-includes-the-streaming-concern"><code>ActiveStorage::BaseController</code> no longer includes the streaming concern</a></li> <li><a href="#memcachestore-and-rediscachestore-now-use-connection-pooling-by-default"><code>MemCacheStore</code> and <code>RedisCacheStore</code> now use connection pooling by default</a></li> <li><a href="#sqlite3adapter-now-configured-to-be-used-in-a-strict-strings-mode"><code>SQLite3Adapter</code> now configured to be used in a strict strings mode</a></li> <li><a href="#support-multiple-preview-paths-for-actionmailer-preview">Support multiple preview paths for <code>ActionMailer::Preview</code></a></li> <li><a href="#config-i18n-raise-on-missing-translations-true-now-raises-on-any-missing-translation"><code>config.i18n.raise_on_missing_translations = true</code> now raises on any missing translation.</a></li> <li><a href="#bin-rails-test-now-runs-test-prepare-task"><code>bin/rails test</code> now runs <code>test:prepare</code> task</a></li> <li><a href="#import-syntax-from-@rails-ujs-is-modified">Import syntax from <code>@rails/ujs</code> is modified</a></li> <li><a href="#rails-logger-now-returns-an-activesupport-broadcastlogger-instance"><code>Rails.logger</code> now returns an <code>ActiveSupport::BroadcastLogger</code> instance</a></li> <li><a href="#active-record-encryption-algorithm-changes">Active Record Encryption algorithm changes</a></li> <li><a href="#new-ways-to-handle-exceptions-in-controller-tests-integration-tests-and-system-tests">New ways to handle exceptions in Controller Tests, Integration Tests, and System Tests</a></li> </ul></li> <li><a href="#upgrading-from-rails-6-1-to-rails-7-0">Upgrading from Rails 6.1 to Rails 7.0</a> <ul> <li><a href="#actionview-helpers-urlhelper-button-to-changed-behavior"><code>ActionView::Helpers::UrlHelper#button_to</code> changed behavior</a></li> <li><a href="#upgrading-from-rails-6-1-to-rails-7-0-spring">Spring</a></li> <li><a href="#sprockets-is-now-an-optional-dependency">Sprockets is now an optional dependency</a></li> <li><a href="#applications-need-to-run-in-zeitwerk-mode">Applications need to run in <code>zeitwerk</code> mode</a></li> <li><a href="#the-setter-config-autoloader-has-been-deleted">The setter <code>config.autoloader=</code> has been deleted</a></li> <li><a href="#activesupport-dependencies-private-api-has-been-deleted"><code>ActiveSupport::Dependencies</code> private API has been deleted</a></li> <li><a href="#autoloading-during-initialization">Autoloading during initialization</a></li> <li><a href="#ability-to-configure-config-autoload-once-paths">Ability to configure <code>config.autoload_once_paths</code></a></li> <li><a href="#actiondispatch-request-content-type-now-returns-content-type-header-as-it-is"><code>ActionDispatch::Request#content_type</code> now returns Content-Type header as it is.</a></li> <li><a href="#key-generator-digest-class-change-requires-a-cookie-rotator">Key generator digest class change requires a cookie rotator</a></li> <li><a href="#digest-class-for-activesupport-digest-changing-to-sha256">Digest class for ActiveSupport::Digest changing to SHA256</a></li> <li><a href="#new-activesupport-cache-serialization-format">New ActiveSupport::Cache serialization format</a></li> <li><a href="#active-storage-video-preview-image-generation">Active Storage video preview image generation</a></li> <li><a href="#active-storage-default-variant-processor-changed-to-vips">Active Storage default variant processor changed to <code>:vips</code></a></li> <li><a href="#rails-version-is-now-included-in-the-active-record-schema-dump">Rails version is now included in the Active Record schema dump</a></li> </ul></li> <li><a href="#upgrading-from-rails-6-0-to-rails-6-1">Upgrading from Rails 6.0 to Rails 6.1</a> <ul> <li><a href="#rails-application-config-for-return-value-no-longer-supports-access-with-string-keys"><code>Rails.application.config_for</code> return value no longer supports access with String keys.</a></li> <li><a href="#response-s-content-type-when-using-respond-to-any">Response's Content-Type when using <code>respond_to#any</code></a></li> <li><a href="#activesupport-callbacks-halted-callback-hook-now-receive-a-second-argument"><code>ActiveSupport::Callbacks#halted_callback_hook</code> now receive a second argument</a></li> <li><a href="#the-helper-class-method-in-controllers-uses-string-constantize">The <code>helper</code> class method in controllers uses <code>String#constantize</code></a></li> <li><a href="#redirection-to-https-from-http-will-now-use-the-308-http-status-code">Redirection to HTTPS from HTTP will now use the 308 HTTP status code</a></li> <li><a href="#active-storage-now-requires-image-processing">Active Storage now requires Image Processing</a></li> <li><a href="#new-activemodel-error-class">New <code>ActiveModel::Error</code> class</a></li> </ul></li> <li><a href="#upgrading-from-rails-5-2-to-rails-6-0">Upgrading from Rails 5.2 to Rails 6.0</a> <ul> <li><a href="#using-webpacker">Using Webpacker</a></li> <li><a href="#force-ssl">Force SSL</a></li> <li><a href="#purpose-and-expiry-metadata-is-now-embedded-inside-signed-and-encrypted-cookies-for-increased-security">Purpose and expiry metadata is now embedded inside signed and encrypted cookies for increased security</a></li> <li><a href="#all-npm-packages-have-been-moved-to-the-@rails-scope">All npm packages have been moved to the <code>@rails</code> scope</a></li> <li><a href="#action-cable-javascript-api-changes">Action Cable JavaScript API Changes</a></li> <li><a href="#actiondispatch-response-content-type-now-returns-the-content-type-header-without-modification"><code>ActionDispatch::Response#content_type</code> now returns the Content-Type header without modification</a></li> <li><a href="#new-config-hosts-setting">New <code>config.hosts</code> setting</a></li> <li><a href="#autoloading">Autoloading</a></li> <li><a href="#active-storage-assignment-behavior-change">Active Storage assignment behavior change</a></li> <li><a href="#custom-exception-handling-applications">Custom exception handling applications</a></li> </ul></li> <li><a href="#upgrading-from-rails-5-1-to-rails-5-2">Upgrading from Rails 5.1 to Rails 5.2</a> <ul> <li><a href="#upgrading-from-rails-5-1-to-rails-5-2-bootsnap">Bootsnap</a></li> <li><a href="#expiry-in-signed-or-encrypted-cookie-is-now-embedded-in-the-cookies-values">Expiry in signed or encrypted cookie is now embedded in the cookies values</a></li> </ul></li> <li><a href="#upgrading-from-rails-5-0-to-rails-5-1">Upgrading from Rails 5.0 to Rails 5.1</a> <ul> <li><a href="#top-level-hashwithindifferentaccess-is-soft-deprecated">Top-level <code>HashWithIndifferentAccess</code> is soft-deprecated</a></li> <li><a href="#application-secrets-now-loaded-with-all-keys-as-symbols"><code>application.secrets</code> now loaded with all keys as symbols</a></li> <li><a href="#removed-deprecated-support-to-text-and-nothing-in-render">Removed deprecated support to <code>:text</code> and <code>:nothing</code> in <code>render</code></a></li> <li><a href="#removed-deprecated-support-of-redirect-to-back">Removed deprecated support of <code>redirect_to :back</code></a></li> </ul></li> <li><a href="#upgrading-from-rails-4-2-to-rails-5-0">Upgrading from Rails 4.2 to Rails 5.0</a> <ul> <li><a href="#ruby-2-2-2-required">Ruby 2.2.2+ required</a></li> <li><a href="#active-record-models-now-inherit-from-applicationrecord-by-default">Active Record Models Now Inherit from ApplicationRecord by Default</a></li> <li><a href="#halting-callback-chains-via-throw-abort">Halting Callback Chains via <code>throw(:abort)</code></a></li> <li><a href="#activejob-now-inherits-from-applicationjob-by-default">ActiveJob Now Inherits from ApplicationJob by Default</a></li> <li><a href="#rails-controller-testing">Rails Controller Testing</a></li> <li><a href="#autoloading-is-disabled-after-booting-in-the-production-environment">Autoloading is Disabled After Booting in the Production Environment</a></li> <li><a href="#xml-serialization">XML Serialization</a></li> <li><a href="#removed-support-for-legacy-mysql-database-adapter">Removed Support for Legacy <code>mysql</code> Database Adapter</a></li> <li><a href="#removed-support-for-debugger">Removed Support for Debugger</a></li> <li><a href="#use-bin-rails-for-running-tasks-and-tests">Use <code>bin/rails</code> for running tasks and tests</a></li> <li><a href="#actioncontroller-parameters-no-longer-inherits-from-hashwithindifferentaccess"><code>ActionController::Parameters</code> No Longer Inherits from <code>HashWithIndifferentAccess</code></a></li> <li><a href="#protect-from-forgery-now-defaults-to-prepend-false"><code>protect_from_forgery</code> Now Defaults to <code>prepend: false</code></a></li> <li><a href="#default-template-handler-is-now-raw">Default Template Handler is Now RAW</a></li> <li><a href="#added-wildcard-matching-for-template-dependencies">Added Wildcard Matching for Template Dependencies</a></li> <li><a href="#actionview-helpers-recordtaghelper-moved-to-external-gem-record-tag-helper"><code>ActionView::Helpers::RecordTagHelper</code> moved to external gem (record_tag_helper)</a></li> <li><a href="#removed-support-for-protected-attributes-gem">Removed Support for <code>protected_attributes</code> Gem</a></li> <li><a href="#removed-support-for-activerecord-deprecated-finders-gem">Removed support for <code>activerecord-deprecated_finders</code> gem</a></li> <li><a href="#activesupport-testcase-default-test-order-is-now-random"><code>ActiveSupport::TestCase</code> Default Test Order is Now Random</a></li> <li><a href="#actioncontroller-live-became-a-concern"><code>ActionController::Live</code> became a <code>Concern</code></a></li> <li><a href="#new-framework-defaults">New Framework Defaults</a></li> <li><a href="#changes-with-json-jsonb-serialization">Changes with JSON/JSONB serialization</a></li> </ul></li> <li><a href="#upgrading-from-rails-4-1-to-rails-4-2">Upgrading from Rails 4.1 to Rails 4.2</a> <ul> <li><a href="#web-console">Web Console</a></li> <li><a href="#responders">Responders</a></li> <li><a href="#error-handling-in-transaction-callbacks">Error handling in transaction callbacks</a></li> <li><a href="#ordering-of-test-cases">Ordering of test cases</a></li> <li><a href="#serialized-attributes">Serialized attributes</a></li> <li><a href="#production-log-level">Production log level</a></li> <li><a href="#after-bundle-in-rails-templates"><code>after_bundle</code> in Rails templates</a></li> <li><a href="#rails-html-sanitizer">Rails HTML Sanitizer</a></li> <li><a href="#rails-dom-testing">Rails DOM Testing</a></li> <li><a href="#masked-authenticity-tokens">Masked Authenticity Tokens</a></li> <li><a href="#action-mailer">Action Mailer</a></li> <li><a href="#foreign-key-support">Foreign Key Support</a></li> </ul></li> <li><a href="#upgrading-from-rails-4-0-to-rails-4-1">Upgrading from Rails 4.0 to Rails 4.1</a> <ul> <li><a href="#csrf-protection-from-remote-script-tags">CSRF protection from remote <code>&lt;script&gt;</code> tags</a></li> <li><a href="#upgrading-from-rails-4-0-to-rails-4-1-spring">Spring</a></li> <li><a href="#config-secrets-yml"><code>config/secrets.yml</code></a></li> <li><a href="#changes-to-test-helper">Changes to test helper</a></li> <li><a href="#cookies-serializer">Cookies serializer</a></li> <li><a href="#flash-structure-changes">Flash structure changes</a></li> <li><a href="#changes-in-json-handling">Changes in JSON handling</a></li> <li><a href="#usage-of-return-within-inline-callback-blocks">Usage of <code>return</code> within inline callback blocks</a></li> <li><a href="#methods-defined-in-active-record-fixtures">Methods defined in Active Record fixtures</a></li> <li><a href="#i18n-enforcing-available-locales">I18n enforcing available locales</a></li> <li><a href="#mutator-methods-called-on-relation">Mutator methods called on Relation</a></li> <li><a href="#changes-on-default-scopes">Changes on Default Scopes</a></li> <li><a href="#rendering-content-from-string">Rendering content from string</a></li> <li><a href="#postgresql-json-and-hstore-datatypes">PostgreSQL JSON and hstore datatypes</a></li> <li><a href="#explicit-block-use-for-activesupport-callbacks">Explicit block use for <code>ActiveSupport::Callbacks</code></a></li> </ul></li> <li><a href="#upgrading-from-rails-3-2-to-rails-4-0">Upgrading from Rails 3.2 to Rails 4.0</a> <ul> <li><a href="#http-patch">HTTP PATCH</a></li> <li><a href="#upgrading-from-rails-3-2-to-rails-4-0-gemfile">Gemfile</a></li> <li><a href="#upgrading-from-rails-3-2-to-rails-4-0-vendor-plugins">vendor/plugins</a></li> <li><a href="#upgrading-from-rails-3-2-to-rails-4-0-active-record">Active Record</a></li> <li><a href="#active-resource">Active Resource</a></li> <li><a href="#active-model">Active Model</a></li> <li><a href="#action-pack">Action Pack</a></li> <li><a href="#active-support">Active Support</a></li> <li><a href="#helpers-loading-order">Helpers Loading Order</a></li> <li><a href="#active-record-observer-and-action-controller-sweeper">Active Record Observer and Action Controller Sweeper</a></li> <li><a href="#sprockets-rails">sprockets-rails</a></li> <li><a href="#sass-rails">sass-rails</a></li> </ul></li> <li><a href="#upgrading-from-rails-3-1-to-rails-3-2">Upgrading from Rails 3.1 to Rails 3.2</a> <ul> <li><a href="#upgrading-from-rails-3-1-to-rails-3-2-gemfile">Gemfile</a></li> <li><a href="#upgrading-from-rails-3-1-to-rails-3-2-config-environments-development-rb">config/environments/development.rb</a></li> <li><a href="#upgrading-from-rails-3-1-to-rails-3-2-config-environments-test-rb">config/environments/test.rb</a></li> <li><a href="#upgrading-from-rails-3-1-to-rails-3-2-vendor-plugins">vendor/plugins</a></li> <li><a href="#upgrading-from-rails-3-1-to-rails-3-2-active-record">Active Record</a></li> </ul></li> <li><a href="#upgrading-from-rails-3-0-to-rails-3-1">Upgrading from Rails 3.0 to Rails 3.1</a> <ul> <li><a href="#gemfile">Gemfile</a></li> <li><a href="#config-application-rb">config/application.rb</a></li> <li><a href="#upgrading-from-rails-3-0-to-rails-3-1-config-environments-development-rb">config/environments/development.rb</a></li> <li><a href="#config-environments-production-rb">config/environments/production.rb</a></li> <li><a href="#upgrading-from-rails-3-0-to-rails-3-1-config-environments-test-rb">config/environments/test.rb</a></li> <li><a href="#config-initializers-wrap-parameters-rb">config/initializers/wrap_parameters.rb</a></li> <li><a href="#config-initializers-session-store-rb">config/initializers/session_store.rb</a></li> <li><a href="#remove-cache-and-concat-options-in-asset-helpers-references-in-views">Remove :cache and :concat options in asset helpers references in views</a></li> </ul></li> </ol> </nav> </div> </header> <div class="wrapper"> <div id="column-main"> <section id="article-body"> <h2 id="general-advice"><a class="anchorlink" href="#general-advice" data-turbo="false"><span>1</span> General Advice</a></h2><p>Before attempting to upgrade an existing application, you should be sure you have a good reason to upgrade. You need to balance several factors: the need for new features, the increasing difficulty of finding support for old code, and your available time and skills, to name a few.</p><h3 id="test-coverage"><a class="anchorlink" href="#test-coverage" data-turbo="false"><span>1.1</span> Test Coverage</a></h3><p>The best way to be sure that your application still works after upgrading is to have good test coverage before you start the process. If you don't have automated tests that exercise the bulk of your application, you'll need to spend time manually exercising all the parts that have changed. In the case of a Rails upgrade, that will mean every single piece of functionality in the application. Do yourself a favor and make sure your test coverage is good <em>before</em> you start an upgrade.</p><h3 id="ruby-versions"><a class="anchorlink" href="#ruby-versions" data-turbo="false"><span>1.2</span> Ruby Versions</a></h3><p>Rails generally stays close to the latest released Ruby version when it's released:</p> <ul> <li>Rails 8.0 requires Ruby 3.2.0 or newer.</li> <li>Rails 7.2 requires Ruby 3.1.0 or newer.</li> <li>Rails 7.0 and 7.1 requires Ruby 2.7.0 or newer.</li> <li>Rails 6 requires Ruby 2.5.0 or newer.</li> <li>Rails 5 requires Ruby 2.2.2 or newer.</li> </ul> <p>It's a good idea to upgrade Ruby and Rails separately. Upgrade to the latest Ruby you can first, and then upgrade Rails.</p><h3 id="the-upgrade-process"><a class="anchorlink" href="#the-upgrade-process" data-turbo="false"><span>1.3</span> The Upgrade Process</a></h3><p>When changing Rails versions, it's best to move slowly, one minor version at a time, in order to make good use of the deprecation warnings. Rails version numbers are in the form Major.Minor.Patch. Major and Minor versions are allowed to make changes to the public API, so this may cause errors in your application. Patch versions only include bug fixes, and don't change any public API.</p><p>The process should go as follows:</p> <ol> <li>Write tests and make sure they pass.</li> <li>Move to the latest patch version after your current version.</li> <li>Fix tests and deprecated features.</li> <li>Move to the latest patch version of the next minor version.</li> </ol> <p>Repeat this process until you reach your target Rails version.</p><h4 id="moving-between-versions"><a class="anchorlink" href="#moving-between-versions" data-turbo="false"><span>1.3.1</span> Moving between versions</a></h4><p>To move between versions:</p> <ol> <li>Change the Rails version number in the <code>Gemfile</code> and run <code>bundle update rails</code>.</li> <li>Change the versions for Rails JavaScript packages in <code>package.json</code> and run <code>bin/rails javascript:install</code> if running jsbundling-rails.</li> <li>Run the <a href="#the-update-task">Update task</a>.</li> <li>Run your tests.</li> </ol> <p>You can find a list of all released Rails gems <a href="https://rubygems.org/gems/rails/versions">here</a>.</p><h3 id="the-update-task"><a class="anchorlink" href="#the-update-task" data-turbo="false"><span>1.4</span> The Update Task</a></h3><p>Rails provides the <code>rails app:update</code> command. After updating the Rails version in the <code>Gemfile</code>, run this command. This will help you with the creation of new files and changes of old files in an interactive session.</p><div class="interstitial code"> <pre><code class="highlight console"><span class="gp">$</span><span class="w"> </span><span class="nb">bin/rails </span>app:update <span class="go"> exist config conflict config/application.rb Overwrite /myapp/config/application.rb? (enter "h" for help) [Ynaqdh] force config/application.rb create config/initializers/new_framework_defaults_8_0.rb </span><span class="c">... </span></code></pre> <button class="clipboard-button" data-clipboard-text="bin/rails app:update ">Copy</button> </div> <p>Don't forget to review the difference, to see if there were any unexpected changes, and note that the diff and merge tools used during this process can be defined using the <code>THOR_DIFF</code> and <code>THOR_MERGE</code> environment variables.</p><h3 id="configure-framework-defaults"><a class="anchorlink" href="#configure-framework-defaults" data-turbo="false"><span>1.5</span> Configure Framework Defaults</a></h3><p>The new Rails version might have different configuration defaults than the previous version. However, after following the steps described above, your application would still run with configuration defaults from the <em>previous</em> Rails version. That's because the value for <code>config.load_defaults</code> in <code>config/application.rb</code> has not been changed yet.</p><p>To allow you to upgrade to new defaults one by one, the update task has created a file <code>config/initializers/new_framework_defaults_X.Y.rb</code> (with the desired Rails version in the filename). You should enable the new configuration defaults by uncommenting them in the file; this can be done gradually over several deployments. Once your application is ready to run with new defaults, you can remove this file and flip the <code>config.load_defaults</code> value.</p><h2 id="upgrading-from-rails-7-2-to-rails-8-0"><a class="anchorlink" href="#upgrading-from-rails-7-2-to-rails-8-0" data-turbo="false"><span>2</span> Upgrading from Rails 7.2 to Rails 8.0</a></h2><p>For more information on changes made to Rails 8.0 please see the <a href="8_0_release_notes.html">release notes</a>.</p><h2 id="upgrading-from-rails-7-1-to-rails-7-2"><a class="anchorlink" href="#upgrading-from-rails-7-1-to-rails-7-2" data-turbo="false"><span>3</span> Upgrading from Rails 7.1 to Rails 7.2</a></h2><p>For more information on changes made to Rails 7.2 please see the <a href="7_2_release_notes.html">release notes</a>.</p><h3 id="all-tests-now-respect-the-active-job-queue-adapter-config"><a class="anchorlink" href="#all-tests-now-respect-the-active-job-queue-adapter-config" data-turbo="false"><span>3.1</span> All tests now respect the <code>active_job.queue_adapter</code> config</a></h3><p>If you have set <code>config.active_job.queue_adapter</code> in your <code>config/application.rb</code> or <code>config/environments/test.rb</code> file, the adapter you selected was previously not used consistently across all tests. In some tests your adapter would be used, but other tests would use the <code>TestAdapter</code>.</p><p>In Rails 7.2, all tests will respect the <code>queue_adapter</code> config if provided. This may cause test errors, if you had set the <code>queue_adapter</code> config to something other than <code>:test</code>, but written tests in a way that was dependent on the <code>TestAdapter</code>.</p><p>If no config is provided, the <code>TestAdapter</code> will continue to be used.</p><h2 id="upgrading-from-rails-7-0-to-rails-7-1"><a class="anchorlink" href="#upgrading-from-rails-7-0-to-rails-7-1" data-turbo="false"><span>4</span> Upgrading from Rails 7.0 to Rails 7.1</a></h2><p>For more information on changes made to Rails 7.1 please see the <a href="7_1_release_notes.html">release notes</a>.</p><h3 id="development-and-test-environments-secret-key-base-file-changed"><a class="anchorlink" href="#development-and-test-environments-secret-key-base-file-changed" data-turbo="false"><span>4.1</span> Development and test environments secret_key_base file changed</a></h3><p>In development and test environments, the file from which Rails reads the <code>secret_key_base</code> has been renamed from <code>tmp/development_secret.txt</code> to <code>tmp/local_secret.txt</code>.</p><p>You can simply rename the previous file to <code>local_secret.txt</code> to continue using the same secret, or copy the key from the previous file to the new one.</p><p>Failure to do so will cause Rails to generate a new secret key in the new file <code>tmp/local_secret.txt</code> when the app loads.</p><p>This will invalidate all existing sessions/cookies in development and test environments, and also cause other signatures derived from <code>secret_key_base</code> to break, such as Active Storage/Action Text attachments.</p><p>Production and other environments are not affected.</p><h3 id="autoloaded-paths-are-no-longer-in-$load-path"><a class="anchorlink" href="#autoloaded-paths-are-no-longer-in-$load-path" data-turbo="false"><span>4.2</span> Autoloaded paths are no longer in $LOAD_PATH</a></h3><p>Starting from Rails 7.1, the directories managed by the autoloaders are no longer added to <code>$LOAD_PATH</code>. This means it won't be possible to load their files with a manual <code>require</code> call, which shouldn't be done anyway.</p><p>Reducing the size of <code>$LOAD_PATH</code> speeds up <code>require</code> calls for apps not using <code>bootsnap</code>, and reduces the size of the <code>bootsnap</code> cache for the others.</p><p>If you'd like to have these paths still in <code>$LOAD_PATH</code>, you can opt-in:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">config</span><span class="p">.</span><span class="nf">add_autoload_paths_to_load_path</span> <span class="o">=</span> <span class="kp">true</span> </code></pre> <button class="clipboard-button" data-clipboard-text="config.add_autoload_paths_to_load_path = true ">Copy</button> </div> <p>but we discourage doing so, classes and modules in the autoload paths are meant to be autoloaded. That is, just reference them.</p><p>The <code>lib</code> directory is not affected by this flag, it is added to <code>$LOAD_PATH</code> always.</p><h3 id="config-autoload-lib-and-config-autoload-lib-once"><a class="anchorlink" href="#config-autoload-lib-and-config-autoload-lib-once" data-turbo="false"><span>4.3</span> config.autoload_lib and config.autoload_lib_once</a></h3><p>If your application does not have <code>lib</code> in the autoload or autoload once paths, please skip this section. You can find that out by inspecting the output of</p><div class="interstitial code"> <pre><code class="highlight console"><span class="gp">#</span><span class="w"> </span>Print autoload paths. <span class="gp">$</span><span class="w"> </span><span class="nb">bin/rails </span>runner <span class="s1">'pp Rails.autoloaders.main.dirs'</span> <span class="go"> </span><span class="gp">#</span><span class="w"> </span>Print autoload once paths. <span class="gp">$</span><span class="w"> </span><span class="nb">bin/rails </span>runner <span class="s1">'pp Rails.autoloaders.once.dirs'</span> </code></pre> <button class="clipboard-button" data-clipboard-text="bin/rails runner 'pp Rails.autoloaders.main.dirs' bin/rails runner 'pp Rails.autoloaders.once.dirs' ">Copy</button> </div> <p>If your application already has <code>lib</code> in the autoload paths, normally there is configuration in <code>config/application.rb</code> that looks something like</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># Autoload lib, but do not eager load it (maybe overlooked).</span> <span class="n">config</span><span class="p">.</span><span class="nf">autoload_paths</span> <span class="o">&lt;&lt;</span> <span class="n">config</span><span class="p">.</span><span class="nf">root</span><span class="p">.</span><span class="nf">join</span><span class="p">(</span><span class="s2">"lib"</span><span class="p">)</span> </code></pre> <button class="clipboard-button" data-clipboard-text="# Autoload lib, but do not eager load it (maybe overlooked). config.autoload_paths << config.root.join(&quot;lib&quot;) ">Copy</button> </div> <p>or</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># Autoload and also eager load lib.</span> <span class="n">config</span><span class="p">.</span><span class="nf">autoload_paths</span> <span class="o">&lt;&lt;</span> <span class="n">config</span><span class="p">.</span><span class="nf">root</span><span class="p">.</span><span class="nf">join</span><span class="p">(</span><span class="s2">"lib"</span><span class="p">)</span> <span class="n">config</span><span class="p">.</span><span class="nf">eager_load_paths</span> <span class="o">&lt;&lt;</span> <span class="n">config</span><span class="p">.</span><span class="nf">root</span><span class="p">.</span><span class="nf">join</span><span class="p">(</span><span class="s2">"lib"</span><span class="p">)</span> </code></pre> <button class="clipboard-button" data-clipboard-text="# Autoload and also eager load lib. config.autoload_paths << config.root.join(&quot;lib&quot;) config.eager_load_paths << config.root.join(&quot;lib&quot;) ">Copy</button> </div> <p>or</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># Same, because all eager load paths become autoload paths too.</span> <span class="n">config</span><span class="p">.</span><span class="nf">eager_load_paths</span> <span class="o">&lt;&lt;</span> <span class="n">config</span><span class="p">.</span><span class="nf">root</span><span class="p">.</span><span class="nf">join</span><span class="p">(</span><span class="s2">"lib"</span><span class="p">)</span> </code></pre> <button class="clipboard-button" data-clipboard-text="# Same, because all eager load paths become autoload paths too. config.eager_load_paths << config.root.join(&quot;lib&quot;) ">Copy</button> </div> <p>That still works, but it is recommended to replace those lines with the more concise</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">config</span><span class="p">.</span><span class="nf">autoload_lib</span><span class="p">(</span><span class="ss">ignore: </span><span class="sx">%w(assets tasks)</span><span class="p">)</span> </code></pre> <button class="clipboard-button" data-clipboard-text="config.autoload_lib(ignore: %w(assets tasks)) ">Copy</button> </div> <p>Please, add to the <code>ignore</code> list any other <code>lib</code> subdirectories that do not contain <code>.rb</code> files, or that should not be reloaded or eager loaded. For example, if your application has <code>lib/templates</code>, <code>lib/generators</code>, or <code>lib/middleware</code>, you'd add their name relative to <code>lib</code>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">config</span><span class="p">.</span><span class="nf">autoload_lib</span><span class="p">(</span><span class="ss">ignore: </span><span class="sx">%w(assets tasks templates generators middleware)</span><span class="p">)</span> </code></pre> <button class="clipboard-button" data-clipboard-text="config.autoload_lib(ignore: %w(assets tasks templates generators middleware)) ">Copy</button> </div> <p>With that one-liner, the (non-ignored) code in <code>lib</code> will be also eager loaded if <code>config.eager_load</code> is <code>true</code> (the default in <code>production</code> mode). This is normally what you want, but if <code>lib</code> was not added to the eager load paths before and you still want it that way, please opt-out:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">Rails</span><span class="p">.</span><span class="nf">autoloaders</span><span class="p">.</span><span class="nf">main</span><span class="p">.</span><span class="nf">do_not_eager_load</span><span class="p">(</span><span class="n">config</span><span class="p">.</span><span class="nf">root</span><span class="p">.</span><span class="nf">join</span><span class="p">(</span><span class="s2">"lib"</span><span class="p">))</span> </code></pre> <button class="clipboard-button" data-clipboard-text="Rails.autoloaders.main.do_not_eager_load(config.root.join(&quot;lib&quot;)) ">Copy</button> </div> <p>The method <code>config.autoload_lib_once</code> is the analogous one if the application had <code>lib</code> in <code>config.autoload_once_paths</code>.</p><h3 id="activestorage-basecontroller-no-longer-includes-the-streaming-concern"><a class="anchorlink" href="#activestorage-basecontroller-no-longer-includes-the-streaming-concern" data-turbo="false"><span>4.4</span> <code>ActiveStorage::BaseController</code> no longer includes the streaming concern</a></h3><p>Application controllers that inherit from <code>ActiveStorage::BaseController</code> and use streaming to implement custom file serving logic must now explicitly include the <code>ActiveStorage::Streaming</code> module.</p><h3 id="memcachestore-and-rediscachestore-now-use-connection-pooling-by-default"><a class="anchorlink" href="#memcachestore-and-rediscachestore-now-use-connection-pooling-by-default" data-turbo="false"><span>4.5</span> <code>MemCacheStore</code> and <code>RedisCacheStore</code> now use connection pooling by default</a></h3><p>The <code>connection_pool</code> gem has been added as a dependency of the <code>activesupport</code> gem, and the <code>MemCacheStore</code> and <code>RedisCacheStore</code> now use connection pooling by default.</p><p>If you don't want to use connection pooling, set <code>:pool</code> option to <code>false</code> when configuring your 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>See the <a href="https://guides.rubyonrails.org/v7.1/caching_with_rails.html#connection-pool-options">caching with Rails</a> guide for more information.</p><h3 id="sqlite3adapter-now-configured-to-be-used-in-a-strict-strings-mode"><a class="anchorlink" href="#sqlite3adapter-now-configured-to-be-used-in-a-strict-strings-mode" data-turbo="false"><span>4.6</span> <code>SQLite3Adapter</code> now configured to be used in a strict strings mode</a></h3><p>The use of a strict strings mode disables double-quoted string literals.</p><p>SQLite has some quirks around double-quoted string literals. It first tries to consider double-quoted strings as identifier names, but if they don't exist it then considers them as string literals. Because of this, typos can silently go unnoticed. For example, it is possible to create an index for a non existing column. See <a href="https://www.sqlite.org/quirks.html#double_quoted_string_literals_are_accepted">SQLite documentation</a> for more details.</p><p>If you don't want to use <code>SQLite3Adapter</code> in a strict mode, you can disable this behavior:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># config/application.rb</span> <span class="n">config</span><span class="p">.</span><span class="nf">active_record</span><span class="p">.</span><span class="nf">sqlite3_adapter_strict_strings_by_default</span> <span class="o">=</span> <span class="kp">false</span> </code></pre> <button class="clipboard-button" data-clipboard-text="config.active_record.sqlite3_adapter_strict_strings_by_default = false ">Copy</button> </div> <h3 id="support-multiple-preview-paths-for-actionmailer-preview"><a class="anchorlink" href="#support-multiple-preview-paths-for-actionmailer-preview" data-turbo="false"><span>4.7</span> Support multiple preview paths for <code>ActionMailer::Preview</code></a></h3><p>Option <code>config.action_mailer.preview_path</code> is deprecated in favor of <code>config.action_mailer.preview_paths</code>. Appending paths to this configuration option will cause those paths to be used in the search for mailer previews.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">config</span><span class="p">.</span><span class="nf">action_mailer</span><span class="p">.</span><span class="nf">preview_paths</span> <span class="o">&lt;&lt;</span> <span class="s2">"</span><span class="si">#{</span><span class="no">Rails</span><span class="p">.</span><span class="nf">root</span><span class="si">}</span><span class="s2">/lib/mailer_previews"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="config.action_mailer.preview_paths << &quot;#{Rails.root}/lib/mailer_previews&quot; ">Copy</button> </div> <h3 id="config-i18n-raise-on-missing-translations-true-now-raises-on-any-missing-translation"><a class="anchorlink" href="#config-i18n-raise-on-missing-translations-true-now-raises-on-any-missing-translation" data-turbo="false"><span>4.8</span> <code>config.i18n.raise_on_missing_translations = true</code> now raises on any missing translation.</a></h3><p>Previously it would only raise when called in a view or controller. Now it will raise anytime <code>I18n.t</code> is provided an unrecognised key.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># with config.i18n.raise_on_missing_translations = true</span> <span class="c1"># in a view or controller:</span> <span class="n">t</span><span class="p">(</span><span class="s2">"missing.key"</span><span class="p">)</span> <span class="c1"># raises in 7.0, raises in 7.1</span> <span class="no">I18n</span><span class="p">.</span><span class="nf">t</span><span class="p">(</span><span class="s2">"missing.key"</span><span class="p">)</span> <span class="c1"># didn't raise in 7.0, raises in 7.1</span> <span class="c1"># anywhere:</span> <span class="no">I18n</span><span class="p">.</span><span class="nf">t</span><span class="p">(</span><span class="s2">"missing.key"</span><span class="p">)</span> <span class="c1"># didn't raise in 7.0, raises in 7.1</span> </code></pre> <button class="clipboard-button" data-clipboard-text="# with config.i18n.raise_on_missing_translations = true # in a view or controller: t(&quot;missing.key&quot;) # raises in 7.0, raises in 7.1 I18n.t(&quot;missing.key&quot;) # didn't raise in 7.0, raises in 7.1 # anywhere: I18n.t(&quot;missing.key&quot;) # didn't raise in 7.0, raises in 7.1 ">Copy</button> </div> <p>If you don't want this behaviour, you can set <code>config.i18n.raise_on_missing_translations = false</code>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># with config.i18n.raise_on_missing_translations = false</span> <span class="c1"># in a view or controller:</span> <span class="n">t</span><span class="p">(</span><span class="s2">"missing.key"</span><span class="p">)</span> <span class="c1"># didn't raise in 7.0, doesn't raise in 7.1</span> <span class="no">I18n</span><span class="p">.</span><span class="nf">t</span><span class="p">(</span><span class="s2">"missing.key"</span><span class="p">)</span> <span class="c1"># didn't raise in 7.0, doesn't raise in 7.1</span> <span class="c1"># anywhere:</span> <span class="no">I18n</span><span class="p">.</span><span class="nf">t</span><span class="p">(</span><span class="s2">"missing.key"</span><span class="p">)</span> <span class="c1"># didn't raise in 7.0, doesn't raise in 7.1</span> </code></pre> <button class="clipboard-button" data-clipboard-text="# with config.i18n.raise_on_missing_translations = false # in a view or controller: t(&quot;missing.key&quot;) # didn't raise in 7.0, doesn't raise in 7.1 I18n.t(&quot;missing.key&quot;) # didn't raise in 7.0, doesn't raise in 7.1 # anywhere: I18n.t(&quot;missing.key&quot;) # didn't raise in 7.0, doesn't raise in 7.1 ">Copy</button> </div> <p>Alternatively, you can customise the <code>I18n.exception_handler</code>. See the <a href="https://guides.rubyonrails.org/v7.1/i18n.html#using-different-exception-handlers">i18n guide</a> for more information.</p><p><code>AbstractController::Translation.raise_on_missing_translations</code> has been removed. This was a private API, if you were relying on it you should migrate to <code>config.i18n.raise_on_missing_translations</code> or to a custom exception handler.</p><h3 id="bin-rails-test-now-runs-test-prepare-task"><a class="anchorlink" href="#bin-rails-test-now-runs-test-prepare-task" data-turbo="false"><span>4.9</span> <code>bin/rails test</code> now runs <code>test:prepare</code> task</a></h3><p>When running tests via <code>bin/rails test</code>, the <code>rake test:prepare</code> task will run before tests run. If you've enhanced the <code>test:prepare</code> task, your enhancements will run before your tests. <code>tailwindcss-rails</code>, <code>jsbundling-rails</code>, and <code>cssbundling-rails</code> enhance this task, as do other third party gems.</p><p>See the <a href="https://guides.rubyonrails.org/testing.html#running-tests-in-continuous-integration-ci">Testing Rails Applications</a> guide for more information.</p><p>If you run a single file's tests (<code>bin/rails test test/models/user_test.rb</code>), <code>test:prepare</code> will not run before it.</p><h3 id="import-syntax-from-@rails-ujs-is-modified"><a class="anchorlink" href="#import-syntax-from-@rails-ujs-is-modified" data-turbo="false"><span>4.10</span> Import syntax from <code>@rails/ujs</code> is modified</a></h3><p>Starting from Rails 7.1, the syntax for importing modules from <code>@rails/ujs</code> is modified. Rails no longer supports the direct import of a module from <code>@rails/ujs</code>.</p><p>For example, attempting to import a function from the library will fail:</p><div class="interstitial code"> <pre><code class="highlight javascript"><span class="k">import</span> <span class="p">{</span> <span class="nx">fileInputSelector</span> <span class="p">}</span> <span class="k">from</span> <span class="dl">"</span><span class="s2">@rails/ujs</span><span class="dl">"</span> <span class="c1">// ERROR: export 'fileInputSelector' (imported as 'fileInputSelector') was not found in '@rails/ujs' (possible exports: default)</span> </code></pre> <button class="clipboard-button" data-clipboard-text="import { fileInputSelector } from &quot;@rails/ujs&quot; // ERROR: export 'fileInputSelector' (imported as 'fileInputSelector') was not found in '@rails/ujs' (possible exports: default) ">Copy</button> </div> <p>In Rails 7.1, users should first import the Rails object directly from <code>@rails/ujs</code>. Users can then import specific modules from the Rails object.</p><p>An example of imports in Rails 7.1 is shown below:</p><div class="interstitial code"> <pre><code class="highlight javascript"><span class="k">import</span> <span class="nx">Rails</span> <span class="k">from</span> <span class="dl">"</span><span class="s2">@rails/ujs</span><span class="dl">"</span> <span class="c1">// Alias the method</span> <span class="kd">const</span> <span class="nx">fileInputSelector</span> <span class="o">=</span> <span class="nx">Rails</span><span class="p">.</span><span class="nx">fileInputSelector</span> <span class="c1">// Alternatively, reference it from the Rails object where it is used</span> <span class="nx">Rails</span><span class="p">.</span><span class="nf">fileInputSelector</span><span class="p">(...)</span> </code></pre> <button class="clipboard-button" data-clipboard-text="import Rails from &quot;@rails/ujs&quot; // Alias the method const fileInputSelector = Rails.fileInputSelector // Alternatively, reference it from the Rails object where it is used Rails.fileInputSelector(...) ">Copy</button> </div> <h3 id="rails-logger-now-returns-an-activesupport-broadcastlogger-instance"><a class="anchorlink" href="#rails-logger-now-returns-an-activesupport-broadcastlogger-instance" data-turbo="false"><span>4.11</span> <code>Rails.logger</code> now returns an <code>ActiveSupport::BroadcastLogger</code> instance</a></h3><p>The <code>ActiveSupport::BroadcastLogger</code> class is a new logger that allows to broadcast logs to different sinks (STDOUT, a log file...) in an easy way.</p><p>The API to broadcast logs (using the <code>ActiveSupport::Logger.broadcast</code> method) was removed and was previously private. If your application or library was relying on this API, you need to make the following changes:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">logger</span> <span class="o">=</span> <span class="no">Logger</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="s2">"some_file.log"</span><span class="p">)</span> <span class="c1"># Before</span> <span class="no">Rails</span><span class="p">.</span><span class="nf">logger</span><span class="p">.</span><span class="nf">extend</span><span class="p">(</span><span class="no">ActiveSupport</span><span class="o">::</span><span class="no">Logger</span><span class="p">.</span><span class="nf">broadcast</span><span class="p">(</span><span class="n">logger</span><span class="p">))</span> <span class="c1"># After</span> <span class="no">Rails</span><span class="p">.</span><span class="nf">logger</span><span class="p">.</span><span class="nf">broadcast_to</span><span class="p">(</span><span class="n">logger</span><span class="p">)</span> </code></pre> <button class="clipboard-button" data-clipboard-text="logger = Logger.new(&quot;some_file.log&quot;) # Before Rails.logger.extend(ActiveSupport::Logger.broadcast(logger)) # After Rails.logger.broadcast_to(logger) ">Copy</button> </div> <p>If your application had configured a custom logger, <code>Rails.logger</code> will wrap and proxy all methods to it. No changes on your side are required to make it work.</p><p>If you need to access your custom logger instance, you can do so using the <code>broadcasts</code> method:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># config/application.rb</span> <span class="n">config</span><span class="p">.</span><span class="nf">logger</span> <span class="o">=</span> <span class="no">MyLogger</span><span class="p">.</span><span class="nf">new</span> <span class="c1"># Anywhere in your application</span> <span class="nb">puts</span> <span class="no">Rails</span><span class="p">.</span><span class="nf">logger</span><span class="p">.</span><span class="nf">class</span> <span class="c1">#=&gt; BroadcastLogger</span> <span class="nb">puts</span> <span class="no">Rails</span><span class="p">.</span><span class="nf">logger</span><span class="p">.</span><span class="nf">broadcasts</span> <span class="c1">#=&gt; [MyLogger]</span> </code></pre> <button class="clipboard-button" data-clipboard-text="config.logger = MyLogger.new # Anywhere in your application puts Rails.logger.class #=> BroadcastLogger puts Rails.logger.broadcasts #=> [MyLogger] ">Copy</button> </div> <h3 id="active-record-encryption-algorithm-changes"><a class="anchorlink" href="#active-record-encryption-algorithm-changes" data-turbo="false"><span>4.12</span> Active Record Encryption algorithm changes</a></h3><p>Active Record Encryption now uses SHA-256 as its hash digest algorithm. If you have data encrypted with previous Rails versions, there are two scenarios to consider:</p> <ol> <li><p>If you have <code>config.active_support.key_generator_hash_digest_class</code> configured as SHA-1 (the default before Rails 7.0), you need to configure SHA-1 for Active Record Encryption too:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">config</span><span class="p">.</span><span class="nf">active_record</span><span class="p">.</span><span class="nf">encryption</span><span class="p">.</span><span class="nf">hash_digest_class</span> <span class="o">=</span> <span class="no">OpenSSL</span><span class="o">::</span><span class="no">Digest</span><span class="o">::</span><span class="no">SHA1</span> </code></pre> <button class="clipboard-button" data-clipboard-text="config.active_record.encryption.hash_digest_class = OpenSSL::Digest::SHA1 ">Copy</button> </div></li> <li><p>If you have <code>config.active_support.key_generator_hash_digest_class</code> configured as SHA-256 (the new default in 7.0), then you need to configure SHA-256 for Active Record Encryption:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">config</span><span class="p">.</span><span class="nf">active_record</span><span class="p">.</span><span class="nf">encryption</span><span class="p">.</span><span class="nf">hash_digest_class</span> <span class="o">=</span> <span class="no">OpenSSL</span><span class="o">::</span><span class="no">Digest</span><span class="o">::</span><span class="no">SHA256</span> </code></pre> <button class="clipboard-button" data-clipboard-text="config.active_record.encryption.hash_digest_class = OpenSSL::Digest::SHA256 ">Copy</button> </div></li> </ol> <p>See the <a href="configuring.html#config-active-record-encryption-hash-digest-class">Configuring Rails Applications</a> guide for more information on <code>config.active_record.encryption.hash_digest_class</code>.</p><p>In addition, a new configuration <a href="configuring.html#config-active-record-encryption-support-sha1-for-non-deterministic-encryption"><code>config.active_record.encryption.support_sha1_for_non_deterministic_encryption</code></a> was introduced to resolve <a href="https://github.com/rails/rails/issues/42922">a bug</a> that caused some attributes to be encrypted using SHA-1 even when SHA-256 was configured via the aforementioned <code>hash_digest_class</code> configuration.</p><p>By default, <code>config.active_record.encryption.support_sha1_for_non_deterministic_encryption</code> is disabled in Rails 7.1. If you have data encrypted in a version of Rails &lt; 7.1 that you believe may be affected by the aforementioned bug, this configuration should be enabled:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">config</span><span class="p">.</span><span class="nf">active_record</span><span class="p">.</span><span class="nf">encryption</span><span class="p">.</span><span class="nf">support_sha1_for_non_deterministic_encryption</span> <span class="o">=</span> <span class="kp">true</span> </code></pre> <button class="clipboard-button" data-clipboard-text="config.active_record.encryption.support_sha1_for_non_deterministic_encryption = true ">Copy</button> </div> <p>If you are working with encrypted data, please carefully review the above.</p><h3 id="new-ways-to-handle-exceptions-in-controller-tests-integration-tests-and-system-tests"><a class="anchorlink" href="#new-ways-to-handle-exceptions-in-controller-tests-integration-tests-and-system-tests" data-turbo="false"><span>4.13</span> New ways to handle exceptions in Controller Tests, Integration Tests, and System Tests</a></h3><p>The <code>config.action_dispatch.show_exceptions</code> configuration controls how Action Pack handles exceptions raised while responding to requests.</p><p>Prior to Rails 7.1, setting <code>config.action_dispatch.show_exceptions = true</code> configured Action Pack to rescue exceptions and render appropriate HTML error pages, like rendering <code>public/404.html</code> with a <code>404 Not found</code> status code instead of raising an <code>ActiveRecord::RecordNotFound</code> exception. Setting <code>config.action_dispatch.show_exceptions = false</code> configured Action Pack to not rescue the exception. Prior to Rails 7.1, new applications were generated with a line in <code>config/environments/test.rb</code> that set <code>config.action_dispatch.show_exceptions = false</code>.</p><p>Rails 7.1 changes the acceptable values from <code>true</code> and <code>false</code> to <code>:all</code>, <code>:rescuable</code>, and <code>:none</code>.</p> <ul> <li><code>:all</code> - render HTML error pages for all exceptions (equivalent to <code>true</code>)</li> <li><code>:rescuable</code> - render HTML error pages for exceptions declared by <a href="/configuring.html#config-action-dispatch-rescue-responses"><code>config.action_dispatch.rescue_responses</code></a></li> <li><code>:none</code> (equivalent to <code>false</code>) - do not rescue from any exceptions</li> </ul> <p>Applications generated by Rails 7.1 or later set <code>config.action_dispatch.show_exceptions = :rescuable</code> in their <code>config/environments/test.rb</code>. When upgrading, existing applications can change <code>config.action_dispatch.show_exceptions = :rescuable</code> to utilize the new behavior, or replace the old values with the corresponding new ones (<code>true</code> replaces <code>:all</code>, <code>false</code> replaces <code>:none</code>).</p><h2 id="upgrading-from-rails-6-1-to-rails-7-0"><a class="anchorlink" href="#upgrading-from-rails-6-1-to-rails-7-0" data-turbo="false"><span>5</span> Upgrading from Rails 6.1 to Rails 7.0</a></h2><p>For more information on changes made to Rails 7.0 please see the <a href="7_0_release_notes.html">release notes</a>.</p><h3 id="actionview-helpers-urlhelper-button-to-changed-behavior"><a class="anchorlink" href="#actionview-helpers-urlhelper-button-to-changed-behavior" data-turbo="false"><span>5.1</span> <code>ActionView::Helpers::UrlHelper#button_to</code> changed behavior</a></h3><p>Starting from Rails 7.0 <code>button_to</code> renders a <code>form</code> tag with <code>patch</code> HTTP verb if a persisted Active Record object is used to build button URL. To keep current behavior consider explicitly passing <code>method:</code> option:</p><div class="interstitial code"> <pre><code class="highlight diff"><span class="gd">-button_to("Do a POST", [:my_custom_post_action_on_workshop, Workshop.find(1)]) </span><span class="gi">+button_to("Do a POST", [:my_custom_post_action_on_workshop, Workshop.find(1)], method: :post) </span></code></pre> <button class="clipboard-button" data-clipboard-text="-button_to(&quot;Do a POST&quot;, [:my_custom_post_action_on_workshop, Workshop.find(1)]) +button_to(&quot;Do a POST&quot;, [:my_custom_post_action_on_workshop, Workshop.find(1)], method: :post) ">Copy</button> </div> <p>or using helper to build the URL:</p><div class="interstitial code"> <pre><code class="highlight diff"><span class="gd">-button_to("Do a POST", [:my_custom_post_action_on_workshop, Workshop.find(1)]) </span><span class="gi">+button_to("Do a POST", my_custom_post_action_on_workshop_workshop_path(Workshop.find(1))) </span></code></pre> <button class="clipboard-button" data-clipboard-text="-button_to(&quot;Do a POST&quot;, [:my_custom_post_action_on_workshop, Workshop.find(1)]) +button_to(&quot;Do a POST&quot;, my_custom_post_action_on_workshop_workshop_path(Workshop.find(1))) ">Copy</button> </div> <h3 id="upgrading-from-rails-6-1-to-rails-7-0-spring"><a class="anchorlink" href="#upgrading-from-rails-6-1-to-rails-7-0-spring" data-turbo="false"><span>5.2</span> Spring</a></h3><p>If your application uses Spring, it needs to be upgraded to at least version 3.0.0. Otherwise you'll get</p><div class="interstitial code"> <pre><code class="highlight plaintext">undefined method `mechanism=' for ActiveSupport::Dependencies:Module </code></pre> <button class="clipboard-button" data-clipboard-text="undefined method `mechanism=' for ActiveSupport::Dependencies:Module ">Copy</button> </div> <p>Also, make sure <a href="configuring.html#config-cache-classes"><code>config.cache_classes</code></a> is set to <code>false</code> in <code>config/environments/test.rb</code>.</p><h3 id="sprockets-is-now-an-optional-dependency"><a class="anchorlink" href="#sprockets-is-now-an-optional-dependency" data-turbo="false"><span>5.3</span> Sprockets is now an optional dependency</a></h3><p>The gem <code>rails</code> doesn't depend on <code>sprockets-rails</code> anymore. If your application still needs to use Sprockets, make sure to add <code>sprockets-rails</code> to your Gemfile.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">gem</span> <span class="s2">"sprockets-rails"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="gem &quot;sprockets-rails&quot; ">Copy</button> </div> <h3 id="applications-need-to-run-in-zeitwerk-mode"><a class="anchorlink" href="#applications-need-to-run-in-zeitwerk-mode" data-turbo="false"><span>5.4</span> Applications need to run in <code>zeitwerk</code> mode</a></h3><p>Applications still running in <code>classic</code> mode have to switch to <code>zeitwerk</code> mode. Please check the <a href="https://guides.rubyonrails.org/v7.0/classic_to_zeitwerk_howto.html">Classic to Zeitwerk HOWTO</a> guide for details.</p><h3 id="the-setter-config-autoloader-has-been-deleted"><a class="anchorlink" href="#the-setter-config-autoloader-has-been-deleted" data-turbo="false"><span>5.5</span> The setter <code>config.autoloader=</code> has been deleted</a></h3><p>In Rails 7 there is no configuration point to set the autoloading mode, <code>config.autoloader=</code> has been deleted. If you had it set to <code>:zeitwerk</code> for whatever reason, just remove it.</p><h3 id="activesupport-dependencies-private-api-has-been-deleted"><a class="anchorlink" href="#activesupport-dependencies-private-api-has-been-deleted" data-turbo="false"><span>5.6</span> <code>ActiveSupport::Dependencies</code> private API has been deleted</a></h3><p>The private API of <code>ActiveSupport::Dependencies</code> has been deleted. That includes methods like <code>hook!</code>, <code>unhook!</code>, <code>depend_on</code>, <code>require_or_load</code>, <code>mechanism</code>, and many others.</p><p>A few of highlights:</p> <ul> <li>If you used <code>ActiveSupport::Dependencies.constantize</code> or <code>ActiveSupport::Dependencies.safe_constantize</code>, just change them to <code>String#constantize</code> or <code>String#safe_constantize</code>.</li> </ul> <div class="interstitial code"> <pre><code class="highlight ruby"> <span class="no">ActiveSupport</span><span class="o">::</span><span class="no">Dependencies</span><span class="p">.</span><span class="nf">constantize</span><span class="p">(</span><span class="s2">"User"</span><span class="p">)</span> <span class="c1"># NO LONGER POSSIBLE</span> <span class="s2">"User"</span><span class="p">.</span><span class="nf">constantize</span> <span class="c1"># 👍</span> </code></pre> <button class="clipboard-button" data-clipboard-text=" ActiveSupport::Dependencies.constantize(&quot;User&quot;) # NO LONGER POSSIBLE &quot;User&quot;.constantize # 👍 ">Copy</button> </div> <ul> <li><p>Any usage of <code>ActiveSupport::Dependencies.mechanism</code>, reader or writer, has to be replaced by accessing <code>config.cache_classes</code> accordingly.</p></li> <li><p>If you want to trace the activity of the autoloader, <code>ActiveSupport::Dependencies.verbose=</code> is no longer available, just throw <code>Rails.autoloaders.log!</code> in <code>config/application.rb</code>.</p></li> </ul> <p>Auxiliary internal classes or modules are also gone, like <code>ActiveSupport::Dependencies::Reference</code>, <code>ActiveSupport::Dependencies::Blamable</code>, and others.</p><h3 id="autoloading-during-initialization"><a class="anchorlink" href="#autoloading-during-initialization" data-turbo="false"><span>5.7</span> Autoloading during initialization</a></h3><p>Applications that autoloaded reloadable constants during initialization outside of <code>to_prepare</code> blocks got those constants unloaded and had this warning issued since Rails 6.0:</p><div class="interstitial code"> <pre><code class="highlight plaintext">DEPRECATION WARNING: Initialization autoloaded the constant .... Being able to do this is deprecated. Autoloading during initialization is going to be an error condition in future versions of Rails. ... </code></pre> <button class="clipboard-button" data-clipboard-text="DEPRECATION WARNING: Initialization autoloaded the constant .... Being able to do this is deprecated. Autoloading during initialization is going to be an error condition in future versions of Rails. ... ">Copy</button> </div> <p>If you still get this warning in the logs, please check the section about autoloading when the application boots in the <a href="https://guides.rubyonrails.org/v7.0/autoloading_and_reloading_constants.html#autoloading-when-the-application-boots">autoloading guide</a>. You'd get a <code>NameError</code> in Rails 7 otherwise.</p><p>Constants managed by the <code>once</code> autoloader can be autoloaded during initialization, and they can be used normally, no need for a <code>to_prepare</code> block. However, the <code>once</code> autoloader is now set up earlier to support that. If the application has custom inflections, and the <code>once</code> autoloader should be aware of them, you need to move the code in <code>config/initializers/inflections.rb</code> to the body of the application class definition in <code>config/application.rb</code>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">module</span> <span class="nn">MyApp</span> <span class="k">class</span> <span class="nc">Application</span> <span class="o">&lt;</span> <span class="no">Rails</span><span class="o">::</span><span class="no">Application</span> <span class="c1"># ...</span> <span class="no">ActiveSupport</span><span class="o">::</span><span class="no">Inflector</span><span class="p">.</span><span class="nf">inflections</span><span class="p">(</span><span class="ss">:en</span><span class="p">)</span> <span class="k">do</span> <span class="o">|</span><span class="n">inflect</span><span class="o">|</span> <span class="n">inflect</span><span class="p">.</span><span class="nf">acronym</span> <span class="s2">"HTML"</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="module MyApp class Application < Rails::Application # ... ActiveSupport::Inflector.inflections(:en) do |inflect| inflect.acronym &quot;HTML&quot; end end end ">Copy</button> </div> <h3 id="ability-to-configure-config-autoload-once-paths"><a class="anchorlink" href="#ability-to-configure-config-autoload-once-paths" data-turbo="false"><span>5.8</span> Ability to configure <code>config.autoload_once_paths</code></a></h3><p><a href="configuring.html#config-autoload-once-paths"><code>config.autoload_once_paths</code></a> can be set in the body of the application class defined in <code>config/application.rb</code> or in the configuration for environments in <code>config/environments/*</code>.</p><p>Similarly, engines can configure that collection in the class body of the engine class or in the configuration for environments.</p><p>After that, the collection is frozen, and you can autoload from those paths. In particular, you can autoload from there during initialization. They are managed by the <code>Rails.autoloaders.once</code> autoloader, which does not reload, only autoloads/eager loads.</p><p>If you configured this setting after the environments configuration has been processed and are getting <code>FrozenError</code>, please just move the code.</p><h3 id="actiondispatch-request-content-type-now-returns-content-type-header-as-it-is"><a class="anchorlink" href="#actiondispatch-request-content-type-now-returns-content-type-header-as-it-is" data-turbo="false"><span>5.9</span> <code>ActionDispatch::Request#content_type</code> now returns Content-Type header as it is.</a></h3><p>Previously, <code>ActionDispatch::Request#content_type</code> returned value does NOT contain charset part. This behavior changed to returned Content-Type header containing charset part as it is.</p><p>If you want just MIME type, please use <code>ActionDispatch::Request#media_type</code> instead.</p><p>Before:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">request</span> <span class="o">=</span> <span class="no">ActionDispatch</span><span class="o">::</span><span class="no">Request</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="s2">"CONTENT_TYPE"</span> <span class="o">=&gt;</span> <span class="s2">"text/csv; header=present; charset=utf-16"</span><span class="p">,</span> <span class="s2">"REQUEST_METHOD"</span> <span class="o">=&gt;</span> <span class="s2">"GET"</span><span class="p">)</span> <span class="n">request</span><span class="p">.</span><span class="nf">content_type</span> <span class="c1">#=&gt; "text/csv"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="request = ActionDispatch::Request.new(&quot;CONTENT_TYPE&quot; => &quot;text/csv; header=present; charset=utf-16&quot;, &quot;REQUEST_METHOD&quot; => &quot;GET&quot;) request.content_type #=> &quot;text/csv&quot; ">Copy</button> </div> <p>After:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">request</span> <span class="o">=</span> <span class="no">ActionDispatch</span><span class="o">::</span><span class="no">Request</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="s2">"Content-Type"</span> <span class="o">=&gt;</span> <span class="s2">"text/csv; header=present; charset=utf-16"</span><span class="p">,</span> <span class="s2">"REQUEST_METHOD"</span> <span class="o">=&gt;</span> <span class="s2">"GET"</span><span class="p">)</span> <span class="n">request</span><span class="p">.</span><span class="nf">content_type</span> <span class="c1">#=&gt; "text/csv; header=present; charset=utf-16"</span> <span class="n">request</span><span class="p">.</span><span class="nf">media_type</span> <span class="c1">#=&gt; "text/csv"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="request = ActionDispatch::Request.new(&quot;Content-Type&quot; => &quot;text/csv; header=present; charset=utf-16&quot;, &quot;REQUEST_METHOD&quot; => &quot;GET&quot;) request.content_type #=> &quot;text/csv; header=present; charset=utf-16&quot; request.media_type #=> &quot;text/csv&quot; ">Copy</button> </div> <h3 id="key-generator-digest-class-change-requires-a-cookie-rotator"><a class="anchorlink" href="#key-generator-digest-class-change-requires-a-cookie-rotator" data-turbo="false"><span>5.10</span> Key generator digest class change requires a cookie rotator</a></h3><p>The default digest class for the key generator is changing from SHA1 to SHA256. This has consequences in any encrypted message generated by Rails, including encrypted cookies.</p><p>In order to be able to read messages using the old digest class it is necessary to register a rotator. Failing to do so may result in users having their sessions invalidated during the upgrade.</p><p>The following is an example for rotator for the encrypted and the signed cookies.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># config/initializers/cookie_rotator.rb</span> <span class="no">Rails</span><span class="p">.</span><span class="nf">application</span><span class="p">.</span><span class="nf">config</span><span class="p">.</span><span class="nf">after_initialize</span> <span class="k">do</span> <span class="no">Rails</span><span class="p">.</span><span class="nf">application</span><span class="p">.</span><span class="nf">config</span><span class="p">.</span><span class="nf">action_dispatch</span><span class="p">.</span><span class="nf">cookies_rotations</span><span class="p">.</span><span class="nf">tap</span> <span class="k">do</span> <span class="o">|</span><span class="n">cookies</span><span class="o">|</span> <span class="n">authenticated_encrypted_cookie_salt</span> <span class="o">=</span> <span class="no">Rails</span><span class="p">.</span><span class="nf">application</span><span class="p">.</span><span class="nf">config</span><span class="p">.</span><span class="nf">action_dispatch</span><span class="p">.</span><span class="nf">authenticated_encrypted_cookie_salt</span> <span class="n">signed_cookie_salt</span> <span class="o">=</span> <span class="no">Rails</span><span class="p">.</span><span class="nf">application</span><span class="p">.</span><span class="nf">config</span><span class="p">.</span><span class="nf">action_dispatch</span><span class="p">.</span><span class="nf">signed_cookie_salt</span> <span class="n">secret_key_base</span> <span class="o">=</span> <span class="no">Rails</span><span class="p">.</span><span class="nf">application</span><span class="p">.</span><span class="nf">secret_key_base</span> <span class="n">key_generator</span> <span class="o">=</span> <span class="no">ActiveSupport</span><span class="o">::</span><span class="no">KeyGenerator</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span> <span class="n">secret_key_base</span><span class="p">,</span> <span class="ss">iterations: </span><span class="mi">1000</span><span class="p">,</span> <span class="ss">hash_digest_class: </span><span class="no">OpenSSL</span><span class="o">::</span><span class="no">Digest</span><span class="o">::</span><span class="no">SHA1</span> <span class="p">)</span> <span class="n">key_len</span> <span class="o">=</span> <span class="no">ActiveSupport</span><span class="o">::</span><span class="no">MessageEncryptor</span><span class="p">.</span><span class="nf">key_len</span> <span class="n">old_encrypted_secret</span> <span class="o">=</span> <span class="n">key_generator</span><span class="p">.</span><span class="nf">generate_key</span><span class="p">(</span><span class="n">authenticated_encrypted_cookie_salt</span><span class="p">,</span> <span class="n">key_len</span><span class="p">)</span> <span class="n">old_signed_secret</span> <span class="o">=</span> <span class="n">key_generator</span><span class="p">.</span><span class="nf">generate_key</span><span class="p">(</span><span class="n">signed_cookie_salt</span><span class="p">)</span> <span class="n">cookies</span><span class="p">.</span><span class="nf">rotate</span> <span class="ss">:encrypted</span><span class="p">,</span> <span class="n">old_encrypted_secret</span> <span class="n">cookies</span><span class="p">.</span><span class="nf">rotate</span> <span class="ss">:signed</span><span class="p">,</span> <span class="n">old_signed_secret</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="Rails.application.config.after_initialize do Rails.application.config.action_dispatch.cookies_rotations.tap do |cookies| authenticated_encrypted_cookie_salt = Rails.application.config.action_dispatch.authenticated_encrypted_cookie_salt signed_cookie_salt = Rails.application.config.action_dispatch.signed_cookie_salt secret_key_base = Rails.application.secret_key_base key_generator = ActiveSupport::KeyGenerator.new( secret_key_base, iterations: 1000, hash_digest_class: OpenSSL::Digest::SHA1 ) key_len = ActiveSupport::MessageEncryptor.key_len old_encrypted_secret = key_generator.generate_key(authenticated_encrypted_cookie_salt, key_len) old_signed_secret = key_generator.generate_key(signed_cookie_salt) cookies.rotate :encrypted, old_encrypted_secret cookies.rotate :signed, old_signed_secret end end ">Copy</button> </div> <h3 id="digest-class-for-activesupport-digest-changing-to-sha256"><a class="anchorlink" href="#digest-class-for-activesupport-digest-changing-to-sha256" data-turbo="false"><span>5.11</span> Digest class for ActiveSupport::Digest changing to SHA256</a></h3><p>The default digest class for ActiveSupport::Digest is changing from SHA1 to SHA256. This has consequences for things like Etags that will change and cache keys as well. Changing these keys can have impact on cache hit rates, so be careful and watch out for this when upgrading to the new hash.</p><h3 id="new-activesupport-cache-serialization-format"><a class="anchorlink" href="#new-activesupport-cache-serialization-format" data-turbo="false"><span>5.12</span> New ActiveSupport::Cache serialization format</a></h3><p>A faster and more compact serialization format was introduced.</p><p>To enable it you must set <code>config.active_support.cache_format_version = 7.0</code>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># config/application.rb</span> <span class="n">config</span><span class="p">.</span><span class="nf">load_defaults</span> <span class="mf">6.1</span> <span class="n">config</span><span class="p">.</span><span class="nf">active_support</span><span class="p">.</span><span class="nf">cache_format_version</span> <span class="o">=</span> <span class="mf">7.0</span> </code></pre> <button class="clipboard-button" data-clipboard-text=" config.load_defaults 6.1 config.active_support.cache_format_version = 7.0 ">Copy</button> </div> <p>Or simply:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># config/application.rb</span> <span class="n">config</span><span class="p">.</span><span class="nf">load_defaults</span> <span class="mf">7.0</span> </code></pre> <button class="clipboard-button" data-clipboard-text=" config.load_defaults 7.0 ">Copy</button> </div> <p>However Rails 6.1 applications are not able to read this new serialization format, so to ensure a seamless upgrade you must first deploy your Rails 7.0 upgrade with <code>config.active_support.cache_format_version = 6.1</code>, and then only once all Rails processes have been updated you can set <code>config.active_support.cache_format_version = 7.0</code>.</p><p>Rails 7.0 is able to read both formats so the cache won't be invalidated during the upgrade.</p><h3 id="active-storage-video-preview-image-generation"><a class="anchorlink" href="#active-storage-video-preview-image-generation" data-turbo="false"><span>5.13</span> Active Storage video preview image generation</a></h3><p>Video preview image generation now uses FFmpeg's scene change detection to generate more meaningful preview images. Previously the first frame of the video would be used and that caused problems if the video faded in from black. This change requires FFmpeg v3.4+.</p><h3 id="active-storage-default-variant-processor-changed-to-vips"><a class="anchorlink" href="#active-storage-default-variant-processor-changed-to-vips" data-turbo="false"><span>5.14</span> Active Storage default variant processor changed to <code>:vips</code></a></h3><p>For new apps, image transformation will use libvips instead of ImageMagick. This will reduce the time taken to generate variants as well as CPU and memory usage, improving response times in apps that rely on Active Storage to serve their images.</p><p>The <code>:mini_magick</code> option is not being deprecated, so it is fine to keep using it.</p><p>To migrate an existing app to libvips, set:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">Rails</span><span class="p">.</span><span class="nf">application</span><span class="p">.</span><span class="nf">config</span><span class="p">.</span><span class="nf">active_storage</span><span class="p">.</span><span class="nf">variant_processor</span> <span class="o">=</span> <span class="ss">:vips</span> </code></pre> <button class="clipboard-button" data-clipboard-text="Rails.application.config.active_storage.variant_processor = :vips ">Copy</button> </div> <p>You will then need to change existing image transformation code to the <code>image_processing</code> macros, and replace ImageMagick's options with libvips' options.</p><h4 id="replace-resize-with-resize-to-limit"><a class="anchorlink" href="#replace-resize-with-resize-to-limit" data-turbo="false"><span>5.14.1</span> Replace resize with resize_to_limit</a></h4><div class="interstitial code"> <pre><code class="highlight diff"><span class="gd">- variant(resize: "100x") </span><span class="gi">+ variant(resize_to_limit: [100, nil]) </span></code></pre> <button class="clipboard-button" data-clipboard-text="- variant(resize: &quot;100x&quot;) + variant(resize_to_limit: [100, nil]) ">Copy</button> </div> <p>If you don't do this, when you switch to vips you will see this error: <code>no implicit conversion to float from string</code>.</p><h4 id="use-an-array-when-cropping"><a class="anchorlink" href="#use-an-array-when-cropping" data-turbo="false"><span>5.14.2</span> Use an array when cropping</a></h4><div class="interstitial code"> <pre><code class="highlight diff"><span class="gd">- variant(crop: "1920x1080+0+0") </span><span class="gi">+ variant(crop: [0, 0, 1920, 1080]) </span></code></pre> <button class="clipboard-button" data-clipboard-text="- variant(crop: &quot;1920x1080+0+0&quot;) + variant(crop: [0, 0, 1920, 1080]) ">Copy</button> </div> <p>If you don't do this when migrating to vips, you will see the following error: <code>unable to call crop: you supplied 2 arguments, but operation needs 5</code>.</p><h4 id="clamp-your-crop-values"><a class="anchorlink" href="#clamp-your-crop-values" data-turbo="false"><span>5.14.3</span> Clamp your crop values:</a></h4><p>Vips is more strict than ImageMagick when it comes to cropping:</p> <ol> <li>It will not crop if <code>x</code> and/or <code>y</code> are negative values. e.g.: <code>[-10, -10, 100, 100]</code></li> <li>It will not crop if position (<code>x</code> or <code>y</code>) plus crop dimension (<code>width</code>, <code>height</code>) is larger than the image. e.g.: a 125x125 image and a crop of <code>[50, 50, 100, 100]</code></li> </ol> <p>If you don't do this when migrating to vips, you will see the following error: <code>extract_area: bad extract area</code></p><h4 id="adjust-the-background-color-used-for-resize-and-pad"><a class="anchorlink" href="#adjust-the-background-color-used-for-resize-and-pad" data-turbo="false"><span>5.14.4</span> Adjust the background color used for <code>resize_and_pad</code></a></h4><p>Vips uses black as the default background color <code>resize_and_pad</code>, instead of white like ImageMagick. Fix that by using the <code>background</code> option:</p><div class="interstitial code"> <pre><code class="highlight diff"><span class="gd">- variant(resize_and_pad: [300, 300]) </span><span class="gi">+ variant(resize_and_pad: [300, 300, background: [255]]) </span></code></pre> <button class="clipboard-button" data-clipboard-text="- variant(resize_and_pad: [300, 300]) + variant(resize_and_pad: [300, 300, background: [255]]) ">Copy</button> </div> <h4 id="remove-any-exif-based-rotation"><a class="anchorlink" href="#remove-any-exif-based-rotation" data-turbo="false"><span>5.14.5</span> Remove any EXIF based rotation</a></h4><p>Vips will auto rotate images using the EXIF value when processing variants. If you were storing rotation values from user uploaded photos to apply rotation with ImageMagick, you must stop doing that:</p><div class="interstitial code"> <pre><code class="highlight diff"><span class="gd">- variant(format: :jpg, rotate: rotation_value) </span><span class="gi">+ variant(format: :jpg) </span></code></pre> <button class="clipboard-button" data-clipboard-text="- variant(format: :jpg, rotate: rotation_value) + variant(format: :jpg) ">Copy</button> </div> <h4 id="replace-monochrome-with-colourspace"><a class="anchorlink" href="#replace-monochrome-with-colourspace" data-turbo="false"><span>5.14.6</span> Replace monochrome with colourspace</a></h4><p>Vips uses a different option to make monochrome images:</p><div class="interstitial code"> <pre><code class="highlight diff"><span class="gd">- variant(monochrome: true) </span><span class="gi">+ variant(colourspace: "b-w") </span></code></pre> <button class="clipboard-button" data-clipboard-text="- variant(monochrome: true) + variant(colourspace: &quot;b-w&quot;) ">Copy</button> </div> <h4 id="switch-to-libvips-options-for-compressing-images"><a class="anchorlink" href="#switch-to-libvips-options-for-compressing-images" data-turbo="false"><span>5.14.7</span> Switch to libvips options for compressing images</a></h4><p>JPEG</p><div class="interstitial code"> <pre><code class="highlight diff"><span class="gd">- variant(strip: true, quality: 80, interlace: "JPEG", sampling_factor: "4:2:0", colorspace: "sRGB") </span><span class="gi">+ variant(saver: { strip: true, quality: 80, interlace: true }) </span></code></pre> <button class="clipboard-button" data-clipboard-text="- variant(strip: true, quality: 80, interlace: &quot;JPEG&quot;, sampling_factor: &quot;4:2:0&quot;, colorspace: &quot;sRGB&quot;) + variant(saver: { strip: true, quality: 80, interlace: true }) ">Copy</button> </div> <p>PNG</p><div class="interstitial code"> <pre><code class="highlight diff"><span class="gd">- variant(strip: true, quality: 75) </span><span class="gi">+ variant(saver: { strip: true, compression: 9 }) </span></code></pre> <button class="clipboard-button" data-clipboard-text="- variant(strip: true, quality: 75) + variant(saver: { strip: true, compression: 9 }) ">Copy</button> </div> <p>WEBP</p><div class="interstitial code"> <pre><code class="highlight diff"><span class="gd">- variant(strip: true, quality: 75, define: { webp: { lossless: false, alpha_quality: 85, thread_level: 1 } }) </span><span class="gi">+ variant(saver: { strip: true, quality: 75, lossless: false, alpha_q: 85, reduction_effort: 6, smart_subsample: true }) </span></code></pre> <button class="clipboard-button" data-clipboard-text="- variant(strip: true, quality: 75, define: { webp: { lossless: false, alpha_quality: 85, thread_level: 1 } }) + variant(saver: { strip: true, quality: 75, lossless: false, alpha_q: 85, reduction_effort: 6, smart_subsample: true }) ">Copy</button> </div> <p>GIF</p><div class="interstitial code"> <pre><code class="highlight diff"><span class="gd">- variant(layers: "Optimize") </span><span class="gi">+ variant(saver: { optimize_gif_frames: true, optimize_gif_transparency: true }) </span></code></pre> <button class="clipboard-button" data-clipboard-text="- variant(layers: &quot;Optimize&quot;) + variant(saver: { optimize_gif_frames: true, optimize_gif_transparency: true }) ">Copy</button> </div> <h4 id="deploy-to-production"><a class="anchorlink" href="#deploy-to-production" data-turbo="false"><span>5.14.8</span> Deploy to production</a></h4><p>Active Storage encodes into the url for the image the list of transformations that must be performed. If your app is caching these urls, your images will break after you deploy the new code to production. Because of this you must manually invalidate your affected cache keys.</p><p>For example, if you have something like this in a view:</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">image_tag</span> <span class="n">product</span><span class="p">.</span><span class="nf">cover_photo</span><span class="p">.</span><span class="nf">variant</span><span class="p">(</span><span class="ss">resize: </span><span class="s2">"200x"</span><span class="p">)</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 %> <%= image_tag product.cover_photo.variant(resize: &quot;200x&quot;) %> <% end %> <% end %> ">Copy</button> </div> <p>You can invalidate the cache either by touching the product, or changing the cache key:</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="p">[</span><span class="s2">"v2"</span><span class="p">,</span> <span class="n">product</span><span class="p">]</span> <span class="k">do</span> <span class="cp">%&gt;</span> <span class="cp">&lt;%=</span> <span class="n">image_tag</span> <span class="n">product</span><span class="p">.</span><span class="nf">cover_photo</span><span class="p">.</span><span class="nf">variant</span><span class="p">(</span><span class="ss">resize_to_limit: </span><span class="p">[</span><span class="mi">200</span><span class="p">,</span> <span class="kp">nil</span><span class="p">])</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 [&quot;v2&quot;, product] do %> <%= image_tag product.cover_photo.variant(resize_to_limit: [200, nil]) %> <% end %> <% end %> ">Copy</button> </div> <h3 id="rails-version-is-now-included-in-the-active-record-schema-dump"><a class="anchorlink" href="#rails-version-is-now-included-in-the-active-record-schema-dump" data-turbo="false"><span>5.15</span> Rails version is now included in the Active Record schema dump</a></h3><p>Rails 7.0 changed some default values for some column types. To avoid that application upgrading from 6.1 to 7.0 load the current schema using the new 7.0 defaults, Rails now includes the version of the framework in the schema dump.</p><p>Before loading the schema for the first time in Rails 7.0, make sure to run <code>rails app:update</code> to ensure that the version of the schema is included in the schema dump.</p><p>The schema file will look like this:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># This file is auto-generated from the current state of the database. Instead</span> <span class="c1"># of editing this file, please use the migrations feature of Active Record to</span> <span class="c1"># incrementally modify your database, and then regenerate this schema definition.</span> <span class="c1">#</span> <span class="c1"># This file is the source Rails uses to define your schema when running `bin/rails</span> <span class="c1"># db:schema:load`. When creating a new database, `bin/rails db:schema:load` tends to</span> <span class="c1"># be faster and is potentially less error prone than running all of your</span> <span class="c1"># migrations from scratch. Old migrations may fail to apply correctly if those</span> <span class="c1"># migrations use external dependencies or application code.</span> <span class="c1">#</span> <span class="c1"># It's strongly recommended that you check this file into your version control system.</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Schema</span><span class="p">[</span><span class="mf">6.1</span><span class="p">].</span><span class="nf">define</span><span class="p">(</span><span class="ss">version: </span><span class="mi">2022_01_28_123512</span><span class="p">)</span> <span class="k">do</span> <span class="c1"># ...</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="# This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # This file is the source Rails uses to define your schema when running `bin/rails # db:schema:load`. When creating a new database, `bin/rails db:schema:load` tends to # be faster and is potentially less error prone than running all of your # migrations from scratch. Old migrations may fail to apply correctly if those # migrations use external dependencies or application code. # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema[6.1].define(version: 2022_01_28_123512) do # ... end ">Copy</button> </div> <div class="interstitial note"><p>The first time you dump the schema with Rails 7.0, you will see many changes to that file, including some column information. Make sure to review the new schema file content and commit it to your repository.</p></div><h2 id="upgrading-from-rails-6-0-to-rails-6-1"><a class="anchorlink" href="#upgrading-from-rails-6-0-to-rails-6-1" data-turbo="false"><span>6</span> Upgrading from Rails 6.0 to Rails 6.1</a></h2><p>For more information on changes made to Rails 6.1 please see the <a href="6_1_release_notes.html">release notes</a>.</p><h3 id="rails-application-config-for-return-value-no-longer-supports-access-with-string-keys"><a class="anchorlink" href="#rails-application-config-for-return-value-no-longer-supports-access-with-string-keys" data-turbo="false"><span>6.1</span> <code>Rails.application.config_for</code> return value no longer supports access with String keys.</a></h3><p>Given a configuration file like this:</p><div class="interstitial code"> <pre><code class="highlight yaml"><span class="c1"># config/example.yml</span> <span class="na">development</span><span class="pi">:</span> <span class="na">options</span><span class="pi">:</span> <span class="na">key</span><span class="pi">:</span> <span class="s">value</span> </code></pre> <button class="clipboard-button" data-clipboard-text="development: options: key: value ">Copy</button> </div> <div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">Rails</span><span class="p">.</span><span class="nf">application</span><span class="p">.</span><span class="nf">config_for</span><span class="p">(</span><span class="ss">:example</span><span class="p">).</span><span class="nf">options</span> </code></pre> <button class="clipboard-button" data-clipboard-text="Rails.application.config_for(:example).options ">Copy</button> </div> <p>This used to return a hash on which you could access values with String keys. That was deprecated in 6.0, and now doesn't work anymore.</p><p>You can call <code>with_indifferent_access</code> on the return value of <code>config_for</code> if you still want to access values with String keys, e.g.:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">Rails</span><span class="p">.</span><span class="nf">application</span><span class="p">.</span><span class="nf">config_for</span><span class="p">(</span><span class="ss">:example</span><span class="p">).</span><span class="nf">with_indifferent_access</span><span class="p">.</span><span class="nf">dig</span><span class="p">(</span><span class="s2">"options"</span><span class="p">,</span> <span class="s2">"key"</span><span class="p">)</span> </code></pre> <button class="clipboard-button" data-clipboard-text="Rails.application.config_for(:example).with_indifferent_access.dig(&quot;options&quot;, &quot;key&quot;) ">Copy</button> </div> <h3 id="response-s-content-type-when-using-respond-to-any"><a class="anchorlink" href="#response-s-content-type-when-using-respond-to-any" data-turbo="false"><span>6.2</span> Response's Content-Type when using <code>respond_to#any</code></a></h3><p>The Content-Type header returned in the response can differ from what Rails 6.0 returned, more specifically if your application uses <code>respond_to { |format| format.any }</code>. The Content-Type will now be based on the given block rather than the request's format.</p><p>Example:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">def</span> <span class="nf">my_action</span> <span class="n">respond_to</span> <span class="k">do</span> <span class="o">|</span><span class="nb">format</span><span class="o">|</span> <span class="nb">format</span><span class="p">.</span><span class="nf">any</span> <span class="p">{</span> <span class="n">render</span><span class="p">(</span><span class="ss">json: </span><span class="p">{</span> <span class="ss">foo: </span><span class="s2">"bar"</span> <span class="p">})</span> <span class="p">}</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="def my_action respond_to do |format| format.any { render(json: { foo: &quot;bar&quot; }) } end end ">Copy</button> </div> <div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">get</span><span class="p">(</span><span class="s2">"my_action.csv"</span><span class="p">)</span> </code></pre> <button class="clipboard-button" data-clipboard-text="get(&quot;my_action.csv&quot;) ">Copy</button> </div> <p>Previous behavior was returning a <code>text/csv</code> response's Content-Type which is inaccurate since a JSON response is being rendered. Current behavior correctly returns a <code>application/json</code> response's Content-Type.</p><p>If your application relies on the previous incorrect behavior, you are encouraged to specify which formats your action accepts, i.e.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="nb">format</span><span class="p">.</span><span class="nf">any</span><span class="p">(</span><span class="ss">:xml</span><span class="p">,</span> <span class="ss">:json</span><span class="p">)</span> <span class="p">{</span> <span class="n">render</span> <span class="n">request</span><span class="p">.</span><span class="nf">format</span><span class="p">.</span><span class="nf">to_sym</span> <span class="o">=&gt;</span> <span class="vi">@people</span> <span class="p">}</span> </code></pre> <button class="clipboard-button" data-clipboard-text="format.any(:xml, :json) { render request.format.to_sym => @people } ">Copy</button> </div> <h3 id="activesupport-callbacks-halted-callback-hook-now-receive-a-second-argument"><a class="anchorlink" href="#activesupport-callbacks-halted-callback-hook-now-receive-a-second-argument" data-turbo="false"><span>6.3</span> <code>ActiveSupport::Callbacks#halted_callback_hook</code> now receive a second argument</a></h3><p>Active Support allows you to override the <code>halted_callback_hook</code> whenever a callback halts the chain. This method now receives a second argument which is the name of the callback being halted. If you have classes that override this method, make sure it accepts two arguments. Note that this is a breaking change without a prior deprecation cycle (for performance reasons).</p><p>Example:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">Book</span> <span class="o">&lt;</span> <span class="no">ApplicationRecord</span> <span class="n">before_save</span> <span class="p">{</span> <span class="kp">throw</span><span class="p">(</span><span class="ss">:abort</span><span class="p">)</span> <span class="p">}</span> <span class="n">before_create</span> <span class="p">{</span> <span class="kp">throw</span><span class="p">(</span><span class="ss">:abort</span><span class="p">)</span> <span class="p">}</span> <span class="k">def</span> <span class="nf">halted_callback_hook</span><span class="p">(</span><span class="n">filter</span><span class="p">,</span> <span class="n">callback_name</span><span class="p">)</span> <span class="c1"># =&gt; This method now accepts 2 arguments instead of 1</span> <span class="no">Rails</span><span class="p">.</span><span class="nf">logger</span><span class="p">.</span><span class="nf">info</span><span class="p">(</span><span class="s2">"Book couldn't be </span><span class="si">#{</span><span class="n">callback_name</span><span class="si">}</span><span class="s2">d"</span><span class="p">)</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class Book < ApplicationRecord before_save { throw(:abort) } before_create { throw(:abort) } def halted_callback_hook(filter, callback_name) # => This method now accepts 2 arguments instead of 1 Rails.logger.info(&quot;Book couldn't be #{callback_name}d&quot;) end end ">Copy</button> </div> <h3 id="the-helper-class-method-in-controllers-uses-string-constantize"><a class="anchorlink" href="#the-helper-class-method-in-controllers-uses-string-constantize" data-turbo="false"><span>6.4</span> The <code>helper</code> class method in controllers uses <code>String#constantize</code></a></h3><p>Conceptually, before Rails 6.1</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">helper</span> <span class="s2">"foo/bar"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="helper &quot;foo/bar&quot; ">Copy</button> </div> <p>resulted in</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">require_dependency</span> <span class="s2">"foo/bar_helper"</span> <span class="n">module_name</span> <span class="o">=</span> <span class="s2">"foo/bar_helper"</span><span class="p">.</span><span class="nf">camelize</span> <span class="n">module_name</span><span class="p">.</span><span class="nf">constantize</span> </code></pre> <button class="clipboard-button" data-clipboard-text="require_dependency &quot;foo/bar_helper&quot; module_name = &quot;foo/bar_helper&quot;.camelize module_name.constantize ">Copy</button> </div> <p>Now it does this instead:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">prefix</span> <span class="o">=</span> <span class="s2">"foo/bar"</span><span class="p">.</span><span class="nf">camelize</span> <span class="s2">"</span><span class="si">#{</span><span class="n">prefix</span><span class="si">}</span><span class="s2">Helper"</span><span class="p">.</span><span class="nf">constantize</span> </code></pre> <button class="clipboard-button" data-clipboard-text="prefix = &quot;foo/bar&quot;.camelize &quot;#{prefix}Helper&quot;.constantize ">Copy</button> </div> <p>This change is backwards compatible for the majority of applications, in which case you do not need to do anything.</p><p>Technically, however, controllers could configure <code>helpers_path</code> to point to a directory in <code>$LOAD_PATH</code> that was not in the autoload paths. That use case is no longer supported out of the box. If the helper module is not autoloadable, the application is responsible for loading it before calling <code>helper</code>.</p><h3 id="redirection-to-https-from-http-will-now-use-the-308-http-status-code"><a class="anchorlink" href="#redirection-to-https-from-http-will-now-use-the-308-http-status-code" data-turbo="false"><span>6.5</span> Redirection to HTTPS from HTTP will now use the 308 HTTP status code</a></h3><p>The default HTTP status code used in <code>ActionDispatch::SSL</code> when redirecting non-GET/HEAD requests from HTTP to HTTPS has been changed to <code>308</code> as defined in <a href="https://tools.ietf.org/html/rfc7538">https://tools.ietf.org/html/rfc7538</a>.</p><h3 id="active-storage-now-requires-image-processing"><a class="anchorlink" href="#active-storage-now-requires-image-processing" data-turbo="false"><span>6.6</span> Active Storage now requires Image Processing</a></h3><p>When processing variants in Active Storage, it's now required to have the <a href="https://github.com/janko/image_processing">image_processing gem</a> bundled instead of directly using <code>mini_magick</code>. Image Processing is configured by default to use <code>mini_magick</code> behind the scenes, so the easiest way to upgrade is by replacing the <code>mini_magick</code> gem for the <code>image_processing</code> gem and making sure to remove the explicit usage of <code>combine_options</code> since it's no longer needed.</p><p>For readability, you may wish to change raw <code>resize</code> calls to <code>image_processing</code> macros. For example, instead of:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">video</span><span class="p">.</span><span class="nf">preview</span><span class="p">(</span><span class="ss">resize: </span><span class="s2">"100x100"</span><span class="p">)</span> <span class="n">video</span><span class="p">.</span><span class="nf">preview</span><span class="p">(</span><span class="ss">resize: </span><span class="s2">"100x100&gt;"</span><span class="p">)</span> <span class="n">video</span><span class="p">.</span><span class="nf">preview</span><span class="p">(</span><span class="ss">resize: </span><span class="s2">"100x100^"</span><span class="p">)</span> </code></pre> <button class="clipboard-button" data-clipboard-text="video.preview(resize: &quot;100x100&quot;) video.preview(resize: &quot;100x100>&quot;) video.preview(resize: &quot;100x100^&quot;) ">Copy</button> </div> <p>you can respectively do:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">video</span><span class="p">.</span><span class="nf">preview</span><span class="p">(</span><span class="ss">resize_to_fit: </span><span class="p">[</span><span class="mi">100</span><span class="p">,</span> <span class="mi">100</span><span class="p">])</span> <span class="n">video</span><span class="p">.</span><span class="nf">preview</span><span class="p">(</span><span class="ss">resize_to_limit: </span><span class="p">[</span><span class="mi">100</span><span class="p">,</span> <span class="mi">100</span><span class="p">])</span> <span class="n">video</span><span class="p">.</span><span class="nf">preview</span><span class="p">(</span><span class="ss">resize_to_fill: </span><span class="p">[</span><span class="mi">100</span><span class="p">,</span> <span class="mi">100</span><span class="p">])</span> </code></pre> <button class="clipboard-button" data-clipboard-text="video.preview(resize_to_fit: [100, 100]) video.preview(resize_to_limit: [100, 100]) video.preview(resize_to_fill: [100, 100]) ">Copy</button> </div> <h3 id="new-activemodel-error-class"><a class="anchorlink" href="#new-activemodel-error-class" data-turbo="false"><span>6.7</span> New <code>ActiveModel::Error</code> class</a></h3><p>Errors are now instances of a new <code>ActiveModel::Error</code> class, with changes to the API. Some of these changes may throw errors depending on how you manipulate errors, while others will print deprecation warnings to be fixed for Rails 7.0.</p><p>More information about this change and details about the API changes can be found <a href="https://github.com/rails/rails/pull/32313">in this PR</a>.</p><h2 id="upgrading-from-rails-5-2-to-rails-6-0"><a class="anchorlink" href="#upgrading-from-rails-5-2-to-rails-6-0" data-turbo="false"><span>7</span> Upgrading from Rails 5.2 to Rails 6.0</a></h2><p>For more information on changes made to Rails 6.0 please see the <a href="6_0_release_notes.html">release notes</a>.</p><h3 id="using-webpacker"><a class="anchorlink" href="#using-webpacker" data-turbo="false"><span>7.1</span> Using Webpacker</a></h3><p><a href="https://github.com/rails/webpacker">Webpacker</a> is the default JavaScript compiler for Rails 6. But if you are upgrading the app, it is not activated by default. If you want to use Webpacker, then include it in your Gemfile and install it:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">gem</span> <span class="s2">"webpacker"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="gem &quot;webpacker&quot; ">Copy</button> </div> <div class="interstitial code"> <pre><code class="highlight console"><span class="gp">$</span><span class="w"> </span><span class="nb">bin/rails </span>webpacker:install </code></pre> <button class="clipboard-button" data-clipboard-text="bin/rails webpacker:install ">Copy</button> </div> <h3 id="force-ssl"><a class="anchorlink" href="#force-ssl" data-turbo="false"><span>7.2</span> Force SSL</a></h3><p>The <code>force_ssl</code> method on controllers has been deprecated and will be removed in Rails 6.1. You are encouraged to enable <a href="configuring.html#config-force-ssl"><code>config.force_ssl</code></a> to enforce HTTPS connections throughout your application. If you need to exempt certain endpoints from redirection, you can use <a href="configuring.html#config-ssl-options"><code>config.ssl_options</code></a> to configure that behavior.</p><h3 id="purpose-and-expiry-metadata-is-now-embedded-inside-signed-and-encrypted-cookies-for-increased-security"><a class="anchorlink" href="#purpose-and-expiry-metadata-is-now-embedded-inside-signed-and-encrypted-cookies-for-increased-security" data-turbo="false"><span>7.3</span> Purpose and expiry metadata is now embedded inside signed and encrypted cookies for increased security</a></h3><p>To improve security, Rails embeds the purpose and expiry metadata inside encrypted or signed cookies value.</p><p>Rails can then thwart attacks that attempt to copy the signed/encrypted value of a cookie and use it as the value of another cookie.</p><p>This new embed metadata make those cookies incompatible with versions of Rails older than 6.0.</p><p>If you require your cookies to be read by Rails 5.2 and older, or you are still validating your 6.0 deploy and want to be able to rollback set <code>Rails.application.config.action_dispatch.use_cookies_with_metadata</code> to <code>false</code>.</p><h3 id="all-npm-packages-have-been-moved-to-the-@rails-scope"><a class="anchorlink" href="#all-npm-packages-have-been-moved-to-the-@rails-scope" data-turbo="false"><span>7.4</span> All npm packages have been moved to the <code>@rails</code> scope</a></h3><p>If you were previously loading any of the <code>actioncable</code>, <code>activestorage</code>, or <code>rails-ujs</code> packages through npm/yarn, you must update the names of these dependencies before you can upgrade them to <code>6.0.0</code>:</p><div class="interstitial code"> <pre><code class="highlight plaintext">actioncable → @rails/actioncable activestorage → @rails/activestorage rails-ujs → @rails/ujs </code></pre> <button class="clipboard-button" data-clipboard-text="actioncable → @rails/actioncable activestorage → @rails/activestorage rails-ujs → @rails/ujs ">Copy</button> </div> <h3 id="action-cable-javascript-api-changes"><a class="anchorlink" href="#action-cable-javascript-api-changes" data-turbo="false"><span>7.5</span> Action Cable JavaScript API Changes</a></h3><p>The Action Cable JavaScript package has been converted from CoffeeScript to ES2015, and we now publish the source code in the npm distribution.</p><p>This release includes some breaking changes to optional parts of the Action Cable JavaScript API:</p> <ul> <li><p>Configuration of the WebSocket adapter and logger adapter have been moved from properties of <code>ActionCable</code> to properties of <code>ActionCable.adapters</code>. If you are configuring these adapters you will need to make these changes:</p><div class="interstitial code"> <pre><code class="highlight diff"><span class="gd">- ActionCable.WebSocket = MyWebSocket </span><span class="gi">+ ActionCable.adapters.WebSocket = MyWebSocket </span></code></pre> <button class="clipboard-button" data-clipboard-text="- ActionCable.WebSocket = MyWebSocket + ActionCable.adapters.WebSocket = MyWebSocket ">Copy</button> </div> <div class="interstitial code"> <pre><code class="highlight diff"><span class="gd">- ActionCable.logger = myLogger </span><span class="gi">+ ActionCable.adapters.logger = myLogger </span></code></pre> <button class="clipboard-button" data-clipboard-text="- ActionCable.logger = myLogger + ActionCable.adapters.logger = myLogger ">Copy</button> </div></li> <li><p>The <code>ActionCable.startDebugging()</code> and <code>ActionCable.stopDebugging()</code> methods have been removed and replaced with the property <code>ActionCable.logger.enabled</code>. If you are using these methods you will need to make these changes:</p><div class="interstitial code"> <pre><code class="highlight diff"><span class="gd">- ActionCable.startDebugging() </span><span class="gi">+ ActionCable.logger.enabled = true </span></code></pre> <button class="clipboard-button" data-clipboard-text="- ActionCable.startDebugging() + ActionCable.logger.enabled = true ">Copy</button> </div> <div class="interstitial code"> <pre><code class="highlight diff"><span class="gd">- ActionCable.stopDebugging() </span><span class="gi">+ ActionCable.logger.enabled = false </span></code></pre> <button class="clipboard-button" data-clipboard-text="- ActionCable.stopDebugging() + ActionCable.logger.enabled = false ">Copy</button> </div></li> </ul> <h3 id="actiondispatch-response-content-type-now-returns-the-content-type-header-without-modification"><a class="anchorlink" href="#actiondispatch-response-content-type-now-returns-the-content-type-header-without-modification" data-turbo="false"><span>7.6</span> <code>ActionDispatch::Response#content_type</code> now returns the Content-Type header without modification</a></h3><p>Previously, the return value of <code>ActionDispatch::Response#content_type</code> did NOT contain the charset part. This behavior has changed to include the previously omitted charset part as well.</p><p>If you want just the MIME type, please use <code>ActionDispatch::Response#media_type</code> instead.</p><p>Before:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">resp</span> <span class="o">=</span> <span class="no">ActionDispatch</span><span class="o">::</span><span class="no">Response</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="mi">200</span><span class="p">,</span> <span class="s2">"Content-Type"</span> <span class="o">=&gt;</span> <span class="s2">"text/csv; header=present; charset=utf-16"</span><span class="p">)</span> <span class="n">resp</span><span class="p">.</span><span class="nf">content_type</span> <span class="c1">#=&gt; "text/csv; header=present"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="resp = ActionDispatch::Response.new(200, &quot;Content-Type&quot; => &quot;text/csv; header=present; charset=utf-16&quot;) resp.content_type #=> &quot;text/csv; header=present&quot; ">Copy</button> </div> <p>After:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">resp</span> <span class="o">=</span> <span class="no">ActionDispatch</span><span class="o">::</span><span class="no">Response</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="mi">200</span><span class="p">,</span> <span class="s2">"Content-Type"</span> <span class="o">=&gt;</span> <span class="s2">"text/csv; header=present; charset=utf-16"</span><span class="p">)</span> <span class="n">resp</span><span class="p">.</span><span class="nf">content_type</span> <span class="c1">#=&gt; "text/csv; header=present; charset=utf-16"</span> <span class="n">resp</span><span class="p">.</span><span class="nf">media_type</span> <span class="c1">#=&gt; "text/csv"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="resp = ActionDispatch::Response.new(200, &quot;Content-Type&quot; => &quot;text/csv; header=present; charset=utf-16&quot;) resp.content_type #=> &quot;text/csv; header=present; charset=utf-16&quot; resp.media_type #=> &quot;text/csv&quot; ">Copy</button> </div> <h3 id="new-config-hosts-setting"><a class="anchorlink" href="#new-config-hosts-setting" data-turbo="false"><span>7.7</span> New <code>config.hosts</code> setting</a></h3><p>Rails now has a new <code>config.hosts</code> setting for security purposes. This setting defaults to <code>localhost</code> in development. If you use other domains in development you need to allow them like this:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># config/environments/development.rb</span> <span class="n">config</span><span class="p">.</span><span class="nf">hosts</span> <span class="o">&lt;&lt;</span> <span class="s2">"dev.myapp.com"</span> <span class="n">config</span><span class="p">.</span><span class="nf">hosts</span> <span class="o">&lt;&lt;</span> <span class="sr">/[a-z0-9-]+\.myapp\.com/</span> <span class="c1"># Optionally, regexp is allowed as well</span> </code></pre> <button class="clipboard-button" data-clipboard-text=" config.hosts << &quot;dev.myapp.com&quot; config.hosts << /[a-z0-9-]+\.myapp\.com/ # Optionally, regexp is allowed as well ">Copy</button> </div> <p>For other environments <code>config.hosts</code> is empty by default, which means Rails won't validate the host at all. You can optionally add them if you want to validate it in production.</p><h3 id="autoloading"><a class="anchorlink" href="#autoloading" data-turbo="false"><span>7.8</span> Autoloading</a></h3><p>The default configuration for Rails 6</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># config/application.rb</span> <span class="n">config</span><span class="p">.</span><span class="nf">load_defaults</span> <span class="mf">6.0</span> </code></pre> <button class="clipboard-button" data-clipboard-text=" config.load_defaults 6.0 ">Copy</button> </div> <p>enables <code>zeitwerk</code> autoloading mode on CRuby. In that mode, autoloading, reloading, and eager loading are managed by <a href="https://github.com/fxn/zeitwerk">Zeitwerk</a>.</p><p>If you are using defaults from a previous Rails version, you can enable zeitwerk like so:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># config/application.rb</span> <span class="n">config</span><span class="p">.</span><span class="nf">autoloader</span> <span class="o">=</span> <span class="ss">:zeitwerk</span> </code></pre> <button class="clipboard-button" data-clipboard-text=" config.autoloader = :zeitwerk ">Copy</button> </div> <h4 id="public-api"><a class="anchorlink" href="#public-api" data-turbo="false"><span>7.8.1</span> Public API</a></h4><p>In general, applications do not need to use the API of Zeitwerk directly. Rails sets things up according to the existing contract: <code>config.autoload_paths</code>, <code>config.cache_classes</code>, etc.</p><p>While applications should stick to that interface, the actual Zeitwerk loader object can be accessed as</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">Rails</span><span class="p">.</span><span class="nf">autoloaders</span><span class="p">.</span><span class="nf">main</span> </code></pre> <button class="clipboard-button" data-clipboard-text="Rails.autoloaders.main ">Copy</button> </div> <p>That may be handy if you need to preload Single Table Inheritance (STI) classes or configure a custom inflector, for example.</p><h4 id="project-structure"><a class="anchorlink" href="#project-structure" data-turbo="false"><span>7.8.2</span> Project Structure</a></h4><p>If the application being upgraded autoloads correctly, the project structure should be already mostly compatible.</p><p>However, <code>classic</code> mode infers file names from missing constant names (<code>underscore</code>), whereas <code>zeitwerk</code> mode infers constant names from file names (<code>camelize</code>). These helpers are not always inverse of each other, in particular if acronyms are involved. For instance, <code>"FOO".underscore</code> is <code>"foo"</code>, but <code>"foo".camelize</code> is <code>"Foo"</code>, not <code>"FOO"</code>.</p><p>Compatibility can be checked with the <code>zeitwerk:check</code> task:</p><div class="interstitial code"> <pre><code class="highlight console"><span class="gp">$</span><span class="w"> </span><span class="nb">bin/rails </span>zeitwerk:check <span class="go">Hold on, I am eager loading the application. All is good! </span></code></pre> <button class="clipboard-button" data-clipboard-text="bin/rails zeitwerk:check ">Copy</button> </div> <h4 id="require-dependency"><a class="anchorlink" href="#require-dependency" data-turbo="false"><span>7.8.3</span> require_dependency</a></h4><p>All known use cases of <code>require_dependency</code> have been eliminated, you should grep the project and delete them.</p><p>If your application uses Single Table Inheritance, please see the <a href="autoloading_and_reloading_constants.html#single-table-inheritance">Single Table Inheritance section</a> of the Autoloading and Reloading Constants (Zeitwerk Mode) guide.</p><h4 id="qualified-names-in-class-and-module-definitions"><a class="anchorlink" href="#qualified-names-in-class-and-module-definitions" data-turbo="false"><span>7.8.4</span> Qualified names in class and module definitions</a></h4><p>You can now robustly use constant paths in class and module definitions:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># Autoloading in this class' body matches Ruby semantics now.</span> <span class="k">class</span> <span class="nc">Admin::UsersController</span> <span class="o">&lt;</span> <span class="no">ApplicationController</span> <span class="c1"># ...</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="# Autoloading in this class' body matches Ruby semantics now. class Admin::UsersController < ApplicationController # ... end ">Copy</button> </div> <p>A gotcha to be aware of is that, depending on the order of execution, the classic autoloader could sometimes be able to autoload <code>Foo::Wadus</code> in</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">Foo::Bar</span> <span class="nc">Wadus</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class Foo::Bar Wadus end ">Copy</button> </div> <p>That does not match Ruby semantics because <code>Foo</code> is not in the nesting, and won't work at all in <code>zeitwerk</code> mode. If you find such corner case you can use the qualified name <code>Foo::Wadus</code>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">Foo::Bar</span> <span class="nc">Foo::Wadus</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class Foo::Bar Foo::Wadus end ">Copy</button> </div> <p>or add <code>Foo</code> to the nesting:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">module</span> <span class="nn">Foo</span> <span class="k">class</span> <span class="nc">Bar</span> <span class="no">Wadus</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="module Foo class Bar Wadus end end ">Copy</button> </div> <h4 id="concerns"><a class="anchorlink" href="#concerns" data-turbo="false"><span>7.8.5</span> Concerns</a></h4><p>You can autoload and eager load from a standard structure like</p><div class="interstitial code"> <pre><code class="highlight plaintext">app/models app/models/concerns </code></pre> <button class="clipboard-button" data-clipboard-text="app/models app/models/concerns ">Copy</button> </div> <p>In that case, <code>app/models/concerns</code> is assumed to be a root directory (because it belongs to the autoload paths), and it is ignored as namespace. So, <code>app/models/concerns/foo.rb</code> should define <code>Foo</code>, not <code>Concerns::Foo</code>.</p><p>The <code>Concerns::</code> namespace worked with the classic autoloader as a side-effect of the implementation, but it was not really an intended behavior. An application using <code>Concerns::</code> needs to rename those classes and modules to be able to run in <code>zeitwerk</code> mode.</p><h4 id="having-app-in-the-autoload-paths"><a class="anchorlink" href="#having-app-in-the-autoload-paths" data-turbo="false"><span>7.8.6</span> Having <code>app</code> in the autoload paths</a></h4><p>Some projects want something like <code>app/api/base.rb</code> to define <code>API::Base</code>, and add <code>app</code> to the autoload paths to accomplish that in <code>classic</code> mode. Since Rails adds all subdirectories of <code>app</code> to the autoload paths automatically, we have another situation in which there are nested root directories, so that setup no longer works. Similar principle we explained above with <code>concerns</code>.</p><p>If you want to keep that structure, you'll need to delete the subdirectory from the autoload paths in an initializer:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">ActiveSupport</span><span class="o">::</span><span class="no">Dependencies</span><span class="p">.</span><span class="nf">autoload_paths</span><span class="p">.</span><span class="nf">delete</span><span class="p">(</span><span class="s2">"</span><span class="si">#{</span><span class="no">Rails</span><span class="p">.</span><span class="nf">root</span><span class="si">}</span><span class="s2">/app/api"</span><span class="p">)</span> </code></pre> <button class="clipboard-button" data-clipboard-text="ActiveSupport::Dependencies.autoload_paths.delete(&quot;#{Rails.root}/app/api&quot;) ">Copy</button> </div> <h4 id="autoloaded-constants-and-explicit-namespaces"><a class="anchorlink" href="#autoloaded-constants-and-explicit-namespaces" data-turbo="false"><span>7.8.7</span> Autoloaded Constants and Explicit Namespaces</a></h4><p>If a namespace is defined in a file, as <code>Hotel</code> is here:</p><div class="interstitial code"> <pre><code class="highlight plaintext">app/models/hotel.rb # Defines Hotel. app/models/hotel/pricing.rb # Defines Hotel::Pricing. </code></pre> <button class="clipboard-button" data-clipboard-text="app/models/hotel.rb # Defines Hotel. app/models/hotel/pricing.rb # Defines Hotel::Pricing. ">Copy</button> </div> <p>the <code>Hotel</code> constant has to be set using the <code>class</code> or <code>module</code> keywords. For example:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">Hotel</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class Hotel end ">Copy</button> </div> <p>is good.</p><p>Alternatives like</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">Hotel</span> <span class="o">=</span> <span class="no">Class</span><span class="p">.</span><span class="nf">new</span> </code></pre> <button class="clipboard-button" data-clipboard-text="Hotel = Class.new ">Copy</button> </div> <p>or</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">Hotel</span> <span class="o">=</span> <span class="no">Struct</span><span class="p">.</span><span class="nf">new</span> </code></pre> <button class="clipboard-button" data-clipboard-text="Hotel = Struct.new ">Copy</button> </div> <p>won't work, child objects like <code>Hotel::Pricing</code> won't be found.</p><p>This restriction only applies to explicit namespaces. Classes and modules not defining a namespace can be defined using those idioms.</p><h4 id="one-file-one-constant-at-the-same-top-level"><a class="anchorlink" href="#one-file-one-constant-at-the-same-top-level" data-turbo="false"><span>7.8.8</span> One file, one constant (at the same top-level)</a></h4><p>In <code>classic</code> mode you could technically define several constants at the same top-level and have them all reloaded. For example, given</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># app/models/foo.rb</span> <span class="k">class</span> <span class="nc">Foo</span> <span class="k">end</span> <span class="k">class</span> <span class="nc">Bar</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text=" class Foo end class Bar end ">Copy</button> </div> <p>while <code>Bar</code> could not be autoloaded, autoloading <code>Foo</code> would mark <code>Bar</code> as autoloaded too. This is not the case in <code>zeitwerk</code> mode, you need to move <code>Bar</code> to its own file <code>bar.rb</code>. One file, one constant.</p><p>This only applies to constants at the same top-level as in the example above. Inner classes and modules are fine. For example, consider</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># app/models/foo.rb</span> <span class="k">class</span> <span class="nc">Foo</span> <span class="k">class</span> <span class="nc">InnerClass</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text=" class Foo class InnerClass end end ">Copy</button> </div> <p>If the application reloads <code>Foo</code>, it will reload <code>Foo::InnerClass</code> too.</p><h4 id="spring-and-the-test-environment"><a class="anchorlink" href="#spring-and-the-test-environment" data-turbo="false"><span>7.8.9</span> Spring and the <code>test</code> Environment</a></h4><p>Spring reloads the application code if something changes. In the <code>test</code> environment you need to enable reloading for that to work:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># config/environments/test.rb</span> <span class="n">config</span><span class="p">.</span><span class="nf">cache_classes</span> <span class="o">=</span> <span class="kp">false</span> </code></pre> <button class="clipboard-button" data-clipboard-text=" config.cache_classes = false ">Copy</button> </div> <p>Otherwise you'll get this error:</p><div class="interstitial code"> <pre><code class="highlight plaintext">reloading is disabled because config.cache_classes is true </code></pre> <button class="clipboard-button" data-clipboard-text="reloading is disabled because config.cache_classes is true ">Copy</button> </div> <h4 id="autoloading-bootsnap"><a class="anchorlink" href="#autoloading-bootsnap" data-turbo="false"><span>7.8.10</span> Bootsnap</a></h4><p>Bootsnap should be at least version 1.4.2.</p><p>In addition to that, Bootsnap needs to disable the iseq cache due to a bug in the interpreter if running Ruby 2.5. Please make sure to depend on at least Bootsnap 1.4.4 in that case.</p><h4 id="config-add-autoload-paths-to-load-path"><a class="anchorlink" href="#config-add-autoload-paths-to-load-path" data-turbo="false"><span>7.8.11</span> <code>config.add_autoload_paths_to_load_path</code></a></h4><p>The new configuration point <a href="configuring.html#config-add-autoload-paths-to-load-path"><code>config.add_autoload_paths_to_load_path</code></a> is <code>true</code> by default for backwards compatibility, but allows you to opt-out from adding the autoload paths to <code>$LOAD_PATH</code>.</p><p>This makes sense in most applications, since you never should require a file in <code>app/models</code>, for example, and Zeitwerk only uses absolute file names internally.</p><p>By opting-out you optimize <code>$LOAD_PATH</code> lookups (less directories to check), and save Bootsnap work and memory consumption, since it does not need to build an index for these directories.</p><h4 id="thread-safety"><a class="anchorlink" href="#thread-safety" data-turbo="false"><span>7.8.12</span> Thread-safety</a></h4><p>In classic mode, constant autoloading is not thread-safe, though Rails has locks in place for example to make web requests thread-safe when autoloading is enabled, as it is common in the development environment.</p><p>Constant autoloading is thread-safe in <code>zeitwerk</code> mode. For example, you can now autoload in multi-threaded scripts executed by the <code>runner</code> command.</p><h4 id="globs-in-config-autoload-paths"><a class="anchorlink" href="#globs-in-config-autoload-paths" data-turbo="false"><span>7.8.13</span> Globs in config.autoload_paths</a></h4><p>Beware of configurations like</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">config</span><span class="p">.</span><span class="nf">autoload_paths</span> <span class="o">+=</span> <span class="no">Dir</span><span class="p">[</span><span class="s2">"</span><span class="si">#{</span><span class="n">config</span><span class="p">.</span><span class="nf">root</span><span class="si">}</span><span class="s2">/lib/**/"</span><span class="p">]</span> </code></pre> <button class="clipboard-button" data-clipboard-text="config.autoload_paths += Dir[&quot;#{config.root}/lib/**/&quot;] ">Copy</button> </div> <p>Every element of <code>config.autoload_paths</code> should represent the top-level namespace (<code>Object</code>) and they cannot be nested in consequence (with the exception of <code>concerns</code> directories explained above).</p><p>To fix this, just remove the wildcards:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">config</span><span class="p">.</span><span class="nf">autoload_paths</span> <span class="o">&lt;&lt;</span> <span class="s2">"</span><span class="si">#{</span><span class="n">config</span><span class="p">.</span><span class="nf">root</span><span class="si">}</span><span class="s2">/lib"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="config.autoload_paths << &quot;#{config.root}/lib&quot; ">Copy</button> </div> <h4 id="eager-loading-and-autoloading-are-consistent"><a class="anchorlink" href="#eager-loading-and-autoloading-are-consistent" data-turbo="false"><span>7.8.14</span> Eager loading and autoloading are consistent</a></h4><p>In <code>classic</code> mode, if <code>app/models/foo.rb</code> defines <code>Bar</code>, you won't be able to autoload that file, but eager loading will work because it loads files recursively blindly. This can be a source of errors if you test things first eager loading, execution may fail later autoloading.</p><p>In <code>zeitwerk</code> mode both loading modes are consistent, they fail and err in the same files.</p><h4 id="how-to-use-the-classic-autoloader-in-rails-6"><a class="anchorlink" href="#how-to-use-the-classic-autoloader-in-rails-6" data-turbo="false"><span>7.8.15</span> How to Use the Classic Autoloader in Rails 6</a></h4><p>Applications can load Rails 6 defaults and still use the classic autoloader by setting <code>config.autoloader</code> this way:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># config/application.rb</span> <span class="n">config</span><span class="p">.</span><span class="nf">load_defaults</span> <span class="mf">6.0</span> <span class="n">config</span><span class="p">.</span><span class="nf">autoloader</span> <span class="o">=</span> <span class="ss">:classic</span> </code></pre> <button class="clipboard-button" data-clipboard-text=" config.load_defaults 6.0 config.autoloader = :classic ">Copy</button> </div> <p>When using the Classic Autoloader in Rails 6 application it is recommended to set concurrency level to 1 in development environment, for the web servers and background processors, due to the thread-safety concerns.</p><h3 id="active-storage-assignment-behavior-change"><a class="anchorlink" href="#active-storage-assignment-behavior-change" data-turbo="false"><span>7.9</span> Active Storage assignment behavior change</a></h3><p>With the configuration defaults for Rails 5.2, assigning to a collection of attachments declared with <code>has_many_attached</code> appends new files:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">User</span> <span class="o">&lt;</span> <span class="no">ApplicationRecord</span> <span class="n">has_many_attached</span> <span class="ss">:highlights</span> <span class="k">end</span> <span class="n">user</span><span class="p">.</span><span class="nf">highlights</span><span class="p">.</span><span class="nf">attach</span><span class="p">(</span><span class="ss">filename: </span><span class="s2">"funky.jpg"</span><span class="p">)</span> <span class="n">user</span><span class="p">.</span><span class="nf">highlights</span><span class="p">.</span><span class="nf">count</span> <span class="c1"># =&gt; 1</span> <span class="n">blob</span> <span class="o">=</span> <span class="no">ActiveStorage</span><span class="o">::</span><span class="no">Blob</span><span class="p">.</span><span class="nf">create_after_upload!</span><span class="p">(</span><span class="ss">filename: </span><span class="s2">"town.jpg"</span><span class="p">)</span> <span class="n">user</span><span class="p">.</span><span class="nf">update!</span><span class="p">(</span><span class="ss">highlights: </span><span class="p">[</span> <span class="n">blob</span> <span class="p">])</span> <span class="n">user</span><span class="p">.</span><span class="nf">highlights</span><span class="p">.</span><span class="nf">count</span> <span class="c1"># =&gt; 2</span> <span class="n">user</span><span class="p">.</span><span class="nf">highlights</span><span class="p">.</span><span class="nf">first</span><span class="p">.</span><span class="nf">filename</span> <span class="c1"># =&gt; "funky.jpg"</span> <span class="n">user</span><span class="p">.</span><span class="nf">highlights</span><span class="p">.</span><span class="nf">second</span><span class="p">.</span><span class="nf">filename</span> <span class="c1"># =&gt; "town.jpg"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class User < ApplicationRecord has_many_attached :highlights end user.highlights.attach(filename: &quot;funky.jpg&quot;) user.highlights.count # => 1 blob = ActiveStorage::Blob.create_after_upload!(filename: &quot;town.jpg&quot;) user.update!(highlights: [ blob ]) user.highlights.count # => 2 user.highlights.first.filename # => &quot;funky.jpg&quot; user.highlights.second.filename # => &quot;town.jpg&quot; ">Copy</button> </div> <p>With the configuration defaults for Rails 6.0, assigning to a collection of attachments replaces existing files instead of appending to them. This matches Active Record behavior when assigning to a collection association:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">user</span><span class="p">.</span><span class="nf">highlights</span><span class="p">.</span><span class="nf">attach</span><span class="p">(</span><span class="ss">filename: </span><span class="s2">"funky.jpg"</span><span class="p">)</span> <span class="n">user</span><span class="p">.</span><span class="nf">highlights</span><span class="p">.</span><span class="nf">count</span> <span class="c1"># =&gt; 1</span> <span class="n">blob</span> <span class="o">=</span> <span class="no">ActiveStorage</span><span class="o">::</span><span class="no">Blob</span><span class="p">.</span><span class="nf">create_after_upload!</span><span class="p">(</span><span class="ss">filename: </span><span class="s2">"town.jpg"</span><span class="p">)</span> <span class="n">user</span><span class="p">.</span><span class="nf">update!</span><span class="p">(</span><span class="ss">highlights: </span><span class="p">[</span> <span class="n">blob</span> <span class="p">])</span> <span class="n">user</span><span class="p">.</span><span class="nf">highlights</span><span class="p">.</span><span class="nf">count</span> <span class="c1"># =&gt; 1</span> <span class="n">user</span><span class="p">.</span><span class="nf">highlights</span><span class="p">.</span><span class="nf">first</span><span class="p">.</span><span class="nf">filename</span> <span class="c1"># =&gt; "town.jpg"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="user.highlights.attach(filename: &quot;funky.jpg&quot;) user.highlights.count # => 1 blob = ActiveStorage::Blob.create_after_upload!(filename: &quot;town.jpg&quot;) user.update!(highlights: [ blob ]) user.highlights.count # => 1 user.highlights.first.filename # => &quot;town.jpg&quot; ">Copy</button> </div> <p><code>#attach</code> can be used to add new attachments without removing the existing ones:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">blob</span> <span class="o">=</span> <span class="no">ActiveStorage</span><span class="o">::</span><span class="no">Blob</span><span class="p">.</span><span class="nf">create_after_upload!</span><span class="p">(</span><span class="ss">filename: </span><span class="s2">"town.jpg"</span><span class="p">)</span> <span class="n">user</span><span class="p">.</span><span class="nf">highlights</span><span class="p">.</span><span class="nf">attach</span><span class="p">(</span><span class="n">blob</span><span class="p">)</span> <span class="n">user</span><span class="p">.</span><span class="nf">highlights</span><span class="p">.</span><span class="nf">count</span> <span class="c1"># =&gt; 2</span> <span class="n">user</span><span class="p">.</span><span class="nf">highlights</span><span class="p">.</span><span class="nf">first</span><span class="p">.</span><span class="nf">filename</span> <span class="c1"># =&gt; "funky.jpg"</span> <span class="n">user</span><span class="p">.</span><span class="nf">highlights</span><span class="p">.</span><span class="nf">second</span><span class="p">.</span><span class="nf">filename</span> <span class="c1"># =&gt; "town.jpg"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="blob = ActiveStorage::Blob.create_after_upload!(filename: &quot;town.jpg&quot;) user.highlights.attach(blob) user.highlights.count # => 2 user.highlights.first.filename # => &quot;funky.jpg&quot; user.highlights.second.filename # => &quot;town.jpg&quot; ">Copy</button> </div> <p>Existing applications can opt in to this new behavior by setting <a href="configuring.html#config-active-storage-replace-on-assign-to-many"><code>config.active_storage.replace_on_assign_to_many</code></a> to <code>true</code>. The old behavior will be deprecated in Rails 7.0 and removed in Rails 7.1.</p><h3 id="custom-exception-handling-applications"><a class="anchorlink" href="#custom-exception-handling-applications" data-turbo="false"><span>7.10</span> Custom exception handling applications</a></h3><p>Invalid <code>Accept</code> or <code>Content-Type</code> request headers will now raise an exception. The default <a href="configuring.html#config-exceptions-app"><code>config.exceptions_app</code></a> specifically handles that error and compensates for it. Custom exceptions applications will need to handle that error as well, or such requests will cause Rails to use the fallback exceptions application, which returns a <code>500 Internal Server Error</code>.</p><h2 id="upgrading-from-rails-5-1-to-rails-5-2"><a class="anchorlink" href="#upgrading-from-rails-5-1-to-rails-5-2" data-turbo="false"><span>8</span> Upgrading from Rails 5.1 to Rails 5.2</a></h2><p>For more information on changes made to Rails 5.2 please see the <a href="5_2_release_notes.html">release notes</a>.</p><h3 id="upgrading-from-rails-5-1-to-rails-5-2-bootsnap"><a class="anchorlink" href="#upgrading-from-rails-5-1-to-rails-5-2-bootsnap" data-turbo="false"><span>8.1</span> Bootsnap</a></h3><p>Rails 5.2 adds bootsnap gem in the <a href="https://github.com/rails/rails/pull/29313">newly generated app's Gemfile</a>. The <code>app:update</code> command sets it up in <code>boot.rb</code>. If you want to use it, then add it in the Gemfile:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># Reduces boot times through caching; required in config/boot.rb</span> <span class="n">gem</span> <span class="s2">"bootsnap"</span><span class="p">,</span> <span class="ss">require: </span><span class="kp">false</span> </code></pre> <button class="clipboard-button" data-clipboard-text="# Reduces boot times through caching; required in config/boot.rb gem &quot;bootsnap&quot;, require: false ">Copy</button> </div> <p>Otherwise change the <code>boot.rb</code> to not use bootsnap.</p><h3 id="expiry-in-signed-or-encrypted-cookie-is-now-embedded-in-the-cookies-values"><a class="anchorlink" href="#expiry-in-signed-or-encrypted-cookie-is-now-embedded-in-the-cookies-values" data-turbo="false"><span>8.2</span> Expiry in signed or encrypted cookie is now embedded in the cookies values</a></h3><p>To improve security, Rails now embeds the expiry information also in encrypted or signed cookies value.</p><p>This new embedded information makes those cookies incompatible with versions of Rails older than 5.2.</p><p>If you require your cookies to be read by 5.1 and older, or you are still validating your 5.2 deploy and want to allow you to rollback set <code>Rails.application.config.action_dispatch.use_authenticated_cookie_encryption</code> to <code>false</code>.</p><h2 id="upgrading-from-rails-5-0-to-rails-5-1"><a class="anchorlink" href="#upgrading-from-rails-5-0-to-rails-5-1" data-turbo="false"><span>9</span> Upgrading from Rails 5.0 to Rails 5.1</a></h2><p>For more information on changes made to Rails 5.1 please see the <a href="5_1_release_notes.html">release notes</a>.</p><h3 id="top-level-hashwithindifferentaccess-is-soft-deprecated"><a class="anchorlink" href="#top-level-hashwithindifferentaccess-is-soft-deprecated" data-turbo="false"><span>9.1</span> Top-level <code>HashWithIndifferentAccess</code> is soft-deprecated</a></h3><p>If your application uses the top-level <code>HashWithIndifferentAccess</code> class, you should slowly move your code to instead use <code>ActiveSupport::HashWithIndifferentAccess</code>.</p><p>It is only soft-deprecated, which means that your code will not break at the moment and no deprecation warning will be displayed, but this constant will be removed in the future.</p><p>Also, if you have pretty old YAML documents containing dumps of such objects, you may need to load and dump them again to make sure that they reference the right constant, and that loading them won't break in the future.</p><h3 id="application-secrets-now-loaded-with-all-keys-as-symbols"><a class="anchorlink" href="#application-secrets-now-loaded-with-all-keys-as-symbols" data-turbo="false"><span>9.2</span> <code>application.secrets</code> now loaded with all keys as symbols</a></h3><p>If your application stores nested configuration in <code>config/secrets.yml</code>, all keys are now loaded as symbols, so access using strings should be changed.</p><p>From:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">Rails</span><span class="p">.</span><span class="nf">application</span><span class="p">.</span><span class="nf">secrets</span><span class="p">[</span><span class="ss">:smtp_settings</span><span class="p">][</span><span class="s2">"address"</span><span class="p">]</span> </code></pre> <button class="clipboard-button" data-clipboard-text="Rails.application.secrets[:smtp_settings][&quot;address&quot;] ">Copy</button> </div> <p>To:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">Rails</span><span class="p">.</span><span class="nf">application</span><span class="p">.</span><span class="nf">secrets</span><span class="p">[</span><span class="ss">:smtp_settings</span><span class="p">][</span><span class="ss">:address</span><span class="p">]</span> </code></pre> <button class="clipboard-button" data-clipboard-text="Rails.application.secrets[:smtp_settings][:address] ">Copy</button> </div> <h3 id="removed-deprecated-support-to-text-and-nothing-in-render"><a class="anchorlink" href="#removed-deprecated-support-to-text-and-nothing-in-render" data-turbo="false"><span>9.3</span> Removed deprecated support to <code>:text</code> and <code>:nothing</code> in <code>render</code></a></h3><p>If your controllers are using <code>render :text</code>, they will no longer work. The new method of rendering text with MIME type of <code>text/plain</code> is to use <code>render :plain</code>.</p><p>Similarly, <code>render :nothing</code> is also removed and you should use the <code>head</code> method to send responses that contain only headers. For example, <code>head :ok</code> sends a 200 response with no body to render.</p><h3 id="removed-deprecated-support-of-redirect-to-back"><a class="anchorlink" href="#removed-deprecated-support-of-redirect-to-back" data-turbo="false"><span>9.4</span> Removed deprecated support of <code>redirect_to :back</code></a></h3><p>In Rails 5.0, <code>redirect_to :back</code> was deprecated. In Rails 5.1, it was removed completely.</p><p>As an alternative, use <code>redirect_back</code>. It's important to note that <code>redirect_back</code> also takes a <code>fallback_location</code> option which will be used in case the <code>HTTP_REFERER</code> is missing.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">redirect_back</span><span class="p">(</span><span class="ss">fallback_location: </span><span class="n">root_path</span><span class="p">)</span> </code></pre> <button class="clipboard-button" data-clipboard-text="redirect_back(fallback_location: root_path) ">Copy</button> </div> <h2 id="upgrading-from-rails-4-2-to-rails-5-0"><a class="anchorlink" href="#upgrading-from-rails-4-2-to-rails-5-0" data-turbo="false"><span>10</span> Upgrading from Rails 4.2 to Rails 5.0</a></h2><p>For more information on changes made to Rails 5.0 please see the <a href="5_0_release_notes.html">release notes</a>.</p><h3 id="ruby-2-2-2-required"><a class="anchorlink" href="#ruby-2-2-2-required" data-turbo="false"><span>10.1</span> Ruby 2.2.2+ required</a></h3><p>From Ruby on Rails 5.0 onwards, Ruby 2.2.2+ is the only supported Ruby version. Make sure you are on Ruby 2.2.2 version or greater, before you proceed.</p><h3 id="active-record-models-now-inherit-from-applicationrecord-by-default"><a class="anchorlink" href="#active-record-models-now-inherit-from-applicationrecord-by-default" data-turbo="false"><span>10.2</span> Active Record Models Now Inherit from ApplicationRecord by Default</a></h3><p>In Rails 4.2, an Active Record model inherits from <code>ActiveRecord::Base</code>. In Rails 5.0, all models inherit from <code>ApplicationRecord</code>.</p><p><code>ApplicationRecord</code> is a new superclass for all app models, analogous to app controllers subclassing <code>ApplicationController</code> instead of <code>ActionController::Base</code>. This gives apps a single spot to configure app-wide model behavior.</p><p>When upgrading from Rails 4.2 to Rails 5.0, you need to create an <code>application_record.rb</code> file in <code>app/models/</code> and add the following content:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">ApplicationRecord</span> <span class="o">&lt;</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Base</span> <span class="nb">self</span><span class="p">.</span><span class="nf">abstract_class</span> <span class="o">=</span> <span class="kp">true</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class ApplicationRecord < ActiveRecord::Base self.abstract_class = true end ">Copy</button> </div> <p>Then make sure that all your models inherit from it.</p><h3 id="halting-callback-chains-via-throw-abort"><a class="anchorlink" href="#halting-callback-chains-via-throw-abort" data-turbo="false"><span>10.3</span> Halting Callback Chains via <code>throw(:abort)</code></a></h3><p>In Rails 4.2, when a 'before' callback returns <code>false</code> in Active Record and Active Model, then the entire callback chain is halted. In other words, successive 'before' callbacks are not executed, and neither is the action wrapped in callbacks.</p><p>In Rails 5.0, returning <code>false</code> in an Active Record or Active Model callback will not have this side effect of halting the callback chain. Instead, callback chains must be explicitly halted by calling <code>throw(:abort)</code>.</p><p>When you upgrade from Rails 4.2 to Rails 5.0, returning <code>false</code> in those kind of callbacks will still halt the callback chain, but you will receive a deprecation warning about this upcoming change.</p><p>When you are ready, you can opt into the new behavior and remove the deprecation warning by adding the following configuration to your <code>config/application.rb</code>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">ActiveSupport</span><span class="p">.</span><span class="nf">halt_callback_chains_on_return_false</span> <span class="o">=</span> <span class="kp">false</span> </code></pre> <button class="clipboard-button" data-clipboard-text="ActiveSupport.halt_callback_chains_on_return_false = false ">Copy</button> </div> <p>Note that this option will not affect Active Support callbacks since they never halted the chain when any value was returned.</p><p>See <a href="https://github.com/rails/rails/pull/17227">#17227</a> for more details.</p><h3 id="activejob-now-inherits-from-applicationjob-by-default"><a class="anchorlink" href="#activejob-now-inherits-from-applicationjob-by-default" data-turbo="false"><span>10.4</span> ActiveJob Now Inherits from ApplicationJob by Default</a></h3><p>In Rails 4.2, an Active Job inherits from <code>ActiveJob::Base</code>. In Rails 5.0, this behavior has changed to now inherit from <code>ApplicationJob</code>.</p><p>When upgrading from Rails 4.2 to Rails 5.0, you need to create an <code>application_job.rb</code> file in <code>app/jobs/</code> and add the following content:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">ApplicationJob</span> <span class="o">&lt;</span> <span class="no">ActiveJob</span><span class="o">::</span><span class="no">Base</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class ApplicationJob < ActiveJob::Base end ">Copy</button> </div> <p>Then make sure that all your job classes inherit from it.</p><p>See <a href="https://github.com/rails/rails/pull/19034">#19034</a> for more details.</p><h3 id="rails-controller-testing"><a class="anchorlink" href="#rails-controller-testing" data-turbo="false"><span>10.5</span> Rails Controller Testing</a></h3><h4 id="extraction-of-some-helper-methods-to-rails-controller-testing"><a class="anchorlink" href="#extraction-of-some-helper-methods-to-rails-controller-testing" data-turbo="false"><span>10.5.1</span> Extraction of some helper methods to <code>rails-controller-testing</code></a></h4><p><code>assigns</code> and <code>assert_template</code> have been extracted to the <code>rails-controller-testing</code> gem. To continue using these methods in your controller tests, add <code>gem "rails-controller-testing"</code> to your <code>Gemfile</code>.</p><p>If you are using RSpec for testing, please see the extra configuration required in the gem's documentation.</p><h4 id="new-behavior-when-uploading-files"><a class="anchorlink" href="#new-behavior-when-uploading-files" data-turbo="false"><span>10.5.2</span> New behavior when uploading files</a></h4><p>If you are using <code>ActionDispatch::Http::UploadedFile</code> in your tests to upload files, you will need to change to use the similar <code>Rack::Test::UploadedFile</code> class instead.</p><p>See <a href="https://github.com/rails/rails/issues/26404">#26404</a> for more details.</p><h3 id="autoloading-is-disabled-after-booting-in-the-production-environment"><a class="anchorlink" href="#autoloading-is-disabled-after-booting-in-the-production-environment" data-turbo="false"><span>10.6</span> Autoloading is Disabled After Booting in the Production Environment</a></h3><p>Autoloading is now disabled after booting in the production environment by default.</p><p>Eager loading the application is part of the boot process, so top-level constants are fine and are still autoloaded, no need to require their files.</p><p>Constants in deeper places only executed at runtime, like regular method bodies, are also fine because the file defining them will have been eager loaded while booting.</p><p>For the vast majority of applications this change needs no action. But in the very rare event that your application needs autoloading while running in production, set <code>Rails.application.config.enable_dependency_loading</code> to true.</p><h3 id="xml-serialization"><a class="anchorlink" href="#xml-serialization" data-turbo="false"><span>10.7</span> XML Serialization</a></h3><p><code>ActiveModel::Serializers::Xml</code> has been extracted from Rails to the <code>activemodel-serializers-xml</code> gem. To continue using XML serialization in your application, add <code>gem "activemodel-serializers-xml"</code> to your <code>Gemfile</code>.</p><h3 id="removed-support-for-legacy-mysql-database-adapter"><a class="anchorlink" href="#removed-support-for-legacy-mysql-database-adapter" data-turbo="false"><span>10.8</span> Removed Support for Legacy <code>mysql</code> Database Adapter</a></h3><p>Rails 5 removes support for the legacy <code>mysql</code> database adapter. Most users should be able to use <code>mysql2</code> instead. It will be converted to a separate gem when we find someone to maintain it.</p><h3 id="removed-support-for-debugger"><a class="anchorlink" href="#removed-support-for-debugger" data-turbo="false"><span>10.9</span> Removed Support for Debugger</a></h3><p><code>debugger</code> is not supported by Ruby 2.2 which is required by Rails 5. Use <code>byebug</code> instead.</p><h3 id="use-bin-rails-for-running-tasks-and-tests"><a class="anchorlink" href="#use-bin-rails-for-running-tasks-and-tests" data-turbo="false"><span>10.10</span> Use <code>bin/rails</code> for running tasks and tests</a></h3><p>Rails 5 adds the ability to run tasks and tests through <code>bin/rails</code> instead of rake. Generally these changes are in parallel with rake, but some were ported over altogether.</p><p>To use the new test runner simply type <code>bin/rails test</code>.</p><p><code>rake dev:cache</code> is now <code>bin/rails dev:cache</code>.</p><p>Run <code>bin/rails</code> inside your application's root directory to see the list of commands available.</p><h3 id="actioncontroller-parameters-no-longer-inherits-from-hashwithindifferentaccess"><a class="anchorlink" href="#actioncontroller-parameters-no-longer-inherits-from-hashwithindifferentaccess" data-turbo="false"><span>10.11</span> <code>ActionController::Parameters</code> No Longer Inherits from <code>HashWithIndifferentAccess</code></a></h3><p>Calling <code>params</code> in your application will now return an object instead of a hash. If your parameters are already permitted, then you will not need to make any changes. If you are using <code>map</code> and other methods that depend on being able to read the hash regardless of <code>permitted?</code> you will need to upgrade your application to first permit and then convert to a hash.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">params</span><span class="p">.</span><span class="nf">permit</span><span class="p">([</span><span class="ss">:proceed_to</span><span class="p">,</span> <span class="ss">:return_to</span><span class="p">]).</span><span class="nf">to_h</span> </code></pre> <button class="clipboard-button" data-clipboard-text="params.permit([:proceed_to, :return_to]).to_h ">Copy</button> </div> <h3 id="protect-from-forgery-now-defaults-to-prepend-false"><a class="anchorlink" href="#protect-from-forgery-now-defaults-to-prepend-false" data-turbo="false"><span>10.12</span> <code>protect_from_forgery</code> Now Defaults to <code>prepend: false</code></a></h3><p><code>protect_from_forgery</code> defaults to <code>prepend: false</code> which means that it will be inserted into the callback chain at the point in which you call it in your application. If you want <code>protect_from_forgery</code> to always run first, then you should change your application to use <code>protect_from_forgery prepend: true</code>.</p><h3 id="default-template-handler-is-now-raw"><a class="anchorlink" href="#default-template-handler-is-now-raw" data-turbo="false"><span>10.13</span> Default Template Handler is Now RAW</a></h3><p>Files without a template handler in their extension will be rendered using the raw handler. Previously Rails would render files using the ERB template handler.</p><p>If you do not want your file to be handled via the raw handler, you should add an extension to your file that can be parsed by the appropriate template handler.</p><h3 id="added-wildcard-matching-for-template-dependencies"><a class="anchorlink" href="#added-wildcard-matching-for-template-dependencies" data-turbo="false"><span>10.14</span> Added Wildcard Matching for Template Dependencies</a></h3><p>You can now use wildcard matching for your template dependencies. For example, if you were defining your templates as such:</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="cp">&lt;%</span> <span class="c1"># Template Dependency: recordings/threads/events/subscribers_changed </span><span class="cp">%&gt;</span> <span class="cp">&lt;%</span> <span class="c1"># Template Dependency: recordings/threads/events/completed </span><span class="cp">%&gt;</span> <span class="cp">&lt;%</span> <span class="c1"># Template Dependency: recordings/threads/events/uncompleted </span><span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<% # Template Dependency: recordings/threads/events/subscribers_changed %> <% # Template Dependency: recordings/threads/events/completed %> <% # Template Dependency: recordings/threads/events/uncompleted %> ">Copy</button> </div> <p>You can now just call the dependency once with a wildcard.</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="cp">&lt;%</span> <span class="c1"># Template Dependency: recordings/threads/events/* </span><span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<% # Template Dependency: recordings/threads/events/* %> ">Copy</button> </div> <h3 id="actionview-helpers-recordtaghelper-moved-to-external-gem-record-tag-helper"><a class="anchorlink" href="#actionview-helpers-recordtaghelper-moved-to-external-gem-record-tag-helper" data-turbo="false"><span>10.15</span> <code>ActionView::Helpers::RecordTagHelper</code> moved to external gem (record_tag_helper)</a></h3><p><code>content_tag_for</code> and <code>div_for</code> have been removed in favor of just using <code>content_tag</code>. To continue using the older methods, add the <code>record_tag_helper</code> gem to your <code>Gemfile</code>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">gem</span> <span class="s2">"record_tag_helper"</span><span class="p">,</span> <span class="s2">"~&gt; 1.0"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="gem &quot;record_tag_helper&quot;, &quot;~> 1.0&quot; ">Copy</button> </div> <p>See <a href="https://github.com/rails/rails/pull/18411">#18411</a> for more details.</p><h3 id="removed-support-for-protected-attributes-gem"><a class="anchorlink" href="#removed-support-for-protected-attributes-gem" data-turbo="false"><span>10.16</span> Removed Support for <code>protected_attributes</code> Gem</a></h3><p>The <code>protected_attributes</code> gem is no longer supported in Rails 5.</p><h3 id="removed-support-for-activerecord-deprecated-finders-gem"><a class="anchorlink" href="#removed-support-for-activerecord-deprecated-finders-gem" data-turbo="false"><span>10.17</span> Removed support for <code>activerecord-deprecated_finders</code> gem</a></h3><p>The <code>activerecord-deprecated_finders</code> gem is no longer supported in Rails 5.</p><h3 id="activesupport-testcase-default-test-order-is-now-random"><a class="anchorlink" href="#activesupport-testcase-default-test-order-is-now-random" data-turbo="false"><span>10.18</span> <code>ActiveSupport::TestCase</code> Default Test Order is Now Random</a></h3><p>When tests are run in your application, the default order is now <code>:random</code> instead of <code>:sorted</code>. Use the following config option to set it back to <code>:sorted</code>.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># config/environments/test.rb</span> <span class="no">Rails</span><span class="p">.</span><span class="nf">application</span><span class="p">.</span><span class="nf">configure</span> <span class="k">do</span> <span class="n">config</span><span class="p">.</span><span class="nf">active_support</span><span class="p">.</span><span class="nf">test_order</span> <span class="o">=</span> <span class="ss">:sorted</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="Rails.application.configure do config.active_support.test_order = :sorted end ">Copy</button> </div> <h3 id="actioncontroller-live-became-a-concern"><a class="anchorlink" href="#actioncontroller-live-became-a-concern" data-turbo="false"><span>10.19</span> <code>ActionController::Live</code> became a <code>Concern</code></a></h3><p>If you include <code>ActionController::Live</code> in another module that is included in your controller, then you should also extend the module with <code>ActiveSupport::Concern</code>. Alternatively, you can use the <code>self.included</code> hook to include <code>ActionController::Live</code> directly to the controller once the <code>StreamingSupport</code> is included.</p><p>This means that if your application used to have its own streaming module, the following code would break in production:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># This is a work-around for streamed controllers performing authentication with Warden/Devise.</span> <span class="c1"># See https://github.com/plataformatec/devise/issues/2332</span> <span class="c1"># Authenticating in the router is another solution as suggested in that issue</span> <span class="k">class</span> <span class="nc">StreamingSupport</span> <span class="kp">include</span> <span class="no">ActionController</span><span class="o">::</span><span class="no">Live</span> <span class="c1"># this won't work in production for Rails 5</span> <span class="c1"># extend ActiveSupport::Concern # unless you uncomment this line.</span> <span class="k">def</span> <span class="nf">process</span><span class="p">(</span><span class="nb">name</span><span class="p">)</span> <span class="k">super</span><span class="p">(</span><span class="nb">name</span><span class="p">)</span> <span class="k">rescue</span> <span class="no">ArgumentError</span> <span class="o">=&gt;</span> <span class="n">e</span> <span class="k">if</span> <span class="n">e</span><span class="p">.</span><span class="nf">message</span> <span class="o">==</span> <span class="s2">"uncaught throw :warden"</span> <span class="kp">throw</span> <span class="ss">:warden</span> <span class="k">else</span> <span class="k">raise</span> <span class="n">e</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="# This is a work-around for streamed controllers performing authentication with Warden/Devise. # See https://github.com/plataformatec/devise/issues/2332 # Authenticating in the router is another solution as suggested in that issue class StreamingSupport include ActionController::Live # this won't work in production for Rails 5 # extend ActiveSupport::Concern # unless you uncomment this line. def process(name) super(name) rescue ArgumentError => e if e.message == &quot;uncaught throw :warden&quot; throw :warden else raise e end end end ">Copy</button> </div> <h3 id="new-framework-defaults"><a class="anchorlink" href="#new-framework-defaults" data-turbo="false"><span>10.20</span> New Framework Defaults</a></h3><h4 id="active-record-belongs-to-required-by-default-option"><a class="anchorlink" href="#active-record-belongs-to-required-by-default-option" data-turbo="false"><span>10.20.1</span> Active Record <code>belongs_to</code> Required by Default Option</a></h4><p><code>belongs_to</code> will now trigger a validation error by default if the association is not present.</p><p>This can be turned off per-association with <code>optional: true</code>.</p><p>This default will be automatically configured in new applications. If an existing application wants to add this feature it will need to be turned on in an initializer:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">config</span><span class="p">.</span><span class="nf">active_record</span><span class="p">.</span><span class="nf">belongs_to_required_by_default</span> <span class="o">=</span> <span class="kp">true</span> </code></pre> <button class="clipboard-button" data-clipboard-text="config.active_record.belongs_to_required_by_default = true ">Copy</button> </div> <p>The configuration is by default global for all your models, but you can override it on a per model basis. This should help you migrate all your models to have their associations required by default.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">Book</span> <span class="o">&lt;</span> <span class="no">ApplicationRecord</span> <span class="c1"># model is not yet ready to have its association required by default</span> <span class="nb">self</span><span class="p">.</span><span class="nf">belongs_to_required_by_default</span> <span class="o">=</span> <span class="kp">false</span> <span class="n">belongs_to</span><span class="p">(</span><span class="ss">:author</span><span class="p">)</span> <span class="k">end</span> <span class="k">class</span> <span class="nc">Car</span> <span class="o">&lt;</span> <span class="no">ApplicationRecord</span> <span class="c1"># model is ready to have its association required by default</span> <span class="nb">self</span><span class="p">.</span><span class="nf">belongs_to_required_by_default</span> <span class="o">=</span> <span class="kp">true</span> <span class="n">belongs_to</span><span class="p">(</span><span class="ss">:pilot</span><span class="p">)</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class Book < ApplicationRecord # model is not yet ready to have its association required by default self.belongs_to_required_by_default = false belongs_to(:author) end class Car < ApplicationRecord # model is ready to have its association required by default self.belongs_to_required_by_default = true belongs_to(:pilot) end ">Copy</button> </div> <h4 id="per-form-csrf-tokens"><a class="anchorlink" href="#per-form-csrf-tokens" data-turbo="false"><span>10.20.2</span> Per-form CSRF Tokens</a></h4><p>Rails 5 now supports per-form CSRF tokens to mitigate against code-injection attacks with forms created by JavaScript. With this option turned on, forms in your application will each have their own CSRF token that is specific to the action and method for that form.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">config</span><span class="p">.</span><span class="nf">action_controller</span><span class="p">.</span><span class="nf">per_form_csrf_tokens</span> <span class="o">=</span> <span class="kp">true</span> </code></pre> <button class="clipboard-button" data-clipboard-text="config.action_controller.per_form_csrf_tokens = true ">Copy</button> </div> <h4 id="forgery-protection-with-origin-check"><a class="anchorlink" href="#forgery-protection-with-origin-check" data-turbo="false"><span>10.20.3</span> Forgery Protection with Origin Check</a></h4><p>You can now configure your application to check if the HTTP <code>Origin</code> header should be checked against the site's origin as an additional CSRF defense. Set the following in your config to true:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">config</span><span class="p">.</span><span class="nf">action_controller</span><span class="p">.</span><span class="nf">forgery_protection_origin_check</span> <span class="o">=</span> <span class="kp">true</span> </code></pre> <button class="clipboard-button" data-clipboard-text="config.action_controller.forgery_protection_origin_check = true ">Copy</button> </div> <h4 id="allow-configuration-of-action-mailer-queue-name"><a class="anchorlink" href="#allow-configuration-of-action-mailer-queue-name" data-turbo="false"><span>10.20.4</span> Allow Configuration of Action Mailer Queue Name</a></h4><p>The default mailer queue name is <code>mailers</code>. This configuration option allows you to globally change the queue name. Set the following in your config:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">config</span><span class="p">.</span><span class="nf">action_mailer</span><span class="p">.</span><span class="nf">deliver_later_queue_name</span> <span class="o">=</span> <span class="ss">:new_queue_name</span> </code></pre> <button class="clipboard-button" data-clipboard-text="config.action_mailer.deliver_later_queue_name = :new_queue_name ">Copy</button> </div> <h4 id="support-fragment-caching-in-action-mailer-views"><a class="anchorlink" href="#support-fragment-caching-in-action-mailer-views" data-turbo="false"><span>10.20.5</span> Support Fragment Caching in Action Mailer Views</a></h4><p>Set <a href="configuring.html#config-action-mailer-perform-caching"><code>config.action_mailer.perform_caching</code></a> in your config to determine whether your Action Mailer views should support caching.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">config</span><span class="p">.</span><span class="nf">action_mailer</span><span class="p">.</span><span class="nf">perform_caching</span> <span class="o">=</span> <span class="kp">true</span> </code></pre> <button class="clipboard-button" data-clipboard-text="config.action_mailer.perform_caching = true ">Copy</button> </div> <h4 id="configure-the-output-of-db-structure-dump"><a class="anchorlink" href="#configure-the-output-of-db-structure-dump" data-turbo="false"><span>10.20.6</span> Configure the Output of <code>db:structure:dump</code></a></h4><p>If you're using <code>schema_search_path</code> or other PostgreSQL extensions, you can control how the schema is dumped. Set to <code>:all</code> to generate all dumps, or to <code>:schema_search_path</code> to generate from schema search path.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">config</span><span class="p">.</span><span class="nf">active_record</span><span class="p">.</span><span class="nf">dump_schemas</span> <span class="o">=</span> <span class="ss">:all</span> </code></pre> <button class="clipboard-button" data-clipboard-text="config.active_record.dump_schemas = :all ">Copy</button> </div> <h4 id="configure-ssl-options-to-enable-hsts-with-subdomains"><a class="anchorlink" href="#configure-ssl-options-to-enable-hsts-with-subdomains" data-turbo="false"><span>10.20.7</span> Configure SSL Options to Enable HSTS with Subdomains</a></h4><p>Set the following in your config to enable HSTS when using subdomains:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">config</span><span class="p">.</span><span class="nf">ssl_options</span> <span class="o">=</span> <span class="p">{</span> <span class="ss">hsts: </span><span class="p">{</span> <span class="ss">subdomains: </span><span class="kp">true</span> <span class="p">}</span> <span class="p">}</span> </code></pre> <button class="clipboard-button" data-clipboard-text="config.ssl_options = { hsts: { subdomains: true } } ">Copy</button> </div> <h4 id="preserve-timezone-of-the-receiver"><a class="anchorlink" href="#preserve-timezone-of-the-receiver" data-turbo="false"><span>10.20.8</span> Preserve Timezone of the Receiver</a></h4><p>When using Ruby 2.4, you can preserve the timezone of the receiver when calling <code>to_time</code>.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">ActiveSupport</span><span class="p">.</span><span class="nf">to_time_preserves_timezone</span> <span class="o">=</span> <span class="kp">false</span> </code></pre> <button class="clipboard-button" data-clipboard-text="ActiveSupport.to_time_preserves_timezone = false ">Copy</button> </div> <h3 id="changes-with-json-jsonb-serialization"><a class="anchorlink" href="#changes-with-json-jsonb-serialization" data-turbo="false"><span>10.21</span> Changes with JSON/JSONB serialization</a></h3><p>In Rails 5.0, how JSON/JSONB attributes are serialized and deserialized changed. Now, if you set a column equal to a <code>String</code>, Active Record will no longer turn that string into a <code>Hash</code>, and will instead only return the string. This is not limited to code interacting with models, but also affects <code>:default</code> column settings in <code>db/schema.rb</code>. It is recommended that you do not set columns equal to a <code>String</code>, but pass a <code>Hash</code> instead, which will be converted to and from a JSON string automatically.</p><h2 id="upgrading-from-rails-4-1-to-rails-4-2"><a class="anchorlink" href="#upgrading-from-rails-4-1-to-rails-4-2" data-turbo="false"><span>11</span> Upgrading from Rails 4.1 to Rails 4.2</a></h2><h3 id="web-console"><a class="anchorlink" href="#web-console" data-turbo="false"><span>11.1</span> Web Console</a></h3><p>First, add <code>gem "web-console", "~&gt; 2.0"</code> to the <code>:development</code> group in your <code>Gemfile</code> and run <code>bundle install</code> (it won't have been included when you upgraded Rails). Once it's been installed, you can simply drop a reference to the console helper (i.e., <code>&lt;%= console %&gt;</code>) into any view you want to enable it for. A console will also be provided on any error page you view in your development environment.</p><h3 id="responders"><a class="anchorlink" href="#responders" data-turbo="false"><span>11.2</span> Responders</a></h3><p><code>respond_with</code> and the class-level <code>respond_to</code> methods have been extracted to the <code>responders</code> gem. To use them, simply add <code>gem "responders", "~&gt; 2.0"</code> to your <code>Gemfile</code>. Calls to <code>respond_with</code> and <code>respond_to</code> (again, at the class level) will no longer work without having included the <code>responders</code> gem in your dependencies:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># app/controllers/users_controller.rb</span> <span class="k">class</span> <span class="nc">UsersController</span> <span class="o">&lt;</span> <span class="no">ApplicationController</span> <span class="n">respond_to</span> <span class="ss">:html</span><span class="p">,</span> <span class="ss">:json</span> <span class="k">def</span> <span class="nf">show</span> <span class="vi">@user</span> <span class="o">=</span> <span class="no">User</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">respond_with</span> <span class="vi">@user</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text=" class UsersController < ApplicationController respond_to :html, :json def show @user = User.find(params[:id]) respond_with @user end end ">Copy</button> </div> <p>Instance-level <code>respond_to</code> is unaffected and does not require the additional gem:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># app/controllers/users_controller.rb</span> <span class="k">class</span> <span class="nc">UsersController</span> <span class="o">&lt;</span> <span class="no">ApplicationController</span> <span class="k">def</span> <span class="nf">show</span> <span class="vi">@user</span> <span class="o">=</span> <span class="no">User</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">respond_to</span> <span class="k">do</span> <span class="o">|</span><span class="nb">format</span><span class="o">|</span> <span class="nb">format</span><span class="p">.</span><span class="nf">html</span> <span class="nb">format</span><span class="p">.</span><span class="nf">json</span> <span class="p">{</span> <span class="n">render</span> <span class="ss">json: </span><span class="vi">@user</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 UsersController < ApplicationController def show @user = User.find(params[:id]) respond_to do |format| format.html format.json { render json: @user } end end end ">Copy</button> </div> <p>See <a href="https://github.com/rails/rails/pull/16526">#16526</a> for more details.</p><h3 id="error-handling-in-transaction-callbacks"><a class="anchorlink" href="#error-handling-in-transaction-callbacks" data-turbo="false"><span>11.3</span> Error handling in transaction callbacks</a></h3><p>Currently, Active Record suppresses errors raised within <code>after_rollback</code> or <code>after_commit</code> callbacks and only prints them to the logs. In the next version, these errors will no longer be suppressed. Instead, the errors will propagate normally just like in other Active Record callbacks.</p><p>When you define an <code>after_rollback</code> or <code>after_commit</code> callback, you will receive a deprecation warning about this upcoming change. When you are ready, you can opt into the new behavior and remove the deprecation warning by adding following configuration to your <code>config/application.rb</code>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">config</span><span class="p">.</span><span class="nf">active_record</span><span class="p">.</span><span class="nf">raise_in_transactional_callbacks</span> <span class="o">=</span> <span class="kp">true</span> </code></pre> <button class="clipboard-button" data-clipboard-text="config.active_record.raise_in_transactional_callbacks = true ">Copy</button> </div> <p>See <a href="https://github.com/rails/rails/pull/14488">#14488</a> and <a href="https://github.com/rails/rails/pull/16537">#16537</a> for more details.</p><h3 id="ordering-of-test-cases"><a class="anchorlink" href="#ordering-of-test-cases" data-turbo="false"><span>11.4</span> Ordering of test cases</a></h3><p>In Rails 5.0, test cases will be executed in random order by default. In anticipation of this change, Rails 4.2 introduced a new configuration option <code>active_support.test_order</code> for explicitly specifying the test ordering. This allows you to either lock down the current behavior by setting the option to <code>:sorted</code>, or opt into the future behavior by setting the option to <code>:random</code>.</p><p>If you do not specify a value for this option, a deprecation warning will be emitted. To avoid this, add the following line to your test environment:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># config/environments/test.rb</span> <span class="no">Rails</span><span class="p">.</span><span class="nf">application</span><span class="p">.</span><span class="nf">configure</span> <span class="k">do</span> <span class="n">config</span><span class="p">.</span><span class="nf">active_support</span><span class="p">.</span><span class="nf">test_order</span> <span class="o">=</span> <span class="ss">:sorted</span> <span class="c1"># or `:random` if you prefer</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="Rails.application.configure do config.active_support.test_order = :sorted # or `:random` if you prefer end ">Copy</button> </div> <h3 id="serialized-attributes"><a class="anchorlink" href="#serialized-attributes" data-turbo="false"><span>11.5</span> Serialized attributes</a></h3><p>When using a custom coder (e.g. <code>serialize :metadata, JSON</code>), assigning <code>nil</code> to a serialized attribute will save it to the database as <code>NULL</code> instead of passing the <code>nil</code> value through the coder (e.g. <code>"null"</code> when using the <code>JSON</code> coder).</p><h3 id="production-log-level"><a class="anchorlink" href="#production-log-level" data-turbo="false"><span>11.6</span> Production log level</a></h3><p>In Rails 5, the default log level for the production environment will be changed to <code>:debug</code> (from <code>:info</code>). To preserve the current default, add the following line to your <code>production.rb</code>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># Set to `:info` to match the current default, or set to `:debug` to opt-into</span> <span class="c1"># the future default.</span> <span class="n">config</span><span class="p">.</span><span class="nf">log_level</span> <span class="o">=</span> <span class="ss">:info</span> </code></pre> <button class="clipboard-button" data-clipboard-text="# Set to `:info` to match the current default, or set to `:debug` to opt-into # the future default. config.log_level = :info ">Copy</button> </div> <h3 id="after-bundle-in-rails-templates"><a class="anchorlink" href="#after-bundle-in-rails-templates" data-turbo="false"><span>11.7</span> <code>after_bundle</code> in Rails templates</a></h3><p>If you have a Rails template that adds all the files in version control, it fails to add the generated binstubs because it gets executed before Bundler:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># template.rb</span> <span class="n">generate</span><span class="p">(</span><span class="ss">:scaffold</span><span class="p">,</span> <span class="s2">"person name:string"</span><span class="p">)</span> <span class="n">route</span> <span class="s2">"root to: 'people#index'"</span> <span class="n">rake</span><span class="p">(</span><span class="s2">"db:migrate"</span><span class="p">)</span> <span class="n">git</span> <span class="ss">:init</span> <span class="n">git</span> <span class="ss">add: </span><span class="s2">"."</span> <span class="n">git</span> <span class="ss">commit: </span><span class="sx">%Q{ -m 'Initial commit' }</span> </code></pre> <button class="clipboard-button" data-clipboard-text="# template.rb generate(:scaffold, &quot;person name:string&quot;) route &quot;root to: 'people#index'&quot; rake(&quot;db:migrate&quot;) git :init git add: &quot;.&quot; git commit: %Q{ -m 'Initial commit' } ">Copy</button> </div> <p>You can now wrap the <code>git</code> calls in an <code>after_bundle</code> block. It will be run after the binstubs have been generated.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># template.rb</span> <span class="n">generate</span><span class="p">(</span><span class="ss">:scaffold</span><span class="p">,</span> <span class="s2">"person name:string"</span><span class="p">)</span> <span class="n">route</span> <span class="s2">"root to: 'people#index'"</span> <span class="n">rake</span><span class="p">(</span><span class="s2">"db:migrate"</span><span class="p">)</span> <span class="n">after_bundle</span> <span class="k">do</span> <span class="n">git</span> <span class="ss">:init</span> <span class="n">git</span> <span class="ss">add: </span><span class="s2">"."</span> <span class="n">git</span> <span class="ss">commit: </span><span class="sx">%Q{ -m 'Initial commit' }</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="# template.rb generate(:scaffold, &quot;person name:string&quot;) route &quot;root to: 'people#index'&quot; rake(&quot;db:migrate&quot;) after_bundle do git :init git add: &quot;.&quot; git commit: %Q{ -m 'Initial commit' } end ">Copy</button> </div> <h3 id="rails-html-sanitizer"><a class="anchorlink" href="#rails-html-sanitizer" data-turbo="false"><span>11.8</span> Rails HTML Sanitizer</a></h3><p>There's a new choice for sanitizing HTML fragments in your applications. The venerable html-scanner approach is now officially being deprecated in favor of <a href="https://github.com/rails/rails-html-sanitizer"><code>Rails HTML Sanitizer</code></a>.</p><p>This means the methods <code>sanitize</code>, <code>sanitize_css</code>, <code>strip_tags</code> and <code>strip_links</code> are backed by a new implementation.</p><p>This new sanitizer uses <a href="https://github.com/flavorjones/loofah">Loofah</a> internally. Loofah in turn uses Nokogiri, which wraps XML parsers written in both C and Java, so sanitization should be faster no matter which Ruby version you run.</p><p>The new version updates <code>sanitize</code>, so it can take a <code>Loofah::Scrubber</code> for powerful scrubbing. <a href="https://github.com/flavorjones/loofah#loofahscrubber">See some examples of scrubbers here</a>.</p><p>Two new scrubbers have also been added: <code>PermitScrubber</code> and <code>TargetScrubber</code>. Read the <a href="https://github.com/rails/rails-html-sanitizer">gem's readme</a> for more information.</p><p>The documentation for <code>PermitScrubber</code> and <code>TargetScrubber</code> explains how you can gain complete control over when and how elements should be stripped.</p><p>If your application needs to use the old sanitizer implementation, include <code>rails-deprecated_sanitizer</code> in your <code>Gemfile</code>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">gem</span> <span class="s2">"rails-deprecated_sanitizer"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="gem &quot;rails-deprecated_sanitizer&quot; ">Copy</button> </div> <h3 id="rails-dom-testing"><a class="anchorlink" href="#rails-dom-testing" data-turbo="false"><span>11.9</span> Rails DOM Testing</a></h3><p>The <a href="https://api.rubyonrails.org/v4.1/classes/ActionDispatch/Assertions/TagAssertions.html"><code>TagAssertions</code> module</a> (containing methods such as <code>assert_tag</code>), <a href="https://github.com/rails/rails/blob/6061472b8c310158a2a2e8e9a6b81a1aef6b60fe/actionpack/lib/action_dispatch/testing/assertions/dom.rb">has been deprecated</a> in favor of the <code>assert_select</code> methods from the <code>SelectorAssertions</code> module, which has been extracted into the <a href="https://github.com/rails/rails-dom-testing">rails-dom-testing gem</a>.</p><h3 id="masked-authenticity-tokens"><a class="anchorlink" href="#masked-authenticity-tokens" data-turbo="false"><span>11.10</span> Masked Authenticity Tokens</a></h3><p>In order to mitigate SSL attacks, <code>form_authenticity_token</code> is now masked so that it varies with each request. Thus, tokens are validated by unmasking and then decrypting. As a result, any strategies for verifying requests from non-rails forms that relied on a static session CSRF token have to take this into account.</p><h3 id="action-mailer"><a class="anchorlink" href="#action-mailer" data-turbo="false"><span>11.11</span> Action Mailer</a></h3><p>Previously, calling a mailer method on a mailer class will result in the corresponding instance method being executed directly. With the introduction of Active Job and <code>#deliver_later</code>, this is no longer true. In Rails 4.2, the invocation of the instance methods are deferred until either <code>deliver_now</code> or <code>deliver_later</code> is called. For example:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">Notifier</span> <span class="o">&lt;</span> <span class="no">ActionMailer</span><span class="o">::</span><span class="no">Base</span> <span class="k">def</span> <span class="nf">notify</span><span class="p">(</span><span class="n">user</span><span class="p">)</span> <span class="nb">puts</span> <span class="s2">"Called"</span> <span class="n">mail</span><span class="p">(</span><span class="ss">to: </span><span class="n">user</span><span class="p">.</span><span class="nf">email</span><span class="p">)</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class Notifier < ActionMailer::Base def notify(user) puts &quot;Called&quot; mail(to: user.email) end end ">Copy</button> </div> <div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">mail</span> <span class="o">=</span> <span class="no">Notifier</span><span class="p">.</span><span class="nf">notify</span><span class="p">(</span><span class="n">user</span><span class="p">)</span> <span class="c1"># Notifier#notify is not yet called at this point</span> <span class="n">mail</span> <span class="o">=</span> <span class="n">mail</span><span class="p">.</span><span class="nf">deliver_now</span> <span class="c1"># Prints "Called"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="mail = Notifier.notify(user) # Notifier#notify is not yet called at this point mail = mail.deliver_now # Prints &quot;Called&quot; ">Copy</button> </div> <p>This should not result in any noticeable differences for most applications. However, if you need some non-mailer methods to be executed synchronously, and you were previously relying on the synchronous proxying behavior, you should define them as class methods on the mailer class directly:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">Notifier</span> <span class="o">&lt;</span> <span class="no">ActionMailer</span><span class="o">::</span><span class="no">Base</span> <span class="k">def</span> <span class="nc">self</span><span class="o">.</span><span class="nf">broadcast_notifications</span><span class="p">(</span><span class="n">users</span><span class="p">,</span> <span class="o">...</span><span class="p">)</span> <span class="n">users</span><span class="p">.</span><span class="nf">each</span> <span class="p">{</span> <span class="o">|</span><span class="n">user</span><span class="o">|</span> <span class="no">Notifier</span><span class="p">.</span><span class="nf">notify</span><span class="p">(</span><span class="n">user</span><span class="p">,</span> <span class="o">...</span><span class="p">)</span> <span class="p">}</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class Notifier < ActionMailer::Base def self.broadcast_notifications(users, ...) users.each { |user| Notifier.notify(user, ...) } end end ">Copy</button> </div> <h3 id="foreign-key-support"><a class="anchorlink" href="#foreign-key-support" data-turbo="false"><span>11.12</span> Foreign Key Support</a></h3><p>The migration DSL has been expanded to support foreign key definitions. If you've been using the Foreigner gem, you might want to consider removing it. Note that the foreign key support of Rails is a subset of Foreigner. This means that not every Foreigner definition can be fully replaced by its Rails migration DSL counterpart.</p><p>The migration procedure is as follows:</p> <ol> <li>remove <code>gem "foreigner"</code> from the <code>Gemfile</code>.</li> <li>run <code>bundle install</code>.</li> <li>run <code>bin/rake db:schema:dump</code>.</li> <li>make sure that <code>db/schema.rb</code> contains every foreign key definition with the necessary options.</li> </ol> <h2 id="upgrading-from-rails-4-0-to-rails-4-1"><a class="anchorlink" href="#upgrading-from-rails-4-0-to-rails-4-1" data-turbo="false"><span>12</span> Upgrading from Rails 4.0 to Rails 4.1</a></h2><h3 id="csrf-protection-from-remote-script-tags"><a class="anchorlink" href="#csrf-protection-from-remote-script-tags" data-turbo="false"><span>12.1</span> CSRF protection from remote <code>&lt;script&gt;</code> tags</a></h3><p>Or, "whaaat my tests are failing!!!?" or "my <code>&lt;script&gt;</code> widget is busted!!"</p><p>Cross-site request forgery (CSRF) protection now covers GET requests with JavaScript responses, too. This prevents a third-party site from remotely referencing your JavaScript with a <code>&lt;script&gt;</code> tag to extract sensitive data.</p><p>This means that your functional and integration tests that use</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">get</span> <span class="ss">:index</span><span class="p">,</span> <span class="ss">format: :js</span> </code></pre> <button class="clipboard-button" data-clipboard-text="get :index, format: :js ">Copy</button> </div> <p>will now trigger CSRF protection. Switch to</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">xhr</span> <span class="ss">:get</span><span class="p">,</span> <span class="ss">:index</span><span class="p">,</span> <span class="ss">format: :js</span> </code></pre> <button class="clipboard-button" data-clipboard-text="xhr :get, :index, format: :js ">Copy</button> </div> <p>to explicitly test an <code>XmlHttpRequest</code>.</p><div class="interstitial note"><p>Your own <code>&lt;script&gt;</code> tags are treated as cross-origin and blocked by default, too. If you really mean to load JavaScript from <code>&lt;script&gt;</code> tags, you must now explicitly skip CSRF protection on those actions.</p></div><h3 id="upgrading-from-rails-4-0-to-rails-4-1-spring"><a class="anchorlink" href="#upgrading-from-rails-4-0-to-rails-4-1-spring" data-turbo="false"><span>12.2</span> Spring</a></h3><p>If you want to use Spring as your application preloader you need to:</p> <ol> <li>Add <code>gem "spring", group: :development</code> to your <code>Gemfile</code>.</li> <li>Install spring using <code>bundle install</code>.</li> <li>Generate the Spring binstub with <code>bundle exec spring binstub</code>.</li> </ol> <div class="interstitial note"><p>User defined rake tasks will run in the <code>development</code> environment by default. If you want them to run in other environments consult the <a href="https://github.com/rails/spring#rake">Spring README</a>.</p></div><h3 id="config-secrets-yml"><a class="anchorlink" href="#config-secrets-yml" data-turbo="false"><span>12.3</span> <code>config/secrets.yml</code></a></h3><p>If you want to use the new <code>secrets.yml</code> convention to store your application's secrets, you need to:</p> <ol> <li><p>Create a <code>secrets.yml</code> file in your <code>config</code> folder with the following content:</p><div class="interstitial code"> <pre><code class="highlight yaml"><span class="na">development</span><span class="pi">:</span> <span class="na">secret_key_base</span><span class="pi">:</span> <span class="na">test</span><span class="pi">:</span> <span class="na">secret_key_base</span><span class="pi">:</span> <span class="na">production</span><span class="pi">:</span> <span class="na">secret_key_base</span><span class="pi">:</span> <span class="s">&lt;%= ENV["SECRET_KEY_BASE"] %&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="development: secret_key_base: test: secret_key_base: production: secret_key_base: <%= ENV[&quot;SECRET_KEY_BASE&quot;] %> ">Copy</button> </div></li> <li><p>Use your existing <code>secret_key_base</code> from the <code>secret_token.rb</code> initializer to set the <code>SECRET_KEY_BASE</code> environment variable for whichever users running the Rails application in production. Alternatively, you can simply copy the existing <code>secret_key_base</code> from the <code>secret_token.rb</code> initializer to <code>secrets.yml</code> under the <code>production</code> section, replacing <code>&lt;%= ENV["SECRET_KEY_BASE"] %&gt;</code>.</p></li> <li><p>Remove the <code>secret_token.rb</code> initializer.</p></li> <li><p>Use <code>rake secret</code> to generate new keys for the <code>development</code> and <code>test</code> sections.</p></li> <li><p>Restart your server.</p></li> </ol> <h3 id="changes-to-test-helper"><a class="anchorlink" href="#changes-to-test-helper" data-turbo="false"><span>12.4</span> Changes to test helper</a></h3><p>If your test helper contains a call to <code>ActiveRecord::Migration.check_pending!</code> this can be removed. The check is now done automatically when you <code>require "rails/test_help"</code>, although leaving this line in your helper is not harmful in any way.</p><h3 id="cookies-serializer"><a class="anchorlink" href="#cookies-serializer" data-turbo="false"><span>12.5</span> Cookies serializer</a></h3><p>Applications created before Rails 4.1 uses <code>Marshal</code> to serialize cookie values into the signed and encrypted cookie jars. If you want to use the new <code>JSON</code>-based format in your application, you can add an initializer file with the following content:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">Rails</span><span class="p">.</span><span class="nf">application</span><span class="p">.</span><span class="nf">config</span><span class="p">.</span><span class="nf">action_dispatch</span><span class="p">.</span><span class="nf">cookies_serializer</span> <span class="o">=</span> <span class="ss">:hybrid</span> </code></pre> <button class="clipboard-button" data-clipboard-text="Rails.application.config.action_dispatch.cookies_serializer = :hybrid ">Copy</button> </div> <p>This would transparently migrate your existing <code>Marshal</code>-serialized cookies into the new <code>JSON</code>-based format.</p><p>When using the <code>:json</code> or <code>:hybrid</code> serializer, you should beware that not all Ruby objects can be serialized as JSON. For example, <code>Date</code> and <code>Time</code> objects will be serialized as strings, and <code>Hash</code>es will have their keys stringified.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">CookiesController</span> <span class="o">&lt;</span> <span class="no">ApplicationController</span> <span class="k">def</span> <span class="nf">set_cookie</span> <span class="n">cookies</span><span class="p">.</span><span class="nf">encrypted</span><span class="p">[</span><span class="ss">:expiration_date</span><span class="p">]</span> <span class="o">=</span> <span class="no">Date</span><span class="p">.</span><span class="nf">tomorrow</span> <span class="c1"># =&gt; Thu, 20 Mar 2014</span> <span class="n">redirect_to</span> <span class="ss">action: </span><span class="s2">"read_cookie"</span> <span class="k">end</span> <span class="k">def</span> <span class="nf">read_cookie</span> <span class="n">cookies</span><span class="p">.</span><span class="nf">encrypted</span><span class="p">[</span><span class="ss">:expiration_date</span><span class="p">]</span> <span class="c1"># =&gt; "2014-03-20"</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class CookiesController < ApplicationController def set_cookie cookies.encrypted[:expiration_date] = Date.tomorrow # => Thu, 20 Mar 2014 redirect_to action: &quot;read_cookie&quot; end def read_cookie cookies.encrypted[:expiration_date] # => &quot;2014-03-20&quot; end end ">Copy</button> </div> <p>It's advisable that you only store simple data (strings and numbers) in cookies. If you have to store complex objects, you would need to handle the conversion manually when reading the values on subsequent requests.</p><p>If you use the cookie session store, this would apply to the <code>session</code> and <code>flash</code> hash as well.</p><h3 id="flash-structure-changes"><a class="anchorlink" href="#flash-structure-changes" data-turbo="false"><span>12.6</span> Flash structure changes</a></h3><p>Flash message keys are <a href="https://github.com/rails/rails/commit/a668beffd64106a1e1fedb71cc25eaaa11baf0c1">normalized to strings</a>. They can still be accessed using either symbols or strings. Looping through the flash will always yield string keys:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">flash</span><span class="p">[</span><span class="s2">"string"</span><span class="p">]</span> <span class="o">=</span> <span class="s2">"a string"</span> <span class="n">flash</span><span class="p">[</span><span class="ss">:symbol</span><span class="p">]</span> <span class="o">=</span> <span class="s2">"a symbol"</span> <span class="c1"># Rails &lt; 4.1</span> <span class="n">flash</span><span class="p">.</span><span class="nf">keys</span> <span class="c1"># =&gt; ["string", :symbol]</span> <span class="c1"># Rails &gt;= 4.1</span> <span class="n">flash</span><span class="p">.</span><span class="nf">keys</span> <span class="c1"># =&gt; ["string", "symbol"]</span> </code></pre> <button class="clipboard-button" data-clipboard-text="flash[&quot;string&quot;] = &quot;a string&quot; flash[:symbol] = &quot;a symbol&quot; # Rails < 4.1 flash.keys # => [&quot;string&quot;, :symbol] # Rails >= 4.1 flash.keys # => [&quot;string&quot;, &quot;symbol&quot;] ">Copy</button> </div> <p>Make sure you are comparing Flash message keys against strings.</p><h3 id="changes-in-json-handling"><a class="anchorlink" href="#changes-in-json-handling" data-turbo="false"><span>12.7</span> Changes in JSON handling</a></h3><p>There are a few major changes related to JSON handling in Rails 4.1.</p><h4 id="multijson-removal"><a class="anchorlink" href="#multijson-removal" data-turbo="false"><span>12.7.1</span> MultiJSON removal</a></h4><p>MultiJSON has reached its <a href="https://github.com/rails/rails/pull/10576">end-of-life</a> and has been removed from Rails.</p><p>If your application currently depends on MultiJSON directly, you have a few options:</p> <ol> <li><p>Add 'multi_json' to your <code>Gemfile</code>. Note that this might cease to work in the future</p></li> <li><p>Migrate away from MultiJSON by using <code>obj.to_json</code>, and <code>JSON.parse(str)</code> instead.</p></li> </ol> <div class="interstitial warning"><p>Do not simply replace <code>MultiJson.dump</code> and <code>MultiJson.load</code> with <code>JSON.dump</code> and <code>JSON.load</code>. These JSON gem APIs are meant for serializing and deserializing arbitrary Ruby objects and are generally <a href="https://ruby-doc.org/stdlib-2.2.2/libdoc/json/rdoc/JSON.html#method-i-load">unsafe</a>.</p></div><h4 id="json-gem-compatibility"><a class="anchorlink" href="#json-gem-compatibility" data-turbo="false"><span>12.7.2</span> JSON gem compatibility</a></h4><p>Historically, Rails had some compatibility issues with the JSON gem. Using <code>JSON.generate</code> and <code>JSON.dump</code> inside a Rails application could produce unexpected errors.</p><p>Rails 4.1 fixed these issues by isolating its own encoder from the JSON gem. The JSON gem APIs will function as normal, but they will not have access to any Rails-specific features. For example:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">FooBar</span> <span class="k">def</span> <span class="nf">as_json</span><span class="p">(</span><span class="n">options</span> <span class="o">=</span> <span class="kp">nil</span><span class="p">)</span> <span class="p">{</span> <span class="ss">foo: </span><span class="s2">"bar"</span> <span class="p">}</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class FooBar def as_json(options = nil) { foo: &quot;bar&quot; } end end ">Copy</button> </div> <div class="interstitial code"> <pre><code class="highlight irb"><span class="gp">irb&gt;</span><span class="w"> </span><span class="no">FooBar</span><span class="p">.</span><span class="nf">new</span><span class="p">.</span><span class="nf">to_json</span> <span class="p">=&gt;</span> <span class="s2">"{</span><span class="se">\"</span><span class="s2">foo</span><span class="se">\"</span><span class="s2">:</span><span class="se">\"</span><span class="s2">bar</span><span class="se">\"</span><span class="s2">}"</span> <span class="gp">irb&gt;</span><span class="w"> </span><span class="no">JSON</span><span class="p">.</span><span class="nf">generate</span><span class="p">(</span><span class="no">FooBar</span><span class="p">.</span><span class="nf">new</span><span class="p">,</span> <span class="ss">quirks_mode: </span><span class="kp">true</span><span class="p">)</span> <span class="p">=&gt;</span> <span class="s2">"</span><span class="se">\"</span><span class="s2">#&lt;FooBar:0x007fa80a481610&gt;</span><span class="se">\"</span><span class="s2">"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="FooBar.new.to_json JSON.generate(FooBar.new, quirks_mode: true) ">Copy</button> </div> <h4 id="new-json-encoder"><a class="anchorlink" href="#new-json-encoder" data-turbo="false"><span>12.7.3</span> New JSON encoder</a></h4><p>The JSON encoder in Rails 4.1 has been rewritten to take advantage of the JSON gem. For most applications, this should be a transparent change. However, as part of the rewrite, the following features have been removed from the encoder:</p> <ol> <li>Circular data structure detection</li> <li>Support for the <code>encode_json</code> hook</li> <li>Option to encode <code>BigDecimal</code> objects as numbers instead of strings</li> </ol> <p>If your application depends on one of these features, you can get them back by adding the <a href="https://github.com/rails/activesupport-json_encoder"><code>activesupport-json_encoder</code></a> gem to your <code>Gemfile</code>.</p><h4 id="json-representation-of-time-objects"><a class="anchorlink" href="#json-representation-of-time-objects" data-turbo="false"><span>12.7.4</span> JSON representation of Time objects</a></h4><p><code>#as_json</code> for objects with time component (<code>Time</code>, <code>DateTime</code>, <code>ActiveSupport::TimeWithZone</code>) now returns millisecond precision by default. If you need to keep old behavior with no millisecond precision, set the following in an initializer:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="no">ActiveSupport</span><span class="o">::</span><span class="no">JSON</span><span class="o">::</span><span class="no">Encoding</span><span class="p">.</span><span class="nf">time_precision</span> <span class="o">=</span> <span class="mi">0</span> </code></pre> <button class="clipboard-button" data-clipboard-text="ActiveSupport::JSON::Encoding.time_precision = 0 ">Copy</button> </div> <h3 id="usage-of-return-within-inline-callback-blocks"><a class="anchorlink" href="#usage-of-return-within-inline-callback-blocks" data-turbo="false"><span>12.8</span> Usage of <code>return</code> within inline callback blocks</a></h3><p>Previously, Rails allowed inline callback blocks to use <code>return</code> this way:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">ReadOnlyModel</span> <span class="o">&lt;</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Base</span> <span class="n">before_save</span> <span class="p">{</span> <span class="k">return</span> <span class="kp">false</span> <span class="p">}</span> <span class="c1"># BAD</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class ReadOnlyModel < ActiveRecord::Base before_save { return false } # BAD end ">Copy</button> </div> <p>This behavior was never intentionally supported. Due to a change in the internals of <code>ActiveSupport::Callbacks</code>, this is no longer allowed in Rails 4.1. Using a <code>return</code> statement in an inline callback block causes a <code>LocalJumpError</code> to be raised when the callback is executed.</p><p>Inline callback blocks using <code>return</code> can be refactored to evaluate to the returned value:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">ReadOnlyModel</span> <span class="o">&lt;</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Base</span> <span class="n">before_save</span> <span class="p">{</span> <span class="kp">false</span> <span class="p">}</span> <span class="c1"># GOOD</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class ReadOnlyModel < ActiveRecord::Base before_save { false } # GOOD end ">Copy</button> </div> <p>Alternatively, if <code>return</code> is preferred it is recommended to explicitly define a method:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">ReadOnlyModel</span> <span class="o">&lt;</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Base</span> <span class="n">before_save</span> <span class="ss">:before_save_callback</span> <span class="c1"># GOOD</span> <span class="kp">private</span> <span class="k">def</span> <span class="nf">before_save_callback</span> <span class="kp">false</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class ReadOnlyModel < ActiveRecord::Base before_save :before_save_callback # GOOD private def before_save_callback false end end ">Copy</button> </div> <p>This change applies to most places in Rails where callbacks are used, including Active Record and Active Model callbacks, as well as filters in Action Controller (e.g. <code>before_action</code>).</p><p>See <a href="https://github.com/rails/rails/pull/13271">this pull request</a> for more details.</p><h3 id="methods-defined-in-active-record-fixtures"><a class="anchorlink" href="#methods-defined-in-active-record-fixtures" data-turbo="false"><span>12.9</span> Methods defined in Active Record fixtures</a></h3><p>Rails 4.1 evaluates each fixture's ERB in a separate context, so helper methods defined in a fixture will not be available in other fixtures.</p><p>Helper methods that are used in multiple fixtures should be defined on modules included in the newly introduced <code>ActiveRecord::FixtureSet.context_class</code>, in <code>test_helper.rb</code>.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">module</span> <span class="nn">FixtureFileHelpers</span> <span class="k">def</span> <span class="nf">file_sha</span><span class="p">(</span><span class="n">path</span><span class="p">)</span> <span class="no">OpenSSL</span><span class="o">::</span><span class="no">Digest</span><span class="o">::</span><span class="no">SHA256</span><span class="p">.</span><span class="nf">hexdigest</span><span class="p">(</span><span class="no">File</span><span class="p">.</span><span class="nf">read</span><span class="p">(</span><span class="no">Rails</span><span class="p">.</span><span class="nf">root</span><span class="p">.</span><span class="nf">join</span><span class="p">(</span><span class="s2">"test/fixtures"</span><span class="p">,</span> <span class="n">path</span><span class="p">)))</span> <span class="k">end</span> <span class="k">end</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">FixtureSet</span><span class="p">.</span><span class="nf">context_class</span><span class="p">.</span><span class="nf">include</span> <span class="no">FixtureFileHelpers</span> </code></pre> <button class="clipboard-button" data-clipboard-text="module FixtureFileHelpers def file_sha(path) OpenSSL::Digest::SHA256.hexdigest(File.read(Rails.root.join(&quot;test/fixtures&quot;, path))) end end ActiveRecord::FixtureSet.context_class.include FixtureFileHelpers ">Copy</button> </div> <h3 id="i18n-enforcing-available-locales"><a class="anchorlink" href="#i18n-enforcing-available-locales" data-turbo="false"><span>12.10</span> I18n enforcing available locales</a></h3><p>Rails 4.1 now defaults the I18n option <code>enforce_available_locales</code> to <code>true</code>. This means that it will make sure that all locales passed to it must be declared in the <code>available_locales</code> list.</p><p>To disable it (and allow I18n to accept <em>any</em> locale option) add the following configuration to your application:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">config</span><span class="p">.</span><span class="nf">i18n</span><span class="p">.</span><span class="nf">enforce_available_locales</span> <span class="o">=</span> <span class="kp">false</span> </code></pre> <button class="clipboard-button" data-clipboard-text="config.i18n.enforce_available_locales = false ">Copy</button> </div> <p>Note that this option was added as a security measure, to ensure user input cannot be used as locale information unless it is previously known. Therefore, it's recommended not to disable this option unless you have a strong reason for doing so.</p><h3 id="mutator-methods-called-on-relation"><a class="anchorlink" href="#mutator-methods-called-on-relation" data-turbo="false"><span>12.11</span> Mutator methods called on Relation</a></h3><p><code>Relation</code> no longer has mutator methods like <code>#map!</code> and <code>#delete_if</code>. Convert to an <code>Array</code> by calling <code>#to_a</code> before using these methods.</p><p>It intends to prevent odd bugs and confusion in code that call mutator methods directly on the <code>Relation</code>.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># Instead of this</span> <span class="no">Author</span><span class="p">.</span><span class="nf">where</span><span class="p">(</span><span class="ss">name: </span><span class="s2">"Hank Moody"</span><span class="p">).</span><span class="nf">compact!</span> <span class="c1"># Now you have to do this</span> <span class="n">authors</span> <span class="o">=</span> <span class="no">Author</span><span class="p">.</span><span class="nf">where</span><span class="p">(</span><span class="ss">name: </span><span class="s2">"Hank Moody"</span><span class="p">).</span><span class="nf">to_a</span> <span class="n">authors</span><span class="p">.</span><span class="nf">compact!</span> </code></pre> <button class="clipboard-button" data-clipboard-text="# Instead of this Author.where(name: &quot;Hank Moody&quot;).compact! # Now you have to do this authors = Author.where(name: &quot;Hank Moody&quot;).to_a authors.compact! ">Copy</button> </div> <h3 id="changes-on-default-scopes"><a class="anchorlink" href="#changes-on-default-scopes" data-turbo="false"><span>12.12</span> Changes on Default Scopes</a></h3><p>Default scopes are no longer overridden by chained conditions.</p><p>In previous versions when you defined a <code>default_scope</code> in a model it was overridden by chained conditions in the same field. Now it is merged like any other scope.</p><p>Before:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">User</span> <span class="o">&lt;</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Base</span> <span class="n">default_scope</span> <span class="p">{</span> <span class="n">where</span> <span class="ss">state: </span><span class="s2">"pending"</span> <span class="p">}</span> <span class="n">scope</span> <span class="ss">:active</span><span class="p">,</span> <span class="o">-&gt;</span> <span class="p">{</span> <span class="n">where</span> <span class="ss">state: </span><span class="s2">"active"</span> <span class="p">}</span> <span class="n">scope</span> <span class="ss">:inactive</span><span class="p">,</span> <span class="o">-&gt;</span> <span class="p">{</span> <span class="n">where</span> <span class="ss">state: </span><span class="s2">"inactive"</span> <span class="p">}</span> <span class="k">end</span> <span class="no">User</span><span class="p">.</span><span class="nf">all</span> <span class="c1"># SELECT "users".* FROM "users" WHERE "users"."state" = 'pending'</span> <span class="no">User</span><span class="p">.</span><span class="nf">active</span> <span class="c1"># SELECT "users".* FROM "users" WHERE "users"."state" = 'active'</span> <span class="no">User</span><span class="p">.</span><span class="nf">where</span><span class="p">(</span><span class="ss">state: </span><span class="s2">"inactive"</span><span class="p">)</span> <span class="c1"># SELECT "users".* FROM "users" WHERE "users"."state" = 'inactive'</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class User < ActiveRecord::Base default_scope { where state: &quot;pending&quot; } scope :active, -> { where state: &quot;active&quot; } scope :inactive, -> { where state: &quot;inactive&quot; } end User.all # SELECT &quot;users&quot;.* FROM &quot;users&quot; WHERE &quot;users&quot;.&quot;state&quot; = 'pending' User.active # SELECT &quot;users&quot;.* FROM &quot;users&quot; WHERE &quot;users&quot;.&quot;state&quot; = 'active' User.where(state: &quot;inactive&quot;) # SELECT &quot;users&quot;.* FROM &quot;users&quot; WHERE &quot;users&quot;.&quot;state&quot; = 'inactive' ">Copy</button> </div> <p>After:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">User</span> <span class="o">&lt;</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Base</span> <span class="n">default_scope</span> <span class="p">{</span> <span class="n">where</span> <span class="ss">state: </span><span class="s2">"pending"</span> <span class="p">}</span> <span class="n">scope</span> <span class="ss">:active</span><span class="p">,</span> <span class="o">-&gt;</span> <span class="p">{</span> <span class="n">where</span> <span class="ss">state: </span><span class="s2">"active"</span> <span class="p">}</span> <span class="n">scope</span> <span class="ss">:inactive</span><span class="p">,</span> <span class="o">-&gt;</span> <span class="p">{</span> <span class="n">where</span> <span class="ss">state: </span><span class="s2">"inactive"</span> <span class="p">}</span> <span class="k">end</span> <span class="no">User</span><span class="p">.</span><span class="nf">all</span> <span class="c1"># SELECT "users".* FROM "users" WHERE "users"."state" = 'pending'</span> <span class="no">User</span><span class="p">.</span><span class="nf">active</span> <span class="c1"># SELECT "users".* FROM "users" WHERE "users"."state" = 'pending' AND "users"."state" = 'active'</span> <span class="no">User</span><span class="p">.</span><span class="nf">where</span><span class="p">(</span><span class="ss">state: </span><span class="s2">"inactive"</span><span class="p">)</span> <span class="c1"># SELECT "users".* FROM "users" WHERE "users"."state" = 'pending' AND "users"."state" = 'inactive'</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class User < ActiveRecord::Base default_scope { where state: &quot;pending&quot; } scope :active, -> { where state: &quot;active&quot; } scope :inactive, -> { where state: &quot;inactive&quot; } end User.all # SELECT &quot;users&quot;.* FROM &quot;users&quot; WHERE &quot;users&quot;.&quot;state&quot; = 'pending' User.active # SELECT &quot;users&quot;.* FROM &quot;users&quot; WHERE &quot;users&quot;.&quot;state&quot; = 'pending' AND &quot;users&quot;.&quot;state&quot; = 'active' User.where(state: &quot;inactive&quot;) # SELECT &quot;users&quot;.* FROM &quot;users&quot; WHERE &quot;users&quot;.&quot;state&quot; = 'pending' AND &quot;users&quot;.&quot;state&quot; = 'inactive' ">Copy</button> </div> <p>To get the previous behavior it is needed to explicitly remove the <code>default_scope</code> condition using <code>unscoped</code>, <code>unscope</code>, <code>rewhere</code> or <code>except</code>.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">User</span> <span class="o">&lt;</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Base</span> <span class="n">default_scope</span> <span class="p">{</span> <span class="n">where</span> <span class="ss">state: </span><span class="s2">"pending"</span> <span class="p">}</span> <span class="n">scope</span> <span class="ss">:active</span><span class="p">,</span> <span class="o">-&gt;</span> <span class="p">{</span> <span class="n">unscope</span><span class="p">(</span><span class="ss">where: :state</span><span class="p">).</span><span class="nf">where</span><span class="p">(</span><span class="ss">state: </span><span class="s2">"active"</span><span class="p">)</span> <span class="p">}</span> <span class="n">scope</span> <span class="ss">:inactive</span><span class="p">,</span> <span class="o">-&gt;</span> <span class="p">{</span> <span class="n">rewhere</span> <span class="ss">state: </span><span class="s2">"inactive"</span> <span class="p">}</span> <span class="k">end</span> <span class="no">User</span><span class="p">.</span><span class="nf">all</span> <span class="c1"># SELECT "users".* FROM "users" WHERE "users"."state" = 'pending'</span> <span class="no">User</span><span class="p">.</span><span class="nf">active</span> <span class="c1"># SELECT "users".* FROM "users" WHERE "users"."state" = 'active'</span> <span class="no">User</span><span class="p">.</span><span class="nf">inactive</span> <span class="c1"># SELECT "users".* FROM "users" WHERE "users"."state" = 'inactive'</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class User < ActiveRecord::Base default_scope { where state: &quot;pending&quot; } scope :active, -> { unscope(where: :state).where(state: &quot;active&quot;) } scope :inactive, -> { rewhere state: &quot;inactive&quot; } end User.all # SELECT &quot;users&quot;.* FROM &quot;users&quot; WHERE &quot;users&quot;.&quot;state&quot; = 'pending' User.active # SELECT &quot;users&quot;.* FROM &quot;users&quot; WHERE &quot;users&quot;.&quot;state&quot; = 'active' User.inactive # SELECT &quot;users&quot;.* FROM &quot;users&quot; WHERE &quot;users&quot;.&quot;state&quot; = 'inactive' ">Copy</button> </div> <h3 id="rendering-content-from-string"><a class="anchorlink" href="#rendering-content-from-string" data-turbo="false"><span>12.13</span> Rendering content from string</a></h3><p>Rails 4.1 introduces <code>:plain</code>, <code>:html</code>, and <code>:body</code> options to <code>render</code>. Those options are now the preferred way to render string-based content, as it allows you to specify which content type you want the response sent as.</p> <ul> <li><code>render :plain</code> will set the content type to <code>text/plain</code></li> <li><code>render :html</code> will set the content type to <code>text/html</code></li> <li><code>render :body</code> will <em>not</em> set the content type header.</li> </ul> <p>From the security standpoint, if you don't expect to have any markup in your response body, you should be using <code>render :plain</code> as most browsers will escape unsafe content in the response for you.</p><p>We will be deprecating the use of <code>render :text</code> in a future version. So please start using the more precise <code>:plain</code>, <code>:html</code>, and <code>:body</code> options instead. Using <code>render :text</code> may pose a security risk, as the content is sent as <code>text/html</code>.</p><h3 id="postgresql-json-and-hstore-datatypes"><a class="anchorlink" href="#postgresql-json-and-hstore-datatypes" data-turbo="false"><span>12.14</span> PostgreSQL JSON and hstore datatypes</a></h3><p>Rails 4.1 will map <code>json</code> and <code>hstore</code> columns to a string-keyed Ruby <code>Hash</code>. In earlier versions, a <code>HashWithIndifferentAccess</code> was used. This means that symbol access is no longer supported. This is also the case for <code>store_accessors</code> based on top of <code>json</code> or <code>hstore</code> columns. Make sure to use string keys consistently.</p><h3 id="explicit-block-use-for-activesupport-callbacks"><a class="anchorlink" href="#explicit-block-use-for-activesupport-callbacks" data-turbo="false"><span>12.15</span> Explicit block use for <code>ActiveSupport::Callbacks</code></a></h3><p>Rails 4.1 now expects an explicit block to be passed when calling <code>ActiveSupport::Callbacks.set_callback</code>. This change stems from <code>ActiveSupport::Callbacks</code> being largely rewritten for the 4.1 release.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># Previously in Rails 4.0</span> <span class="n">set_callback</span> <span class="ss">:save</span><span class="p">,</span> <span class="ss">:around</span><span class="p">,</span> <span class="o">-&gt;</span><span class="p">(</span><span class="n">r</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">block</span><span class="p">)</span> <span class="p">{</span> <span class="n">stuff</span><span class="p">;</span> <span class="n">result</span> <span class="o">=</span> <span class="n">block</span><span class="p">.</span><span class="nf">call</span><span class="p">;</span> <span class="n">stuff</span> <span class="p">}</span> <span class="c1"># Now in Rails 4.1</span> <span class="n">set_callback</span> <span class="ss">:save</span><span class="p">,</span> <span class="ss">:around</span><span class="p">,</span> <span class="o">-&gt;</span><span class="p">(</span><span class="n">r</span><span class="p">,</span> <span class="n">block</span><span class="p">)</span> <span class="p">{</span> <span class="n">stuff</span><span class="p">;</span> <span class="n">result</span> <span class="o">=</span> <span class="n">block</span><span class="p">.</span><span class="nf">call</span><span class="p">;</span> <span class="n">stuff</span> <span class="p">}</span> </code></pre> <button class="clipboard-button" data-clipboard-text="# Previously in Rails 4.0 set_callback :save, :around, ->(r, &amp;block) { stuff; result = block.call; stuff } # Now in Rails 4.1 set_callback :save, :around, ->(r, block) { stuff; result = block.call; stuff } ">Copy</button> </div> <h2 id="upgrading-from-rails-3-2-to-rails-4-0"><a class="anchorlink" href="#upgrading-from-rails-3-2-to-rails-4-0" data-turbo="false"><span>13</span> Upgrading from Rails 3.2 to Rails 4.0</a></h2><p>If your application is currently on any version of Rails older than 3.2.x, you should upgrade to Rails 3.2 before attempting one to Rails 4.0.</p><p>The following changes are meant for upgrading your application to Rails 4.0.</p><h3 id="http-patch"><a class="anchorlink" href="#http-patch" data-turbo="false"><span>13.1</span> HTTP PATCH</a></h3><p>Rails 4 now uses <code>PATCH</code> as the primary HTTP verb for updates when a RESTful resource is declared in <code>config/routes.rb</code>. The <code>update</code> action is still used, and <code>PUT</code> requests will continue to be routed to the <code>update</code> action as well. So, if you're using only the standard RESTful routes, no changes need to be made:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">resources</span> <span class="ss">:users</span> </code></pre> <button class="clipboard-button" data-clipboard-text="resources :users ">Copy</button> </div> <div class="interstitial code"> <pre><code class="highlight erb"><span class="cp">&lt;%=</span> <span class="n">form_for</span> <span class="vi">@user</span> <span class="k">do</span> <span class="o">|</span><span class="n">f</span><span class="o">|</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<%= form_for @user do |f| %> ">Copy</button> </div> <div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">UsersController</span> <span class="o">&lt;</span> <span class="no">ApplicationController</span> <span class="k">def</span> <span class="nf">update</span> <span class="c1"># No change needed; PATCH will be preferred, and PUT will still work.</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class UsersController < ApplicationController def update # No change needed; PATCH will be preferred, and PUT will still work. end end ">Copy</button> </div> <p>However, you will need to make a change if you are using <code>form_for</code> to update a resource in conjunction with a custom route using the <code>PUT</code> HTTP method:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">resources</span> <span class="ss">:users</span> <span class="k">do</span> <span class="n">put</span> <span class="ss">:update_name</span><span class="p">,</span> <span class="ss">on: :member</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="resources :users do put :update_name, on: :member end ">Copy</button> </div> <div class="interstitial code"> <pre><code class="highlight erb"><span class="cp">&lt;%=</span> <span class="n">form_for</span> <span class="p">[</span> <span class="ss">:update_name</span><span class="p">,</span> <span class="vi">@user</span> <span class="p">]</span> <span class="k">do</span> <span class="o">|</span><span class="n">f</span><span class="o">|</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<%= form_for [ :update_name, @user ] do |f| %> ">Copy</button> </div> <div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">UsersController</span> <span class="o">&lt;</span> <span class="no">ApplicationController</span> <span class="k">def</span> <span class="nf">update_name</span> <span class="c1"># Change needed; form_for will try to use a non-existent PATCH route.</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class UsersController < ApplicationController def update_name # Change needed; form_for will try to use a non-existent PATCH route. end end ">Copy</button> </div> <p>If the action is not being used in a public API and you are free to change the HTTP method, you can update your route to use <code>patch</code> instead of <code>put</code>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">resources</span> <span class="ss">:users</span> <span class="k">do</span> <span class="n">patch</span> <span class="ss">:update_name</span><span class="p">,</span> <span class="ss">on: :member</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="resources :users do patch :update_name, on: :member end ">Copy</button> </div> <p><code>PUT</code> requests to <code>/users/:id</code> in Rails 4 get routed to <code>update</code> as they are today. So, if you have an API that gets real PUT requests it is going to work. The router also routes <code>PATCH</code> requests to <code>/users/:id</code> to the <code>update</code> action.</p><p>If the action is being used in a public API and you can't change to HTTP method being used, you can update your form to use the <code>PUT</code> method instead:</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="cp">&lt;%=</span> <span class="n">form_for</span> <span class="p">[</span> <span class="ss">:update_name</span><span class="p">,</span> <span class="vi">@user</span> <span class="p">],</span> <span class="ss">method: :put</span> <span class="k">do</span> <span class="o">|</span><span class="n">f</span><span class="o">|</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<%= form_for [ :update_name, @user ], method: :put do |f| %> ">Copy</button> </div> <p>For more on PATCH and why this change was made, see <a href="https://weblog.rubyonrails.org/2012/2/26/edge-rails-patch-is-the-new-primary-http-method-for-updates/">this post</a> on the Rails blog.</p><h4 id="a-note-about-media-types"><a class="anchorlink" href="#a-note-about-media-types" data-turbo="false"><span>13.1.1</span> A note about media types</a></h4><p>The errata for the <code>PATCH</code> verb <a href="http://www.rfc-editor.org/errata_search.php?rfc=5789">specifies that a 'diff' media type should be used with <code>PATCH</code></a>. One such format is <a href="https://tools.ietf.org/html/rfc6902">JSON Patch</a>. While Rails does not support JSON Patch natively, it's easy enough to add support:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># in your controller:</span> <span class="k">def</span> <span class="nf">update</span> <span class="n">respond_to</span> <span class="k">do</span> <span class="o">|</span><span class="nb">format</span><span class="o">|</span> <span class="nb">format</span><span class="p">.</span><span class="nf">json</span> <span class="k">do</span> <span class="c1"># perform a partial update</span> <span class="vi">@article</span><span class="p">.</span><span class="nf">update</span> <span class="n">params</span><span class="p">[</span><span class="ss">:article</span><span class="p">]</span> <span class="k">end</span> <span class="nb">format</span><span class="p">.</span><span class="nf">json_patch</span> <span class="k">do</span> <span class="c1"># perform sophisticated change</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="# in your controller: def update respond_to do |format| format.json do # perform a partial update @article.update params[:article] end format.json_patch do # perform sophisticated change end end end ">Copy</button> </div> <div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># config/initializers/json_patch.rb</span> <span class="no">Mime</span><span class="o">::</span><span class="no">Type</span><span class="p">.</span><span class="nf">register</span> <span class="s2">"application/json-patch+json"</span><span class="p">,</span> <span class="ss">:json_patch</span> </code></pre> <button class="clipboard-button" data-clipboard-text="Mime::Type.register &quot;application/json-patch+json&quot;, :json_patch ">Copy</button> </div> <p>As JSON Patch was only recently made into an RFC, there aren't a lot of great Ruby libraries yet. Aaron Patterson's <a href="https://github.com/tenderlove/hana">hana</a> is one such gem, but doesn't have full support for the last few changes in the specification.</p><h3 id="upgrading-from-rails-3-2-to-rails-4-0-gemfile"><a class="anchorlink" href="#upgrading-from-rails-3-2-to-rails-4-0-gemfile" data-turbo="false"><span>13.2</span> Gemfile</a></h3><p>Rails 4.0 removed the <code>assets</code> group from <code>Gemfile</code>. You'd need to remove that line from your <code>Gemfile</code> when upgrading. You should also update your application file (in <code>config/application.rb</code>):</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># Require the gems listed in Gemfile, including any gems</span> <span class="c1"># you've limited to :test, :development, or :production.</span> <span class="no">Bundler</span><span class="p">.</span><span class="nf">require</span><span class="p">(</span><span class="o">*</span><span class="no">Rails</span><span class="p">.</span><span class="nf">groups</span><span class="p">)</span> </code></pre> <button class="clipboard-button" data-clipboard-text="# Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) ">Copy</button> </div> <h3 id="upgrading-from-rails-3-2-to-rails-4-0-vendor-plugins"><a class="anchorlink" href="#upgrading-from-rails-3-2-to-rails-4-0-vendor-plugins" data-turbo="false"><span>13.3</span> vendor/plugins</a></h3><p>Rails 4.0 no longer supports loading plugins from <code>vendor/plugins</code>. You must replace any plugins by extracting them to gems and adding them to your <code>Gemfile</code>. If you choose not to make them gems, you can move them into, say, <code>lib/my_plugin/*</code> and add an appropriate initializer in <code>config/initializers/my_plugin.rb</code>.</p><h3 id="upgrading-from-rails-3-2-to-rails-4-0-active-record"><a class="anchorlink" href="#upgrading-from-rails-3-2-to-rails-4-0-active-record" data-turbo="false"><span>13.4</span> Active Record</a></h3> <ul> <li><p>Rails 4.0 has removed the identity map from Active Record, due to <a href="https://github.com/rails/rails/commit/302c912bf6bcd0fa200d964ec2dc4a44abe328a6">some inconsistencies with associations</a>. If you have manually enabled it in your application, you will have to remove the following config that has no effect anymore: <code>config.active_record.identity_map</code>.</p></li> <li><p>The <code>delete</code> method in collection associations can now receive <code>Integer</code> or <code>String</code> arguments as record ids, besides records, pretty much like the <code>destroy</code> method does. Previously it raised <code>ActiveRecord::AssociationTypeMismatch</code> for such arguments. From Rails 4.0 on <code>delete</code> automatically tries to find the records matching the given ids before deleting them.</p></li> <li><p>In Rails 4.0 when a column or a table is renamed the related indexes are also renamed. If you have migrations which rename the indexes, they are no longer needed.</p></li> <li><p>Rails 4.0 has changed <code>serialized_attributes</code> and <code>attr_readonly</code> to class methods only. You shouldn't use instance methods since it's now deprecated. You should change them to use class methods, e.g. <code>self.serialized_attributes</code> to <code>self.class.serialized_attributes</code>.</p></li> <li><p>When using the default coder, assigning <code>nil</code> to a serialized attribute will save it to the database as <code>NULL</code> instead of passing the <code>nil</code> value through YAML (<code>"--- \n...\n"</code>).</p></li> <li><p>Rails 4.0 has removed <code>attr_accessible</code> and <code>attr_protected</code> feature in favor of Strong Parameters. You can use the <a href="https://github.com/rails/protected_attributes">Protected Attributes gem</a> for a smooth upgrade path.</p></li> <li><p>If you are not using Protected Attributes, you can remove any options related to this gem such as <code>whitelist_attributes</code> or <code>mass_assignment_sanitizer</code> options.</p></li> <li><p>Rails 4.0 requires that scopes use a callable object such as a Proc or lambda:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">scope</span> <span class="ss">:active</span><span class="p">,</span> <span class="n">where</span><span class="p">(</span><span class="ss">active: </span><span class="kp">true</span><span class="p">)</span> <span class="c1"># becomes</span> <span class="n">scope</span> <span class="ss">:active</span><span class="p">,</span> <span class="o">-&gt;</span> <span class="p">{</span> <span class="n">where</span> <span class="ss">active: </span><span class="kp">true</span> <span class="p">}</span> </code></pre> <button class="clipboard-button" data-clipboard-text="scope :active, where(active: true) # becomes scope :active, -> { where active: true } ">Copy</button> </div></li> <li><p>Rails 4.0 has deprecated <code>ActiveRecord::Fixtures</code> in favor of <code>ActiveRecord::FixtureSet</code>.</p></li> <li><p>Rails 4.0 has deprecated <code>ActiveRecord::TestCase</code> in favor of <code>ActiveSupport::TestCase</code>.</p></li> <li><p>Rails 4.0 has deprecated the old-style hash-based finder API. This means that methods which previously accepted "finder options" no longer do. For example, <code>Book.find(:all, conditions: { name: '1984' })</code> has been deprecated in favor of <code>Book.where(name: '1984')</code></p></li> <li><p>All dynamic methods except for <code>find_by_...</code> and <code>find_by_...!</code> are deprecated. Here's how you can handle the changes:</p> <ul> <li><code>find_all_by_...</code> becomes <code>where(...)</code>.</li> <li><code>find_last_by_...</code> becomes <code>where(...).last</code>.</li> <li><code>scoped_by_...</code> becomes <code>where(...)</code>.</li> <li><code>find_or_initialize_by_...</code> becomes <code>find_or_initialize_by(...)</code>.</li> <li><code>find_or_create_by_...</code> becomes <code>find_or_create_by(...)</code>.</li> </ul></li> <li><p>Note that <code>where(...)</code> returns a relation, not an array like the old finders. If you require an <code>Array</code>, use <code>where(...).to_a</code>.</p></li> <li><p>These equivalent methods may not execute the same SQL as the previous implementation.</p></li> <li><p>To re-enable the old finders, you can use the <a href="https://github.com/rails/activerecord-deprecated_finders">activerecord-deprecated_finders gem</a>.</p></li> <li><p>Rails 4.0 has changed to default join table for <code>has_and_belongs_to_many</code> relations to strip the common prefix off the second table name. Any existing <code>has_and_belongs_to_many</code> relationship between models with a common prefix must be specified with the <code>join_table</code> option. For example:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">CatalogCategory</span> <span class="o">&lt;</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Base</span> <span class="n">has_and_belongs_to_many</span> <span class="ss">:catalog_products</span><span class="p">,</span> <span class="ss">join_table: </span><span class="s2">"catalog_categories_catalog_products"</span> <span class="k">end</span> <span class="k">class</span> <span class="nc">CatalogProduct</span> <span class="o">&lt;</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Base</span> <span class="n">has_and_belongs_to_many</span> <span class="ss">:catalog_categories</span><span class="p">,</span> <span class="ss">join_table: </span><span class="s2">"catalog_categories_catalog_products"</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class CatalogCategory < ActiveRecord::Base has_and_belongs_to_many :catalog_products, join_table: &quot;catalog_categories_catalog_products&quot; end class CatalogProduct < ActiveRecord::Base has_and_belongs_to_many :catalog_categories, join_table: &quot;catalog_categories_catalog_products&quot; end ">Copy</button> </div></li> <li><p>Note that the prefix takes scopes into account as well, so relations between <code>Catalog::Category</code> and <code>Catalog::Product</code> or <code>Catalog::Category</code> and <code>CatalogProduct</code> need to be updated similarly.</p></li> </ul> <h3 id="active-resource"><a class="anchorlink" href="#active-resource" data-turbo="false"><span>13.5</span> Active Resource</a></h3><p>Rails 4.0 extracted Active Resource to its own gem. If you still need the feature you can add the <a href="https://github.com/rails/activeresource">Active Resource gem</a> in your <code>Gemfile</code>.</p><h3 id="active-model"><a class="anchorlink" href="#active-model" data-turbo="false"><span>13.6</span> Active Model</a></h3> <ul> <li><p>Rails 4.0 has changed how errors attach with the <code>ActiveModel::Validations::ConfirmationValidator</code>. Now when confirmation validations fail, the error will be attached to <code>:#{attribute}_confirmation</code> instead of <code>attribute</code>.</p></li> <li><p>Rails 4.0 has changed <code>ActiveModel::Serializers::JSON.include_root_in_json</code> default value to <code>false</code>. Now, Active Model Serializers and Active Record objects have the same default behavior. This means that you can comment or remove the following option in the <code>config/initializers/wrap_parameters.rb</code> file:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># Disable root element in JSON by default.</span> <span class="c1"># ActiveSupport.on_load(:active_record) do</span> <span class="c1"># self.include_root_in_json = false</span> <span class="c1"># end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="# Disable root element in JSON by default. # ActiveSupport.on_load(:active_record) do # self.include_root_in_json = false # end ">Copy</button> </div></li> </ul> <h3 id="action-pack"><a class="anchorlink" href="#action-pack" data-turbo="false"><span>13.7</span> Action Pack</a></h3> <ul> <li><p>Rails 4.0 introduces <code>ActiveSupport::KeyGenerator</code> and uses this as a base from which to generate and verify signed cookies (among other things). Existing signed cookies generated with Rails 3.x will be transparently upgraded if you leave your existing <code>secret_token</code> in place and add the new <code>secret_key_base</code>.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># config/initializers/secret_token.rb</span> <span class="no">Myapp</span><span class="o">::</span><span class="no">Application</span><span class="p">.</span><span class="nf">config</span><span class="p">.</span><span class="nf">secret_token</span> <span class="o">=</span> <span class="s2">"existing secret token"</span> <span class="no">Myapp</span><span class="o">::</span><span class="no">Application</span><span class="p">.</span><span class="nf">config</span><span class="p">.</span><span class="nf">secret_key_base</span> <span class="o">=</span> <span class="s2">"new secret key base"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="Myapp::Application.config.secret_token = &quot;existing secret token&quot; Myapp::Application.config.secret_key_base = &quot;new secret key base&quot; ">Copy</button> </div> <p>Please note that you should wait to set <code>secret_key_base</code> until you have 100% of your userbase on Rails 4.x and are reasonably sure you will not need to rollback to Rails 3.x. This is because cookies signed based on the new <code>secret_key_base</code> in Rails 4.x are not backwards compatible with Rails 3.x. You are free to leave your existing <code>secret_token</code> in place, not set the new <code>secret_key_base</code>, and ignore the deprecation warnings until you are reasonably sure that your upgrade is otherwise complete.</p><p>If you are relying on the ability for external applications or JavaScript to be able to read your Rails app's signed session cookies (or signed cookies in general) you should not set <code>secret_key_base</code> until you have decoupled these concerns.</p></li> <li><p>Rails 4.0 encrypts the contents of cookie-based sessions if <code>secret_key_base</code> has been set. Rails 3.x signed, but did not encrypt, the contents of cookie-based session. Signed cookies are "secure" in that they are verified to have been generated by your app and are tamper-proof. However, the contents can be viewed by end users, and encrypting the contents eliminates this caveat/concern without a significant performance penalty.</p><p>Please read <a href="https://github.com/rails/rails/pull/9978">Pull Request #9978</a> for details on the move to encrypted session cookies.</p></li> <li><p>Rails 4.0 removed the <code>ActionController::Base.asset_path</code> option. Use the assets pipeline feature.</p></li> <li><p>Rails 4.0 has deprecated <code>ActionController::Base.page_cache_extension</code> option. Use <code>ActionController::Base.default_static_extension</code> instead.</p></li> <li><p>Rails 4.0 has removed Action and Page caching from Action Pack. You will need to add the <code>actionpack-action_caching</code> gem in order to use <code>caches_action</code> and the <code>actionpack-page_caching</code> to use <code>caches_page</code> in your controllers.</p></li> <li><p>Rails 4.0 has removed the XML parameters parser. You will need to add the <code>actionpack-xml_parser</code> gem if you require this feature.</p></li> <li><p>Rails 4.0 changes the default <code>layout</code> lookup set using symbols or procs that return nil. To get the "no layout" behavior, return false instead of nil.</p></li> <li><p>Rails 4.0 changes the default memcached client from <code>memcache-client</code> to <code>dalli</code>. To upgrade, simply add <code>gem "dalli"</code> to your <code>Gemfile</code>.</p></li> <li><p>Rails 4.0 deprecates the <code>dom_id</code> and <code>dom_class</code> methods in controllers (they are fine in views). You will need to include the <code>ActionView::RecordIdentifier</code> module in controllers requiring this feature.</p></li> <li><p>Rails 4.0 deprecates the <code>:confirm</code> option for the <code>link_to</code> helper. You should instead rely on a data attribute (e.g. <code>data: { confirm: 'Are you sure?' }</code>). This deprecation also concerns the helpers based on this one (such as <code>link_to_if</code> or <code>link_to_unless</code>).</p></li> <li><p>Rails 4.0 changed how <code>assert_generates</code>, <code>assert_recognizes</code>, and <code>assert_routing</code> work. Now all these assertions raise <code>Assertion</code> instead of <code>ActionController::RoutingError</code>.</p></li> <li><p>Rails 4.0 raises an <code>ArgumentError</code> if clashing named routes are defined. This can be triggered by explicitly defined named routes or by the <code>resources</code> method. Here are two examples that clash with routes named <code>example_path</code>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">get</span> <span class="s2">"one"</span> <span class="o">=&gt;</span> <span class="s2">"test#example"</span><span class="p">,</span> <span class="ss">as: :example</span> <span class="n">get</span> <span class="s2">"two"</span> <span class="o">=&gt;</span> <span class="s2">"test#example"</span><span class="p">,</span> <span class="ss">as: :example</span> </code></pre> <button class="clipboard-button" data-clipboard-text="get &quot;one&quot; => &quot;test#example&quot;, as: :example get &quot;two&quot; => &quot;test#example&quot;, as: :example ">Copy</button> </div> <div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">resources</span> <span class="ss">:examples</span> <span class="n">get</span> <span class="s2">"clashing/:id"</span> <span class="o">=&gt;</span> <span class="s2">"test#example"</span><span class="p">,</span> <span class="ss">as: :example</span> </code></pre> <button class="clipboard-button" data-clipboard-text="resources :examples get &quot;clashing/:id&quot; => &quot;test#example&quot;, as: :example ">Copy</button> </div> <p>In the first case, you can simply avoid using the same name for multiple routes. In the second, you can use the <code>only</code> or <code>except</code> options provided by the <code>resources</code> method to restrict the routes created as detailed in the <a href="routing.html#restricting-the-routes-created">Routing Guide</a>.</p></li> <li><p>Rails 4.0 also changed the way unicode character routes are drawn. Now you can draw unicode character routes directly. If you already draw such routes, you must change them, for example:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">get</span> <span class="no">Rack</span><span class="o">::</span><span class="no">Utils</span><span class="p">.</span><span class="nf">escape</span><span class="p">(</span><span class="s2">"こんにちは"</span><span class="p">),</span> <span class="ss">controller: </span><span class="s2">"welcome"</span><span class="p">,</span> <span class="ss">action: </span><span class="s2">"index"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="get Rack::Utils.escape(&quot;こんにちは&quot;), controller: &quot;welcome&quot;, action: &quot;index&quot; ">Copy</button> </div> <p>becomes</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">get</span> <span class="s2">"こんにちは"</span><span class="p">,</span> <span class="ss">controller: </span><span class="s2">"welcome"</span><span class="p">,</span> <span class="ss">action: </span><span class="s2">"index"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="get &quot;こんにちは&quot;, controller: &quot;welcome&quot;, action: &quot;index&quot; ">Copy</button> </div></li> <li><p>Rails 4.0 requires that routes using <code>match</code> must specify the request method. For example:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># Rails 3.x</span> <span class="n">match</span> <span class="s2">"/"</span> <span class="o">=&gt;</span> <span class="s2">"root#index"</span> <span class="c1"># becomes</span> <span class="n">match</span> <span class="s2">"/"</span> <span class="o">=&gt;</span> <span class="s2">"root#index"</span><span class="p">,</span> <span class="ss">via: :get</span> <span class="c1"># or</span> <span class="n">get</span> <span class="s2">"/"</span> <span class="o">=&gt;</span> <span class="s2">"root#index"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="# Rails 3.x match &quot;/&quot; => &quot;root#index&quot; # becomes match &quot;/&quot; => &quot;root#index&quot;, via: :get # or get &quot;/&quot; => &quot;root#index&quot; ">Copy</button> </div></li> <li><p>Rails 4.0 has removed <code>ActionDispatch::BestStandardsSupport</code> middleware, <code>&lt;!DOCTYPE html&gt;</code> already triggers standards mode per <a href="https://msdn.microsoft.com/en-us/library/jj676915(v=vs.85).aspx">https://msdn.microsoft.com/en-us/library/jj676915(v=vs.85).aspx</a> and ChromeFrame header has been moved to <code>config.action_dispatch.default_headers</code>.</p><p>Remember you must also remove any references to the middleware from your application code, for example:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># Raise exception</span> <span class="n">config</span><span class="p">.</span><span class="nf">middleware</span><span class="p">.</span><span class="nf">insert_before</span><span class="p">(</span><span class="no">Rack</span><span class="o">::</span><span class="no">Lock</span><span class="p">,</span> <span class="no">ActionDispatch</span><span class="o">::</span><span class="no">BestStandardsSupport</span><span class="p">)</span> </code></pre> <button class="clipboard-button" data-clipboard-text="# Raise exception config.middleware.insert_before(Rack::Lock, ActionDispatch::BestStandardsSupport) ">Copy</button> </div> <p>Also check your environment settings for <code>config.action_dispatch.best_standards_support</code> and remove it if present.</p></li> <li><p>Rails 4.0 allows configuration of HTTP headers by setting <code>config.action_dispatch.default_headers</code>. The defaults are as follows:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">config</span><span class="p">.</span><span class="nf">action_dispatch</span><span class="p">.</span><span class="nf">default_headers</span> <span class="o">=</span> <span class="p">{</span> <span class="s2">"X-Frame-Options"</span> <span class="o">=&gt;</span> <span class="s2">"SAMEORIGIN"</span><span class="p">,</span> <span class="s2">"X-XSS-Protection"</span> <span class="o">=&gt;</span> <span class="s2">"1; mode=block"</span> <span class="p">}</span> </code></pre> <button class="clipboard-button" data-clipboard-text="config.action_dispatch.default_headers = { &quot;X-Frame-Options&quot; => &quot;SAMEORIGIN&quot;, &quot;X-XSS-Protection&quot; => &quot;1; mode=block&quot; } ">Copy</button> </div> <p>Please note that if your application is dependent on loading certain pages in a <code>&lt;frame&gt;</code> or <code>&lt;iframe&gt;</code>, then you may need to explicitly set <code>X-Frame-Options</code> to <code>ALLOW-FROM ...</code> or <code>ALLOWALL</code>.</p></li> <li><p>In Rails 4.0, precompiling assets no longer automatically copies non-JS/CSS assets from <code>vendor/assets</code> and <code>lib/assets</code>. Rails application and engine developers should put these assets in <code>app/assets</code> or configure <a href="configuring.html#config-assets-precompile"><code>config.assets.precompile</code></a>.</p></li> <li><p>In Rails 4.0, <code>ActionController::UnknownFormat</code> is raised when the action doesn't handle the request format. By default, the exception is handled by responding with 406 Not Acceptable, but you can override that now. In Rails 3, 406 Not Acceptable was always returned. No overrides.</p></li> <li><p>In Rails 4.0, a generic <code>ActionDispatch::ParamsParser::ParseError</code> exception is raised when <code>ParamsParser</code> fails to parse request params. You will want to rescue this exception instead of the low-level <code>MultiJson::DecodeError</code>, for example.</p></li> <li><p>In Rails 4.0, <code>SCRIPT_NAME</code> is properly nested when engines are mounted on an app that's served from a URL prefix. You no longer have to set <code>default_url_options[:script_name]</code> to work around overwritten URL prefixes.</p></li> <li><p>Rails 4.0 deprecated <code>ActionController::Integration</code> in favor of <code>ActionDispatch::Integration</code>.</p></li> <li><p>Rails 4.0 deprecated <code>ActionController::IntegrationTest</code> in favor of <code>ActionDispatch::IntegrationTest</code>.</p></li> <li><p>Rails 4.0 deprecated <code>ActionController::PerformanceTest</code> in favor of <code>ActionDispatch::PerformanceTest</code>.</p></li> <li><p>Rails 4.0 deprecated <code>ActionController::AbstractRequest</code> in favor of <code>ActionDispatch::Request</code>.</p></li> <li><p>Rails 4.0 deprecated <code>ActionController::Request</code> in favor of <code>ActionDispatch::Request</code>.</p></li> <li><p>Rails 4.0 deprecated <code>ActionController::AbstractResponse</code> in favor of <code>ActionDispatch::Response</code>.</p></li> <li><p>Rails 4.0 deprecated <code>ActionController::Response</code> in favor of <code>ActionDispatch::Response</code>.</p></li> <li><p>Rails 4.0 deprecated <code>ActionController::Routing</code> in favor of <code>ActionDispatch::Routing</code>.</p></li> </ul> <h3 id="active-support"><a class="anchorlink" href="#active-support" data-turbo="false"><span>13.8</span> Active Support</a></h3><p>Rails 4.0 removes the <code>j</code> alias for <code>ERB::Util#json_escape</code> since <code>j</code> is already used for <code>ActionView::Helpers::JavaScriptHelper#escape_javascript</code>.</p><h4 id="cache"><a class="anchorlink" href="#cache" data-turbo="false"><span>13.8.1</span> Cache</a></h4><p>The caching method changed between Rails 3.x and 4.0. You should <a href="https://guides.rubyonrails.org/v4.0/caching_with_rails.html#activesupport-cache-store">change the cache namespace</a> and roll out with a cold cache.</p><h3 id="helpers-loading-order"><a class="anchorlink" href="#helpers-loading-order" data-turbo="false"><span>13.9</span> Helpers Loading Order</a></h3><p>The order in which helpers from more than one directory are loaded has changed in Rails 4.0. Previously, they were gathered and then sorted alphabetically. After upgrading to Rails 4.0, helpers will preserve the order of loaded directories and will be sorted alphabetically only within each directory. Unless you explicitly use the <code>helpers_path</code> parameter, this change will only impact the way of loading helpers from engines. If you rely on the ordering, you should check if correct methods are available after upgrade. If you would like to change the order in which engines are loaded, you can use <code>config.railties_order=</code> method.</p><h3 id="active-record-observer-and-action-controller-sweeper"><a class="anchorlink" href="#active-record-observer-and-action-controller-sweeper" data-turbo="false"><span>13.10</span> Active Record Observer and Action Controller Sweeper</a></h3><p><code>ActiveRecord::Observer</code> and <code>ActionController::Caching::Sweeper</code> have been extracted to the <code>rails-observers</code> gem. You will need to add the <code>rails-observers</code> gem if you require these features.</p><h3 id="sprockets-rails"><a class="anchorlink" href="#sprockets-rails" data-turbo="false"><span>13.11</span> sprockets-rails</a></h3> <ul> <li><code>assets:precompile:primary</code> and <code>assets:precompile:all</code> have been removed. Use <code>assets:precompile</code> instead.</li> <li><p>The <code>config.assets.compress</code> option should be changed to <a href="configuring.html#config-assets-js-compressor"><code>config.assets.js_compressor</code></a> like so for instance:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">config</span><span class="p">.</span><span class="nf">assets</span><span class="p">.</span><span class="nf">js_compressor</span> <span class="o">=</span> <span class="ss">:uglifier</span> </code></pre> <button class="clipboard-button" data-clipboard-text="config.assets.js_compressor = :uglifier ">Copy</button> </div></li> </ul> <h3 id="sass-rails"><a class="anchorlink" href="#sass-rails" data-turbo="false"><span>13.12</span> sass-rails</a></h3> <ul> <li><code>asset-url</code> with two arguments is deprecated. For example: <code>asset-url("rails.png", image)</code> becomes <code>asset-url("rails.png")</code>.</li> </ul> <h2 id="upgrading-from-rails-3-1-to-rails-3-2"><a class="anchorlink" href="#upgrading-from-rails-3-1-to-rails-3-2" data-turbo="false"><span>14</span> Upgrading from Rails 3.1 to Rails 3.2</a></h2><p>If your application is currently on any version of Rails older than 3.1.x, you should upgrade to Rails 3.1 before attempting an update to Rails 3.2.</p><p>The following changes are meant for upgrading your application to the latest 3.2.x version of Rails.</p><h3 id="upgrading-from-rails-3-1-to-rails-3-2-gemfile"><a class="anchorlink" href="#upgrading-from-rails-3-1-to-rails-3-2-gemfile" data-turbo="false"><span>14.1</span> Gemfile</a></h3><p>Make the following changes to your <code>Gemfile</code>.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">gem</span> <span class="s2">"rails"</span><span class="p">,</span> <span class="s2">"3.2.21"</span> <span class="n">group</span> <span class="ss">:assets</span> <span class="k">do</span> <span class="n">gem</span> <span class="s2">"sass-rails"</span><span class="p">,</span> <span class="s2">"~&gt; 3.2.6"</span> <span class="n">gem</span> <span class="s2">"coffee-rails"</span><span class="p">,</span> <span class="s2">"~&gt; 3.2.2"</span> <span class="n">gem</span> <span class="s2">"uglifier"</span><span class="p">,</span> <span class="s2">"&gt;= 1.0.3"</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="gem &quot;rails&quot;, &quot;3.2.21&quot; group :assets do gem &quot;sass-rails&quot;, &quot;~> 3.2.6&quot; gem &quot;coffee-rails&quot;, &quot;~> 3.2.2&quot; gem &quot;uglifier&quot;, &quot;>= 1.0.3&quot; end ">Copy</button> </div> <h3 id="upgrading-from-rails-3-1-to-rails-3-2-config-environments-development-rb"><a class="anchorlink" href="#upgrading-from-rails-3-1-to-rails-3-2-config-environments-development-rb" data-turbo="false"><span>14.2</span> config/environments/development.rb</a></h3><p>There are a couple of new configuration settings that you should add to your development environment:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># Raise exception on mass assignment protection for Active Record models</span> <span class="n">config</span><span class="p">.</span><span class="nf">active_record</span><span class="p">.</span><span class="nf">mass_assignment_sanitizer</span> <span class="o">=</span> <span class="ss">:strict</span> <span class="c1"># Log the query plan for queries taking more than this (works</span> <span class="c1"># with SQLite, MySQL, and PostgreSQL)</span> <span class="n">config</span><span class="p">.</span><span class="nf">active_record</span><span class="p">.</span><span class="nf">auto_explain_threshold_in_seconds</span> <span class="o">=</span> <span class="mf">0.5</span> </code></pre> <button class="clipboard-button" data-clipboard-text="# Raise exception on mass assignment protection for Active Record models config.active_record.mass_assignment_sanitizer = :strict # Log the query plan for queries taking more than this (works # with SQLite, MySQL, and PostgreSQL) config.active_record.auto_explain_threshold_in_seconds = 0.5 ">Copy</button> </div> <h3 id="upgrading-from-rails-3-1-to-rails-3-2-config-environments-test-rb"><a class="anchorlink" href="#upgrading-from-rails-3-1-to-rails-3-2-config-environments-test-rb" data-turbo="false"><span>14.3</span> config/environments/test.rb</a></h3><p>The <code>mass_assignment_sanitizer</code> configuration setting should also be added to <code>config/environments/test.rb</code>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># Raise exception on mass assignment protection for Active Record models</span> <span class="n">config</span><span class="p">.</span><span class="nf">active_record</span><span class="p">.</span><span class="nf">mass_assignment_sanitizer</span> <span class="o">=</span> <span class="ss">:strict</span> </code></pre> <button class="clipboard-button" data-clipboard-text="# Raise exception on mass assignment protection for Active Record models config.active_record.mass_assignment_sanitizer = :strict ">Copy</button> </div> <h3 id="upgrading-from-rails-3-1-to-rails-3-2-vendor-plugins"><a class="anchorlink" href="#upgrading-from-rails-3-1-to-rails-3-2-vendor-plugins" data-turbo="false"><span>14.4</span> vendor/plugins</a></h3><p>Rails 3.2 deprecates <code>vendor/plugins</code> and Rails 4.0 will remove them completely. While it's not strictly necessary as part of a Rails 3.2 upgrade, you can start replacing any plugins by extracting them to gems and adding them to your <code>Gemfile</code>. If you choose not to make them gems, you can move them into, say, <code>lib/my_plugin/*</code> and add an appropriate initializer in <code>config/initializers/my_plugin.rb</code>.</p><h3 id="upgrading-from-rails-3-1-to-rails-3-2-active-record"><a class="anchorlink" href="#upgrading-from-rails-3-1-to-rails-3-2-active-record" data-turbo="false"><span>14.5</span> Active Record</a></h3><p>Option <code>:dependent =&gt; :restrict</code> has been removed from <code>belongs_to</code>. If you want to prevent deleting the object if there are any associated objects, you can set <code>:dependent =&gt; :destroy</code> and return <code>false</code> after checking for existence of association from any of the associated object's destroy callbacks.</p><h2 id="upgrading-from-rails-3-0-to-rails-3-1"><a class="anchorlink" href="#upgrading-from-rails-3-0-to-rails-3-1" data-turbo="false"><span>15</span> Upgrading from Rails 3.0 to Rails 3.1</a></h2><p>If your application is currently on any version of Rails older than 3.0.x, you should upgrade to Rails 3.0 before attempting an update to Rails 3.1.</p><p>The following changes are meant for upgrading your application to Rails 3.1.12, the last 3.1.x version of Rails.</p><h3 id="gemfile"><a class="anchorlink" href="#gemfile" data-turbo="false"><span>15.1</span> Gemfile</a></h3><p>Make the following changes to your <code>Gemfile</code>.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">gem</span> <span class="s2">"rails"</span><span class="p">,</span> <span class="s2">"3.1.12"</span> <span class="n">gem</span> <span class="s2">"mysql2"</span> <span class="c1"># Needed for the new asset pipeline</span> <span class="n">group</span> <span class="ss">:assets</span> <span class="k">do</span> <span class="n">gem</span> <span class="s2">"sass-rails"</span><span class="p">,</span> <span class="s2">"~&gt; 3.1.7"</span> <span class="n">gem</span> <span class="s2">"coffee-rails"</span><span class="p">,</span> <span class="s2">"~&gt; 3.1.1"</span> <span class="n">gem</span> <span class="s2">"uglifier"</span><span class="p">,</span> <span class="s2">"&gt;= 1.0.3"</span> <span class="k">end</span> <span class="c1"># jQuery is the default JavaScript library in Rails 3.1</span> <span class="n">gem</span> <span class="s2">"jquery-rails"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="gem &quot;rails&quot;, &quot;3.1.12&quot; gem &quot;mysql2&quot; # Needed for the new asset pipeline group :assets do gem &quot;sass-rails&quot;, &quot;~> 3.1.7&quot; gem &quot;coffee-rails&quot;, &quot;~> 3.1.1&quot; gem &quot;uglifier&quot;, &quot;>= 1.0.3&quot; end # jQuery is the default JavaScript library in Rails 3.1 gem &quot;jquery-rails&quot; ">Copy</button> </div> <h3 id="config-application-rb"><a class="anchorlink" href="#config-application-rb" data-turbo="false"><span>15.2</span> config/application.rb</a></h3><p>The asset pipeline requires the following additions:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">config</span><span class="p">.</span><span class="nf">assets</span><span class="p">.</span><span class="nf">enabled</span> <span class="o">=</span> <span class="kp">true</span> <span class="n">config</span><span class="p">.</span><span class="nf">assets</span><span class="p">.</span><span class="nf">version</span> <span class="o">=</span> <span class="s2">"1.0"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="config.assets.enabled = true config.assets.version = &quot;1.0&quot; ">Copy</button> </div> <p>If your application is using an "/assets" route for a resource you may want to change the prefix used for assets to avoid conflicts:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># Defaults to '/assets'</span> <span class="n">config</span><span class="p">.</span><span class="nf">assets</span><span class="p">.</span><span class="nf">prefix</span> <span class="o">=</span> <span class="s2">"/asset-files"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="# Defaults to '/assets' config.assets.prefix = &quot;/asset-files&quot; ">Copy</button> </div> <h3 id="upgrading-from-rails-3-0-to-rails-3-1-config-environments-development-rb"><a class="anchorlink" href="#upgrading-from-rails-3-0-to-rails-3-1-config-environments-development-rb" data-turbo="false"><span>15.3</span> config/environments/development.rb</a></h3><p>Remove the RJS setting <code>config.action_view.debug_rjs = true</code>.</p><p>Add these settings if you enable the asset pipeline:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># Do not compress assets</span> <span class="n">config</span><span class="p">.</span><span class="nf">assets</span><span class="p">.</span><span class="nf">compress</span> <span class="o">=</span> <span class="kp">false</span> <span class="c1"># Expands the lines which load the assets</span> <span class="n">config</span><span class="p">.</span><span class="nf">assets</span><span class="p">.</span><span class="nf">debug</span> <span class="o">=</span> <span class="kp">true</span> </code></pre> <button class="clipboard-button" data-clipboard-text="# Do not compress assets config.assets.compress = false # Expands the lines which load the assets config.assets.debug = true ">Copy</button> </div> <h3 id="config-environments-production-rb"><a class="anchorlink" href="#config-environments-production-rb" data-turbo="false"><span>15.4</span> config/environments/production.rb</a></h3><p>Again, most of the changes below are for the asset pipeline. You can read more about these in the <a href="asset_pipeline.html">Asset Pipeline</a> guide.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># Compress JavaScripts and CSS</span> <span class="n">config</span><span class="p">.</span><span class="nf">assets</span><span class="p">.</span><span class="nf">compress</span> <span class="o">=</span> <span class="kp">true</span> <span class="c1"># Don't fallback to assets pipeline if a precompiled asset is missed</span> <span class="n">config</span><span class="p">.</span><span class="nf">assets</span><span class="p">.</span><span class="nf">compile</span> <span class="o">=</span> <span class="kp">false</span> <span class="c1"># Generate digests for assets URLs</span> <span class="n">config</span><span class="p">.</span><span class="nf">assets</span><span class="p">.</span><span class="nf">digest</span> <span class="o">=</span> <span class="kp">true</span> <span class="c1"># Defaults to Rails.root.join("public/assets")</span> <span class="c1"># config.assets.manifest = YOUR_PATH</span> <span class="c1"># Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)</span> <span class="c1"># config.assets.precompile += %w( admin.js admin.css )</span> <span class="c1"># Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.</span> <span class="c1"># config.force_ssl = true</span> </code></pre> <button class="clipboard-button" data-clipboard-text="# Compress JavaScripts and CSS config.assets.compress = true # Don't fallback to assets pipeline if a precompiled asset is missed config.assets.compile = false # Generate digests for assets URLs config.assets.digest = true # Defaults to Rails.root.join(&quot;public/assets&quot;) # config.assets.manifest = YOUR_PATH # Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added) # config.assets.precompile += %w( admin.js admin.css ) # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true ">Copy</button> </div> <h3 id="upgrading-from-rails-3-0-to-rails-3-1-config-environments-test-rb"><a class="anchorlink" href="#upgrading-from-rails-3-0-to-rails-3-1-config-environments-test-rb" data-turbo="false"><span>15.5</span> config/environments/test.rb</a></h3><p>You can help test performance with these additions to your test environment:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># Configure static asset server for tests with Cache-Control for performance</span> <span class="n">config</span><span class="p">.</span><span class="nf">public_file_server</span><span class="p">.</span><span class="nf">enabled</span> <span class="o">=</span> <span class="kp">true</span> <span class="n">config</span><span class="p">.</span><span class="nf">public_file_server</span><span class="p">.</span><span class="nf">headers</span> <span class="o">=</span> <span class="p">{</span> <span class="s2">"Cache-Control"</span> <span class="o">=&gt;</span> <span class="s2">"public, max-age=3600"</span> <span class="p">}</span> </code></pre> <button class="clipboard-button" data-clipboard-text="# Configure static asset server for tests with Cache-Control for performance config.public_file_server.enabled = true config.public_file_server.headers = { &quot;Cache-Control&quot; => &quot;public, max-age=3600&quot; } ">Copy</button> </div> <h3 id="config-initializers-wrap-parameters-rb"><a class="anchorlink" href="#config-initializers-wrap-parameters-rb" data-turbo="false"><span>15.6</span> config/initializers/wrap_parameters.rb</a></h3><p>Add this file with the following contents, if you wish to wrap parameters into a nested hash. This is on by default in new applications.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># Be sure to restart your server when you modify this file.</span> <span class="c1"># This file contains settings for ActionController::ParamsWrapper which</span> <span class="c1"># is enabled by default.</span> <span class="c1"># Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array.</span> <span class="no">ActiveSupport</span><span class="p">.</span><span class="nf">on_load</span><span class="p">(</span><span class="ss">:action_controller</span><span class="p">)</span> <span class="k">do</span> <span class="n">wrap_parameters</span> <span class="ss">format: </span><span class="p">[</span><span class="ss">:json</span><span class="p">]</span> <span class="k">end</span> <span class="c1"># Disable root element in JSON by default.</span> <span class="no">ActiveSupport</span><span class="p">.</span><span class="nf">on_load</span><span class="p">(</span><span class="ss">:active_record</span><span class="p">)</span> <span class="k">do</span> <span class="nb">self</span><span class="p">.</span><span class="nf">include_root_in_json</span> <span class="o">=</span> <span class="kp">false</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="# Be sure to restart your server when you modify this file. # This file contains settings for ActionController::ParamsWrapper which # is enabled by default. # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. ActiveSupport.on_load(:action_controller) do wrap_parameters format: [:json] end # Disable root element in JSON by default. ActiveSupport.on_load(:active_record) do self.include_root_in_json = false end ">Copy</button> </div> <h3 id="config-initializers-session-store-rb"><a class="anchorlink" href="#config-initializers-session-store-rb" data-turbo="false"><span>15.7</span> config/initializers/session_store.rb</a></h3><p>You need to change your session key to something new, or remove all sessions:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># in config/initializers/session_store.rb</span> <span class="no">AppName</span><span class="o">::</span><span class="no">Application</span><span class="p">.</span><span class="nf">config</span><span class="p">.</span><span class="nf">session_store</span> <span class="ss">:cookie_store</span><span class="p">,</span> <span class="ss">key: </span><span class="s2">"SOMETHINGNEW"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="# in config/initializers/session_store.rb AppName::Application.config.session_store :cookie_store, key: &quot;SOMETHINGNEW&quot; ">Copy</button> </div> <p>or</p><div class="interstitial code"> <pre><code class="highlight console"><span class="gp">$</span><span class="w"> </span>bin/rake db:sessions:clear </code></pre> <button class="clipboard-button" data-clipboard-text="bin/rake db:sessions:clear ">Copy</button> </div> <h3 id="remove-cache-and-concat-options-in-asset-helpers-references-in-views"><a class="anchorlink" href="#remove-cache-and-concat-options-in-asset-helpers-references-in-views" data-turbo="false"><span>15.8</span> Remove :cache and :concat options in asset helpers references in views</a></h3> <ul> <li>With the Asset Pipeline the :cache and :concat options aren't used anymore, delete these options from your views.</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