Ruby on Rails - upgrading from rails 4.2 to Rails 5.0 - ruby on rails tutorial - rails guides - rails tutorial - ruby rails
To upgrade:
- Rails 4.2 to Rails 5.0 upgrade,we must be using Ruby 2.2.2 or newer.
- After upgrading our Ruby version if required, go to our Gemfile and change the line:
to:
- Run the command line:
- This will help us to update configuration files.
- We will be prompted to overwrite files and we have several options to input:
- Y – yes, overwrite
- n – no, do not overwrite
- a – all, overwrite this and all others
- q – quit, abort
- d – diff, show the differences between the old and the new
- h – help
Typically,we should check the differences between the old and new files to make sure we aren't getting any unwanted changes.
- Rails 5.0 ActiveRecord models inherit from ApplicationRecord, rather than ActiveRecord::Base.
- ApplicationRecord is the superclass for all models, similar to how ApplicationController is the superclass for controllers.
- To account for this new way in which models are handled, we must create a file in our app/models/ folder called application_record.rb and then edit that file's contents to be:
- Rails 5.0 also handles callbacks slightly different. Callbacks that return false won't halt the callback chain, which means subsequent callbacks will still run, unlike Rails 4.2. When we upgrade, the Rails 4.2 behavior will remain, though we can switch to the Rails 5.0 behavior by adding:
- The config/application.rb file. we can explicitly halt the callback chain by calling throw(:abort).
Rails 5.0, ActiveJob will inherit from ApplicationJob, rather than ActiveJob::Base like in Rails 4.2. To upgrade to Rails 5.0, create a file called application_job.rb in the app/jobs/ folder.
Edit that file's contents to be:
- We must change all of our jobs to inherit from ApplicationJob rather than ActiveJob::Base.
- One of the other biggest changes of Rails 5.0 doesn't require any code changes, but will change the way we use the command line with our Rails apps.
- We will be able to use bin/rails, or just rails, to run tasks and tests.
Example
- Instead of using $ rake db:migrate ,we can now do $ rails db:migrate.
- If we run $ bin/rails, we can view all the available commands.
- Note: that many of the tasks that can now be run with bin/rails still work using rake.