**DO NOT READ THIS FILE ON GITHUB, GUIDES ARE PUBLISHED ON http://guides.rubyonrails.org.** A Guide for Upgrading Ruby on Rails =================================== 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. -------------------------------------------------------------------------------- General Advice -------------- 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. ### Test Coverage 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 _before_ you start an upgrade. ### The Upgrade Process 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. The process should go as follows: 1. Write tests and make sure they pass. 2. Move to the latest patch version after your current version. 3. Fix tests and deprecated features. 4. Move to the latest patch version of the next minor version. Repeat this process until you reach your target Rails version. Each time you move versions, you will need to change the Rails version number in the Gemfile (and possibly other gem versions) and run `bundle update`. Then run the Update task mentioned below to update configuration files, then run your tests. You can find a list of all released Rails versions [here](https://rubygems.org/gems/rails/versions). ### Ruby Versions Rails generally stays close to the latest released Ruby version when it's released: * Rails 5 requires Ruby 2.2.2 or newer. * Rails 4 prefers Ruby 2.0 and requires 1.9.3 or newer. * Rails 3.2.x is the last branch to support Ruby 1.8.7. * Rails 3 and above require Ruby 1.8.7 or higher. Support for all of the previous Ruby versions has been dropped officially. You should upgrade as early as possible. TIP: Ruby 1.8.7 p248 and p249 have marshaling bugs that crash Rails. Ruby Enterprise Edition has these fixed since the release of 1.8.7-2010.02. On the 1.9 front, Ruby 1.9.1 is not usable because it outright segfaults, so if you want to use 1.9.x, jump straight to 1.9.3 for smooth sailing. ### The Update Task Rails provides the `app:update` task (`rails:update` on 4.2 and earlier). After updating the Rails version in the Gemfile, run this task. This will help you with the creation of new files and changes of old files in an interactive session. ```bash $ rails app:update identical config/boot.rb exist config conflict config/routes.rb Overwrite /myapp/config/routes.rb? (enter "h" for help) [Ynaqdh] force config/routes.rb conflict config/application.rb Overwrite /myapp/config/application.rb? (enter "h" for help) [Ynaqdh] force config/application.rb conflict config/environment.rb ... ``` Don't forget to review the difference, to see if there were any unexpected changes. Upgrading from Rails 4.2 to Rails 5.0 ------------------------------------- For more information on changes made to Rails 5.0 please see the [release notes](5_0_release_notes.html). ### Ruby 2.2.2+ required 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. ### Active Record Models Now Inherit from ApplicationRecord by Default In Rails 4.2, an Active Record model inherits from `ActiveRecord::Base`. In Rails 5.0, all models inherit from `ApplicationRecord`. `ApplicationRecord` is a new superclass for all app models, analogous to app controllers subclassing `ApplicationController` instead of `ActionController::Base`. This gives apps a single spot to configure app-wide model behavior. When upgrading from Rails 4.2 to Rails 5.0, you need to create an `application_record.rb` file in `app/models/` and add the following content: ``` class ApplicationRecord < ActiveRecord::Base self.abstract_class = true end ``` ### Halting Callback Chains via `throw(:abort)` In Rails 4.2, when a 'before' callback returns `false` 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. In Rails 5.0, returning `false` 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 `throw(:abort)`. When you upgrade from Rails 4.2 to Rails 5.0, returning `false` in those kind of callbacks will still halt the callback chain, but 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 the following configuration to your `config/application.rb`: ActiveSupport.halt_callback_chains_on_return_false = false Note that this option will not affect Active Support callbacks since they never halted the chain when any value was returned. See [#17227](https://github.com/rails/rails/pull/17227) for more details. ### ActiveJob Now Inherits from ApplicationJob by Default In Rails 4.2, an Active Job inherits from `ActiveJob::Base`. In Rails 5.0, this behavior has changed to now inherit from `ApplicationJob`. When upgrading from Rails 4.2 to Rails 5.0, you need to create an `application_job.rb` file in `app/jobs/` and add the following content: ``` class ApplicationJob < ActiveJob::Base end ``` Then make sure that all your job classes inherit from it. See [#19034](https://github.com/rails/rails/pull/19034) for more details. ### Rails Controller Testing `assigns` and `assert_template` have been extracted to the `rails-controller-testing` gem. To continue using these methods in your controller tests, add `gem 'rails-controller-testing'` to your Gemfile. If you are using Rspec for testing, please see the extra configuration required in the gem's documentation. ### Autoloading is Disabled After Booting in the Production Environment Autoloading is now disabled after booting in the production environment by default. 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. 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. 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 mode, set `Rails.application.config.enable_dependency_loading` to true. ### XML Serialization `ActiveModel::Serializers::Xml` has been extracted from Rails to the `activemodel-serializers-xml` gem. To continue using XML serialization in your application, add `gem 'activemodel-serializers-xml'` to your Gemfile. ### Removed Support for Legacy `mysql` Database Adapter Rails 5 removes support for the legacy `mysql` database adapter. Most users should be able to use `mysql2` instead. It will be converted to a separate gem when we find someone to maintain it. ### Removed Support for Debugger `debugger` is not supported by Ruby 2.2 which is required by Rails 5. Use `byebug` instead. ### Use bin/rails for running tasks and tests Rails 5 adds the ability to run tasks and tests through `bin/rails` instead of rake. Generally these changes are in parallel with rake, but some were ported over altogether. To use the new test runner simply type `bin/rails test`. `rake dev:cache` is now `rails dev:cache`. Run `bin/rails` to see the list of commands available. ### `ActionController::Parameters` No Longer Inherits from `HashWithIndifferentAccess` Calling `params` 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 `slice` and other methods that depend on being able to read the hash regardless of `permitted?` you will need to upgrade your application to first permit and then convert to a hash. params.permit([:proceed_to, :return_to]).to_h ### `protect_from_forgery` Now Defaults to `prepend: false` `protect_from_forgery` defaults to `prepend: false` 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 `protect_from_forgery` to always run first you should change your application to use `protect_from_forgery prepend: true`. ### Default Template Handler is Now RAW 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. 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. ### Added Wildcard Matching for Template Dependencies You can now use wildcard matching for your template dependencies. For example if you were defining your templates as such: ```erb <% # Template Dependency: recordings/threads/events/subscribers_changed %> <% # Template Dependency: recordings/threads/events/completed %> <% # Template Dependency: recordings/threads/events/uncompleted %> ``` You can now just call the dependency once with a wildcard. ```erb <% # Template Dependency: recordings/threads/events/* %> ``` ### Removed Support for `protected_attributes` Gem The `protected_attributes` gem is no longer supported in Rails 5. ### Removed support for `activerecord-deprecated_finders` gem The `activerecord-deprecated_finders` gem is no longer supported in Rails 5. ### `ActiveSupport::TestCase` Default Test Rrder is Now Random When tests are run in your application the default order is now `:random` instead of `:sorted`. Use the following config option to set it back to `:sorted`. ```ruby # config/environments/test.rb Rails.application.configure do config.active_support.test_order = :sorted end ``` ### `ActionController::Live` became a `Concern` That means that if your application used to have its own streaming module, the following code would break in production mode: ```ruby # 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 == 'uncaught throw :warden' throw :warden else raise e end end end ``` If you include `ActionController::Live` in another module that is included in your controller you should also extend the module with `ActiveSupport::Concern`. Or you could use the `self.included` hook to include `ActionController::Live` directly to the controller once the `StreamingSupport` is included. ### New Framework Defaults #### Active Record `belongs_to` Required by Default Option `belongs_to` will now trigger a validation error by default if the association is not present. This can be turned off per-association with `optional: true`. This default will will be automatically configured in new applications. If existing application want to add this feature it will need to be turned on in an initializer. config.active_record.belongs_to_required_by_default = true #### Per-form CSRF Tokens 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 specified to the action and method for that form. config.action_controller.per_form_csrf_tokens = true #### Forgery Protection with Origin Check You can how configure your application to check if the HTTP `Origin` header should be checked against the site's origin as an additional CSRF defense. Set the following in your config to true: config.action_controller.forgery_protection_origin_check = true #### Allow Configuration of Action Mailer Queue Name The default mailer queue name is `mailers`. This configuration option allows you to globally change the queue name. Set the following in your config. config.action_mailer.deliver_later_queue_name = :new_queue_name #### Support Fragment Caching in Action Mailer Views Set `config.action_mailer.perform_caching` in your config to determine whether your Action Mailer views should support caching. config.action_mailer.perform_caching = true #### Configure the Output of `db:structure:dump` If you're using `schema_search_path` or other PostgreSQL extentions, you can control how the schema is dumped. Set to `:all` to generate all dumps, or `:schema_search_path` to generate from schema search path. config.active_record.dump_schemas = :all #### Configure SSL Options to Enable HSTS with Subdomains Set the following in your config to enable HSTS when using subdomains. config.ssl_options = { hsts: { subdomains: true } } #### Preserve Timezone of the Receiver When using Ruby 2.4 you can preserve the timezone of the receiver when calling `to_time`. ActiveSupport.to_time_preserves_timezone = false Upgrading from Rails 4.1 to Rails 4.2 ------------------------------------- ### Web Console First, add `gem 'web-console', '~> 2.0'` to the `:development` group in your Gemfile and run `bundle install` (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., `<%= console %>`) 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. ### Responders `respond_with` and the class-level `respond_to` methods have been extracted to the `responders` gem. To use them, simply add `gem 'responders', '~> 2.0'` to your Gemfile. Calls to `respond_with` and `respond_to` (again, at the class level) will no longer work without having included the `responders` gem in your dependencies: ```ruby # app/controllers/users_controller.rb class UsersController < ApplicationController respond_to :html, :json def show @user = User.find(params[:id]) respond_with @user end end ``` Instance-level `respond_to` is unaffected and does not require the additional gem: ```ruby # app/controllers/users_controller.rb class UsersController < ApplicationController def show @user = User.find(params[:id]) respond_to do |format| format.html format.json { render json: @user } end end end ``` See [#16526](https://github.com/rails/rails/pull/16526) for more details. ### Error handling in transaction callbacks Currently, Active Record suppresses errors raised within `after_rollback` or `after_commit` 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. When you define an `after_rollback` or `after_commit` 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 `config/application.rb`: config.active_record.raise_in_transactional_callbacks = true See [#14488](https://github.com/rails/rails/pull/14488) and [#16537](https://github.com/rails/rails/pull/16537) for more details. ### Ordering of test cases 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 `active_support.test_order` for explicitly specifying the test ordering. This allows you to either lock down the current behavior by setting the option to `:sorted`, or opt into the future behavior by setting the option to `:random`. 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: ```ruby # config/environments/test.rb Rails.application.configure do config.active_support.test_order = :sorted # or `:random` if you prefer end ``` ### Serialized attributes When using a custom coder (e.g. `serialize :metadata, JSON`), assigning `nil` to a serialized attribute will save it to the database as `NULL` instead of passing the `nil` value through the coder (e.g. `"null"` when using the `JSON` coder). ### Production log level In Rails 5, the default log level for the production environment will be changed to `:debug` (from `:info`). To preserve the current default, add the following line to your `production.rb`: ```ruby # Set to `:info` to match the current default, or set to `:debug` to opt-into # the future default. config.log_level = :info ``` ### `after_bundle` in Rails templates 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: ```ruby # template.rb generate(:scaffold, "person name:string") route "root to: 'people#index'" rake("db:migrate") git :init git add: "." git commit: %Q{ -m 'Initial commit' } ``` You can now wrap the `git` calls in an `after_bundle` block. It will be run after the binstubs have been generated. ```ruby # template.rb generate(:scaffold, "person name:string") route "root to: 'people#index'" rake("db:migrate") after_bundle do git :init git add: "." git commit: %Q{ -m 'Initial commit' } end ``` ### Rails HTML Sanitizer 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 [`Rails HTML Sanitizer`](https://github.com/rails/rails-html-sanitizer). This means the methods `sanitize`, `sanitize_css`, `strip_tags` and `strip_links` are backed by a new implementation. This new sanitizer uses [Loofah](https://github.com/flavorjones/loofah) 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. The new version updates `sanitize`, so it can take a `Loofah::Scrubber` for powerful scrubbing. [See some examples of scrubbers here](https://github.com/flavorjones/loofah#loofahscrubber). Two new scrubbers have also been added: `PermitScrubber` and `TargetScrubber`. Read the [gem's readme](https://github.com/rails/rails-html-sanitizer) for more information. The documentation for `PermitScrubber` and `TargetScrubber` explains how you can gain complete control over when and how elements should be stripped. If your application needs to use the old sanitizer implementation, include `rails-deprecated_sanitizer` in your Gemfile: ```ruby gem 'rails-deprecated_sanitizer' ``` ### Rails DOM Testing The [`TagAssertions` module](http://api.rubyonrails.org/classes/ActionDispatch/Assertions/TagAssertions.html) (containing methods such as `assert_tag`), [has been deprecated](https://github.com/rails/rails/blob/6061472b8c310158a2a2e8e9a6b81a1aef6b60fe/actionpack/lib/action_dispatch/testing/assertions/dom.rb) in favor of the `assert_select` methods from the `SelectorAssertions` module, which has been extracted into the [rails-dom-testing gem](https://github.com/rails/rails-dom-testing). ### Masked Authenticity Tokens In order to mitigate SSL attacks, `form_authenticity_token` 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. ### Action Mailer 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 `#deliver_later`, this is no longer true. In Rails 4.2, the invocation of the instance methods are deferred until either `deliver_now` or `deliver_later` is called. For example: ```ruby class Notifier < ActionMailer::Base def notify(user, ...) puts "Called" mail(to: user.email, ...) end end mail = Notifier.notify(user, ...) # Notifier#notify is not yet called at this point mail = mail.deliver_now # Prints "Called" ``` 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: ```ruby class Notifier < ActionMailer::Base def self.broadcast_notifications(users, ...) users.each { |user| Notifier.notify(user, ...) } end end ``` ### Foreign Key Support 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. The migration procedure is as follows: 1. remove `gem "foreigner"` from the Gemfile. 2. run `bundle install`. 3. run `bin/rake db:schema:dump`. 4. make sure that `db/schema.rb` contains every foreign key definition with the necessary options. Upgrading from Rails 4.0 to Rails 4.1 ------------------------------------- ### CSRF protection from remote `