This document is a work in progress, please help to improve this by sending a pull request.
1 Upgrading to Rails 4.2
If you're upgrading an existing application, it's a great idea to have good test coverage before going in. You should also first upgrade to Rails 4.1 in case you haven't and make sure your application still runs as expected before attempting to upgrade to Rails 4.2. A list of things to watch out for when upgrading is available in the Upgrading Ruby on Rails guide.
2 Major Features
2.1 Active Job, Action Mailer #deliver_later
Active Job is a new framework in Rails 4.2. It is an adapter layer on top of queuing systems like Resque, Delayed Job, Sidekiq, and more. You can write your jobs to Active Job, and it'll run on all these queues with no changes. (It comes pre-configured with an inline runner.)
Building on top of Active Job, Action Mailer now comes with a #deliver_later method, which adds your email to be sent as a job to a queue, so it doesn't bog down the controller or model.
The new GlobalID library makes it easy to pass Active Record objects to jobs by serializing them in a generic form. This means you no longer have to manually pack and unpack your Active Records by passing ids. Just give the job the straight Active Record object, and it'll serialize it using GlobalID, and deserialize it at run time.
2.2 Adequate Record
Rails 4.2 comes with a performance improvement feature called Adequate Record for Active Record. A lot of common queries are now up to twice as fast in Rails 4.2!
add some technical details
2.3 Web Console
New applications generated from Rails 4.2 now comes with the Web Console gem by default.
Web Console is an IRB console available in the browser. In development mode, you can go to /console and do your work right there. It will also be made available on all exception pages and allows you to jump between the different points in the backtrace.
2.4 Foreign key support
The migration DSL now supports adding and removing foreign keys. They are dumped
to schema.rb as well. At this time, only the mysql, mysql2 and postgresql
adapters support foreign keys.
# add a foreign key to `articles.author_id` referencing `authors.id` add_foreign_key :articles, :authors # add a foreign key to `articles.author_id` referencing `users.lng_id` add_foreign_key :articles, :users, column: :author_id, primary_key: "lng_id" # remove the foreign key on `accounts.branch_id` remove_foreign_key :accounts, :branches # remove the foreign key on `accounts.owner_id` remove_foreign_key :accounts, column: :owner_id
See the API documentation on add_foreign_key and remove_foreign_key for a full description.
3 Railties
Please refer to the Changelog for detailed changes.
3.1 Removals
- The
rails applicationcommand has been removed without replacement. (Pull Request)
3.2 Deprecations
- Deprecated
Rails::Rack::LogTailerwithout replacement. (Commit)
3.3 Notable changes
Introduced
web-consolein the default application Gemfile. (Pull Request)Added a
requiredoption to the model generator for associations. (Pull Request)Introduced an
after_bundlecallback for use in Rails templates. (Pull Request)-
Introduced the
xnamespace for defining custom configuration options:# config/environments/production.rb config.x.payment_processing.schedule = :daily config.x.payment_processing.retries = 3 config.x.super_debugger = true
These options are then available through the configuration object:
Rails.configuration.x.payment_processing.schedule # => :daily Rails.configuration.x.payment_processing.retries # => 3 Rails.configuration.x.super_debugger # => true
(Commit)
-
Introduced
Rails::Application.config_forto load a configuration for the current environment.# config/exception_notification.yml: production: url: http://127.0.0.1:8080 namespace: my_app_production development: url: http://localhost:3001 namespace: my_app_development # config/production.rb MyApp::Application.configure do config.middleware.use ExceptionNotifier, config_for(:exception_notification) end
Introduced a
--skip-gemsoption in the app generator to skip gems such asturbolinksandcoffee-railsthat do not have their own specific flags. (Commit)Introduced a
bin/setupscript to enable automated setup code when bootstrapping an application. (Pull Request)Changed default value for
config.assets.digesttotruein development. (Pull Request)Introduced an API to register new extensions for
rake notes. (Pull Request)Introduced
Rails.gem_versionas a convenience method to returnGem::Version.new(Rails.version). (Pull Request)
4 Action Pack
Please refer to the Changelog for detailed changes.
4.1 Removals
respond_withand the class-levelrespond_towere removed from Rails and moved to therespondersgem (version 2.0). Addgem 'responders', '~> 2.0'to yourGemfileto continue using these features. (Pull Request)Removed deprecated
AbstractController::Helpers::ClassMethods::MissingHelperErrorin favor ofAbstractController::Helpers::MissingHelperError. (Commit)
4.2 Deprecations
Deprecated
assert_tag,assert_no_tag,find_tagandfind_all_tagin favor ofassert_select. (Commit)-
Deprecated support for setting the
:tooption of a router to a symbol or a string that does not contain a#character:get '/posts', to: MyRackApp => (No change necessary) get '/posts', to: 'post#index' => (No change necessary) get '/posts', to: 'posts' => get '/posts', controller: :posts get '/posts', to: :index => get '/posts', action: :index
(Commit)
4.3 Notable changes
Rails will now automatically include the template's digest in ETags. (Pull Request)
render nothing: trueor rendering anilbody no longer add a single space padding to the response body. (Pull Request)Introduced the
always_permitted_parametersoption to configure which parameters are permitted globally. The default value of this configuration is['controller', 'action']. (Pull Request)-
The
*_filterfamily methods have been removed from the documentation. Their usage is discouraged in favor of the*_actionfamily methods:after_filter => after_action append_after_filter => append_after_action append_around_filter => append_around_action append_before_filter => append_before_action around_filter => around_action before_filter => before_action prepend_after_filter => prepend_after_action prepend_around_filter => prepend_around_action prepend_before_filter => prepend_before_action skip_after_filter => skip_after_action skip_around_filter => skip_around_action skip_before_filter => skip_before_action skip_filter => skip_action_callback
If your application is depending on these methods, you should use the replacement
*_actionmethods instead. These methods will be deprecated in the future and eventually removed from Rails. Added HTTP method
MKCALENDARfrom RFC-4791 (Pull Request)*_fragment.action_controllernotifications now include the controller and action name in the payload. (Pull Request)Segments that are passed into URL helpers are now automatically escaped. (Commit)
Improved the Routing Error page with fuzzy matching for route search. (Pull Request)
Added an option to disable logging of CSRF failures. (Pull Request)
5 Action View
Please refer to the Changelog for detailed changes.
5.1 Deprecations
Deprecated
AbstractController::Base.parent_prefixes. OverrideAbstractController::Base.local_prefixeswhen you want to change where to find views. (Pull Request)Deprecated
ActionView::Digestor#digest(name, format, finder, options = {}). Arguments should be passed as a hash instead. (Pull Request)
5.2 Notable changes
Introduced a
#{partial_name}_iterationspecial local variable for use with partials that are rendered with a collection. It provides access to the current state of the iteration via the#index,#size,#first?and#last?methods. (Pull Request)The form helpers no longer generate a
<div>element with inline CSS around the hidden fields. (Pull Request)Placeholder I18n follows the same convention as
labelI18n. (Pull Request)
6 Action Mailer
Please refer to the Changelog for detailed changes.
6.1 Deprecations
Deprecated
*_pathhelpers in mailers. Always use*_urlhelpers instead. (Pull Request)Deprecated
deliver/deliver!in favour ofdeliver_now/deliver_now!. (Pull Request)
6.2 Notable changes
Introduced
deliver_laterwhich enqueues a job on the application's queue to deliver the mailer asynchronously. (Pull Request)Added the
show_previewsconfiguration option for enabling mailer previews outside of the development environment. (Pull Request)
7 Active Record
Please refer to the Changelog for detailed changes.
7.1 Removals
Removed
cache_attributesand friends. All attributes are cached. (Pull Request)Removed deprecated method
ActiveRecord::Base.quoted_locking_column. (Pull Request)Removed deprecated
ActiveRecord::Migrator.proper_table_name. Use theproper_table_nameinstance method onActiveRecord::Migrationinstead. (Pull Request)Removed unused
:timestamptype. Transparently alias it to:datetimein all cases. Fixes inconsistencies when column types are sent outside ofActiveRecord, such as for XML Serialization. (Pull Request)
7.2 Deprecations
Deprecated swallowing of errors inside
after_commitandafter_rollback. (Pull Request)Deprecated calling
DatabaseTasks.load_schemawithout a connection. UseDatabaseTasks.load_schema_currentinstead. (Commit)Deprecated
Reflection#source_macrowithout replacement as it is no longer needed in Active Record. (Pull Request)Deprecated broken support for automatic detection of counter caches on
has_many :throughassociations. You should instead manually specify the counter cache on thehas_manyandbelongs_toassociations for the through records. (Pull Request)Deprecated
serialized_attributeswithout replacement. (Pull Request)Deprecated returning
nilfromcolumn_for_attributewhen no column exists. It will return a null object in Rails 5.0 (Pull Request)Deprecated using
.joins,.preloadand.eager_loadwith associations that depends on the instance state (i.e. those defined with a scope that takes an argument) without replacement. (Commit)Deprecated passing Active Record objects to
.findor.exists?. Call#idon the objects first. (Commit 1, 2)-
Deprecated half-baked support for PostgreSQL range values with excluding beginnings. We currently map PostgreSQL ranges to Ruby ranges. This conversion is not fully possible because the Ruby range does not support excluded beginnings.
The current solution of incrementing the beginning is not correct and is now deprecated. For subtypes where we don't know how to increment (e.g.
#succis not defined) it will raise anArgumentErrorfor ranges with excluding beginnings.(Commit)
7.3 Notable changes
The PostgreSQL adapter now supports the
JSONBdatatype in PostgreSQL 9.4+. (Pull Request)The
#referencesmethod in migrations now supports atypeoption for specifying the type of the foreign key (e.g.:uuid). (Pull Request)Added a
:requiredoption to singular associations, which defines a presence validation on the association. (Pull Request)Introduced
ActiveRecord::Base#validate!that raisesRecordInvalidif the record is invalid. (Pull Request)ActiveRecord::Base#reloadnow behaves the same asm = Model.find(m.id), meaning that it no longer retains the extra attributes from customselects. (Pull Request)Introduced the
bin/rake db:purgetask to empty the database for the current environment. (Commit)ActiveRecord::Dirtynow detects in-place changes to mutable values. Serialized attributes on ActiveRecord models will no longer save when unchanged. This also works with other types such as string columns and json columns on PostgreSQL. (Pull Requests 1, 2, 3)Added support for
#pretty_printinActiveRecord::Baseobjects. (Pull Request)PostgreSQL and SQLite adapters no longer add a default limit of 255 characters on string columns. (Pull Request)
sqlite3:///some/pathnow resolves to the absolute system path/some/path. For relative paths, usesqlite3:some/pathinstead. (Previously,sqlite3:///some/pathresolved to the relative pathsome/path. This behaviour was deprecated on Rails 4.1.) (Pull Request)Introduced
#validateas an alias for#valid?. (Pull Request)#touchnow accepts multiple attributes to be touched at once. (Pull Request)Added support for fractional seconds for MySQL 5.6 and above. (Pull Request 1, 2)
Added support for the
citextcolumn type in PostgreSQL adapter. (Pull Request)Added support for user-created range types in PostgreSQL adapter. (Commit)
8 Active Model
Please refer to the Changelog for detailed changes.
8.1 Removals
- Removed deprecated
Validator#setupwithout replacement. (Pull Request)
8.2 Deprecations
Deprecated reset_#{attribute} in favor of restore_#{attribute}. (Pull Request)
Deprecated ActiveModel::Dirty#reset_changes in favor of #clear_changes_information. (Pull Request)
8.3 Notable changes
Introduced the
restore_attributesmethod inActiveModel::Dirtyto restore the changed (dirty) attributes to their previous values. (Pull Request 1, 2)has_secure_passwordno longer disallow blank passwords (i.e. passwords that contains only spaces) by default. (Pull Request)has_secure_passwordnow verifies that the given password is less than 72 characters if validations are enabled. (Pull Request)Introduced
#validateas an alias for#valid?. (Pull Request)
9 Active Support
Please refer to the Changelog for detailed changes.
9.1 Removals
Removed deprecated
Numeric#ago,Numeric#until,Numeric#since,Numeric#from_now. (Commit)Removed deprecated string based terminators for
ActiveSupport::Callbacks. (Pull Request)
9.2 Deprecations
Deprecated
Kernel#silence_stderr,Kernel#captureandKernel#quietlywithout replacement. (Pull Request)Deprecated
Class#superclass_delegating_accessor, useClass#class_attributeinstead. (Pull Request)Deprecated
ActiveSupport::SafeBuffer#prepend!asActiveSupport::SafeBuffer#prependnow performs the same function. (Pull Request)
9.3 Notable changes
The
travel_totest helper now truncates theuseccomponent to 0. (Commit)ActiveSupport::TestCasenow randomizes the order that test cases are ran by default. (Commit)Introduced
Object#itselfas an identity function. (Commit 1, 2)Object#with_optionscan now be used without an explicit receiver. (Pull Request)Introduced
String#truncate_wordsto truncate a string by a number of words. (Pull Request)Added
Hash#transform_valuesandHash#transform_values!to simplify a common pattern where the values of a hash must change, but the keys are left the same. (Pull Request)The
humanizeinflector helper now strips any leading underscores. (Commit)Introduced
Concern#class_methodsas an alternative tomodule ClassMethods, as well asKernel#concernto avoid themodule Foo; extend ActiveSupport::Concern; endboilerplate. (Commit)
10 Credits
See the full list of contributors to Rails for the many people who spent many hours making Rails the stable and robust framework it is today. Kudos to all of them.
Feedback
You're encouraged to help improve the quality of this guide.
Please contribute if you see any typos or factual errors. To get started, you can read our documentation contributions section.
You may also find incomplete content, or stuff that is not up to date. Please do add any missing documentation for master. Make sure to check Edge Guides first to verify if the issues are already fixed or not on the master branch. Check the Ruby on Rails Guides Guidelines for style and conventions.
If for whatever reason you spot something to fix but cannot patch it yourself, please open an issue.
And last but not least, any kind of discussion regarding Ruby on Rails documentation is very welcome in the rubyonrails-docs mailing list.