**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 ------------------------------------- ### Ruby 2.2.2+ From Ruby on Rails 5.0 onwards, Ruby 2.2.2+ is the only supported 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 jobs now inherit from ApplicationJob by default In Rails 4.2 an ActiveJob 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. 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 `