Monday, July 10, 2017

Upgrade Rails From 4.2 to 5.0

Upgrade Rails From 4.2 to 5.0

Please see the reference: Upgrading from Rails 4.2 to Rails 5.0

Ruby version > 2.2.2

  $ rvm get stable
  $ rvm install 5.1.2
  $ rvm --default use 5.1.2 (use 5.1.2 as default and current version)
  $ rvm list

Modify Gemfile

  gem 'rails', '4.2.5.1' -> '5.1.2'
  gem 'coffee-rails'     -> # , '~> 4.1.0' 

Active Record Models Now Inherit from ApplicationRecord by Default.

Create an application_record.rb file in  ```app/models/``` and add the following content:
    class ApplicationRecord < ActiveRecord::Base
      self.abstract_class = true
    end

Then modify all model as:

    class Post < ApplicationRecord
                :
    end

Comment the following line in config/application.rb

#config.active_record.raise_in_transactional_callbacks = true

Change ‘for’ to ‘permit’ in ‘controllers/application_controller.rb’ (if gem devise is used)

class ApplicationController < ActionController::Base
  :
  :
  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up) { |u| u.permit(:name, :email, :password, :password_confirmation)}
    devise_parameter_sanitizer.permit(:account_update) { |u| u.permit(:name, :email, :password, :password_confirmation, :current_password) }
  end
end

Update Database Migration File

It is necessary to add version information after version information in database migration file after Rails 5. For example, [5.0]is added in the following example:

class CreateOrders < ActiveRecord::Migration[5.0]
  def change
    create_table :orders do |t|
      t.string :po_number
      t.date :shipment_require_date
      t.date :order_date
      t.string :ship_to
      t.text :reference

      t.timestamps
    end
  end
end

Or, we can add a bunch of code to test which version of Rails and add the information to the end of class declaration. Likewise:

migration_superclass = if ActiveRecord::VERSION::MAJOR >= 5
  ActiveRecord::Migration["#{ActiveRecord::VERSION::MAJOR}.#{ActiveRecord::VERSION::MINOR}"]
else
  ActiveRecord::Migration
end

And also change ActiveRecord::Migration to migration_superclass.

class CreateOrders < migration_superclass

Update gem spring

System shows warning message while execute bundle install:

Array values in the parameter to `Gem.paths=` are deprecated.
Please use a String or nil.

The issue has been posted here.

The solution is to update gem spring:

bundle update spring && bundle exec spring binstub --remove --all && bundle exec spring binstub --all

2 comments: