Ruby on Rails 5.1 Release Notes
Highlights in Rails 5.1:
- Yarn Support
- Optional Webpack support
- jQuery no longer a default dependency
- System tests
- Encrypted secrets
- Parameterized mailers
- Direct & resolved routes
- Unification of form_for and form_tag into form_with
These release notes cover only the major changes. To learn about various bugfixes and changes, please refer to the changelogs or check out thelist ofcommits in the main Railsrepository on GitHub.
1. Upgrading to Rails 5.1
If you're upgrading an existing application, it's a great idea to have good testcoverage before going in. You should also first upgrade to Rails 5.0 in case youhaven't and make sure your application still runs as expected before attemptingan update to Rails 5.1. A list of things to watch out for when upgrading isavailable in theUpgrading Ruby on Railsguide.
2. Major Features
2.1. Yarn Support
Rails 5.1 allows managing JavaScript dependenciesfrom npm via Yarn. This will make it easy to use libraries like React, VueJSor any other library from npm world. The Yarn support is integrated withthe asset pipeline so that all dependencies will work seamlessly with theRails 5.1 app.
2.2. Optional Webpack support
Rails apps can integrate withWebpack, a JavaScriptasset bundler, more easily using the newWebpackergem. Use the--webpack flag when generating new applications to enable Webpackintegration.
This is fully compatible with the asset pipeline, which you can continue to use forimages, fonts, sounds, and other assets. You can even have some JavaScript codemanaged by the asset pipeline, and other code processed via Webpack. All of this is managedby Yarn, which is enabled by default.
2.3. jQuery no longer a default dependency
jQuery was required by default in earlier versions of Rails to provide featureslikedata-remote,data-confirm and other parts of Rails' Unobtrusive JavaScriptofferings. It is no longer required, as the UJS has been rewritten to use plain,vanilla JavaScript. This code now ships inside of Action View asrails-ujs.
You can still use jQuery if needed, but it is no longer required by default.
2.4. System tests
Rails 5.1 has baked-in support for writing Capybara tests, in the form ofSystem tests. You no longer need to worry about configuring Capybara anddatabase cleaning strategies for such tests. Rails 5.1 provides a wrapperfor running tests in Chrome with additional features such as failurescreenshots.
2.5. Encrypted secrets
Rails now allows management of application secrets in a secure way,inspired by thesekrets gem.
Runbin/rails secrets:setup to set up a new encrypted secrets file. This willalso generate a master key, which must be stored outside of the repository. Thesecrets themselves can then be safely checked into the revision control system,in an encrypted form.
Secrets will be decrypted in production, using a key stored either in theRAILS_MASTER_KEY environment variable, or in a key file.
2.6. Parameterized mailers
Allows specifying common parameters used for all methods in a mailer class inorder to share instance variables, headers, and other common setup.
classInvitationsMailer<ApplicationMailerbefore_action{@inviter,@invitee=params[:inviter],params[:invitee]}before_action{@account=params[:inviter].account}defaccount_invitationmailsubject:"#{@inviter.name} invited you to their Basecamp (#{@account.name})"endendInvitationsMailer.with(inviter:person_a,invitee:person_b).account_invitation.deliver_later2.7. Direct & resolved routes
Rails 5.1 adds two new methods,resolve anddirect, to the routingDSL. Theresolve method allows customizing polymorphic mapping of models.
resource:basketresolve("Basket"){[:basket]}<%=form_for@basketdo|form|%><!-- basket form --><%end%>This will generate the singular URL/basket instead of the usual/baskets/:id.
Thedirect method allows creation of custom URL helpers.
direct(:homepage){"https://rubyonrails.org"}homepage_url# => "https://rubyonrails.org"The return value of the block must be a valid argument for theurl_formethod. So, you can pass a valid string URL, Hash, Array, anActive Model instance, or an Active Model class.
direct:commentabledo|model|[model,anchor:model.dom_id]enddirect:maindo{controller:'pages',action:'index',subdomain:'www'}end2.8. Unification of form_for and form_tag into form_with
Before Rails 5.1, there were two interfaces for handling HTML forms:form_for for model instances andform_tag for custom URLs.
Rails 5.1 combines both of these interfaces withform_with, andcan generate form tags based on URLs, scopes, or models.
Using just a URL:
<%=form_withurl:posts_pathdo|form|%><%=form.text_field:title%><%end%><%# Will generate %><formaction="/posts"method="post"data-remote="true"><inputtype="text"name="title"></form>Adding a scope prefixes the input field names:
<%=form_withscope: :post,url:posts_pathdo|form|%><%=form.text_field:title%><%end%><%# Will generate %><formaction="/posts"method="post"data-remote="true"><inputtype="text"name="post[title]"></form>Using a model infers both the URL and scope:
<%=form_withmodel:Post.newdo|form|%><%=form.text_field:title%><%end%><%# Will generate %><formaction="/posts"method="post"data-remote="true"><inputtype="text"name="post[title]"></form>An existing model makes an update form and fills out field values:
<%=form_withmodel:Post.firstdo|form|%><%=form.text_field:title%><%end%><%# Will generate %><formaction="/posts/1"method="post"data-remote="true"><inputtype="hidden"name="_method"value="patch"><inputtype="text"name="post[title]"value="<the title of the post>"></form>3. Incompatibilities
The following changes may require immediate action upon upgrade.
3.1. Transactional tests with multiple connections
Transactional tests now wrap all Active Record connections in databasetransactions.
When a test spawns additional threads, and those threads obtain databaseconnections, those connections are now handled specially:
The threads will share a single connection, which is inside the managedtransaction. This ensures all threads see the database in the samestate, ignoring the outermost transaction. Previously, such additionalconnections were unable to see the fixture rows, for example.
When a thread enters a nested transaction, it will temporarily obtainexclusive use of the connection, to maintain isolation.
If your tests currently rely on obtaining a separate,outside-of-transaction, connection in a spawned thread, you'll need toswitch to more explicit connection management.
If your tests spawn threads and those threads interact while also usingexplicit database transactions, this change may introduce a deadlock.
The easy way to opt-out of this new behavior is to disable transactionaltests on any test cases it affects.
4. Railties
Please refer to theChangelog for detailed changes.
4.1. Removals
Remove deprecated
config.static_cache_control.(commit)Remove deprecated
config.serve_static_files.(commit)Remove deprecated file
rails/rack/debugger.(commit)Remove deprecated tasks:
rails:update,rails:template,rails:template:copy,rails:update:configsandrails:update:bin.(commit)Remove deprecated
CONTROLLERenvironment variable forroutestask.(commit)Remove -j (--javascript) option from
rails newcommand.(Pull Request)
4.2. Notable changes
Added a shared section to
config/secrets.ymlthat will be loaded for allenvironments.(commit)The config file
config/secrets.ymlis now loaded in with all keys as symbols.(Pull Request)Removed jquery-rails from default stack. rails-ujs, which is shippedwith Action View, is included as default UJS adapter.(Pull Request)
Add Yarn support in new apps with a yarn binstub and package.json.(Pull Request)
Add Webpack support in new apps via the
--webpackoption, which will delegateto the rails/webpacker gem.(Pull Request)Initialize Git repo when generating new app, if option
--skip-gitis notprovided.(Pull Request)Add encrypted secrets in
config/secrets.yml.enc.(Pull Request)Display railtie class name in
rails initializers.(Pull Request)
5. Action Cable
Please refer to theChangelog for detailed changes.
5.1. Notable changes
Added support for
channel_prefixto Redis and evented Redis adaptersincable.ymlto avoid name collisions when using the same Redis serverwith multiple applications.(Pull Request)Add
ActiveSupport::Notificationshook for broadcasting data.(Pull Request)
6. Action Pack
Please refer to theChangelog for detailed changes.
6.1. Removals
Removed support for non-keyword arguments in
#process,#get,#post,#patch,#put,#delete, and#headfor theActionDispatch::IntegrationTestandActionController::TestCaseclasses.(Commit,Commit)Removed deprecated
ActionDispatch::Callbacks.to_prepareandActionDispatch::Callbacks.to_cleanup.(Commit)Removed deprecated methods related to controller filters.(Commit)
Removed deprecated support to
:textand:nothinginrender.(Commit,Commit)Removed deprecated support for calling
HashWithIndifferentAccessmethods onActionController::Parameters.(Commit)
6.2. Deprecations
- Deprecated
config.action_controller.raise_on_unfiltered_parameters.It doesn't have any effect in Rails 5.1.(Commit)
6.3. Notable changes
Added the
directandresolvemethods to the routing DSL.(Pull Request)Added a new
ActionDispatch::SystemTestCaseclass to write system tests inyour applications.(Pull Request)
7. Action View
Please refer to theChangelog for detailed changes.
7.1. Removals
Removed deprecated
#original_exceptioninActionView::Template::Error.(commit)Remove the option
encode_special_charsmisnomer fromstrip_tags.(Pull Request)
7.2. Deprecations
- Deprecated Erubis ERB handler in favor of Erubi.(Pull Request)
7.3. Notable changes
Raw template handler (the default template handler in Rails 5) now outputsHTML-safe strings.(commit)
Change
datetime_fieldanddatetime_field_tagto generatedatetime-localfields.(Pull Request)New Builder-style syntax for HTML tags (
tag.div,tag.br, etc.)(Pull Request)Add
form_withto unifyform_tagandform_forusage.(Pull Request)Add
check_parametersoption tocurrent_page?.(Pull Request)
8. Action Mailer
Please refer to theChangelog for detailed changes.
8.1. Notable changes
Allowed setting custom content type when attachments are includedand body is set inline.(Pull Request)
Allowed passing lambdas as values to the
defaultmethod.(Commit)Added support for parameterized invocation of mailers to share before filters and defaultsbetween different mailer actions.(Commit)
Passed the incoming arguments to the mailer action to
process.action_mailerevent underanargskey.(Pull Request)
9. Active Record
Please refer to theChangelog for detailed changes.
9.1. Removals
Removed support for passing arguments and block at the same time to
ActiveRecord::QueryMethods#select.(Commit)Removed deprecated
activerecord.errors.messages.restrict_dependent_destroy.oneandactiverecord.errors.messages.restrict_dependent_destroy.manyi18n scopes.(Commit)Removed deprecated force-reload argument in singular and collection association readers.(Commit)
Removed deprecated support for passing a column to
#quote.(Commit)Removed deprecated
namearguments from#tables.(Commit)Removed deprecated behavior of
#tablesand#table_exists?to return tables and viewsto return only tables and not views.(Commit)Removed deprecated
original_exceptionargument inActiveRecord::StatementInvalid#initializeandActiveRecord::StatementInvalid#original_exception.(Commit)Removed deprecated support of passing a class as a value in a query.(Commit)
Removed deprecated support to query using commas on LIMIT.(Commit)
Removed deprecated
conditionsparameter from#destroy_all.(Commit)Removed deprecated
conditionsparameter from#delete_all.(Commit)Removed deprecated method
#load_schema_forin favor of#load_schema.(Commit)Removed deprecated
#raise_in_transactional_callbacksconfiguration.(Commit)Removed deprecated
#use_transactional_fixturesconfiguration.(Commit)
9.2. Deprecations
Deprecated
error_on_ignored_order_or_limitflag in favor oferror_on_ignored_order.(Commit)Deprecated
sanitize_conditionsin favor ofsanitize_sql.(Pull Request)Deprecated
supports_migrations?on connection adapters.(Pull Request)Deprecated
Migrator.schema_migrations_table_name, useSchemaMigration.table_nameinstead.(Pull Request)Deprecated using
#quoted_idin quoting and type casting.(Pull Request)Deprecated passing
defaultargument to#index_name_exists?.(Pull Request)
9.3. Notable changes
Change Default Primary Keys to BIGINT.(Pull Request)
Virtual/generated column support for MySQL 5.7.5+ and MariaDB 5.2.0+.(Commit)
Added support for limits in batch processing.(Commit)
Transactional tests now wrap all Active Record connections in databasetransactions.(Pull Request)
Skipped comments in the output of
mysqldumpcommand by default.(Pull Request)Fixed
ActiveRecord::Relation#countto use Ruby'sEnumerable#countfor countingrecords when a block is passed as argument instead of silently ignoring thepassed block.(Pull Request)Pass
"-v ON_ERROR_STOP=1"flag withpsqlcommand to not suppress SQL errors.(Pull Request)Add
ActiveRecord::Base.connection_pool.stat.(Pull Request)Inheriting directly from
ActiveRecord::Migrationraises an error.Specify the Rails version for which the migration was written for.(Commit)An error is raised when
throughassociation has ambiguous reflection name.(Commit)
10. Active Model
Please refer to theChangelog for detailed changes.
10.1. Removals
Removed deprecated methods in
ActiveModel::Errors.(commit)Removed deprecated
:tokenizeroption in the length validator.(commit)Remove deprecated behavior that halts callbacks when the return value is false.(commit)
10.2. Notable changes
- The original string assigned to a model attribute is no longer incorrectlyfrozen.(Pull Request)
11. Active Job
Please refer to theChangelog for detailed changes.
11.1. Removals
Removed deprecated support to passing the adapter class to
.queue_adapter.(commit)Removed deprecated
#original_exceptioninActiveJob::DeserializationError.(commit)
11.2. Notable changes
Added declarative exception handling via
ActiveJob::Base.retry_onandActiveJob::Base.discard_on.(Pull Request)Yield the job instance so you have access to things like
job.argumentsonthe custom logic after retries fail.(commit)
12. Active Support
Please refer to theChangelog for detailed changes.
12.1. Removals
Removed the
ActiveSupport::Concurrency::Latchclass.(Commit)Removed
halt_callback_chains_on_return_false.(Commit)Removed deprecated behavior that halts callbacks when the return is false.(Commit)
12.2. Deprecations
The top level
HashWithIndifferentAccessclass has been softly deprecatedin favor of theActiveSupport::HashWithIndifferentAccessone.(Pull Request)Deprecated passing string to
:ifand:unlessconditional options onset_callbackandskip_callback.(Commit)
12.3. Notable changes
Fixed duration parsing and traveling to make it consistent across DST changes.(Commit,Pull Request)
Updated Unicode to version 9.0.0.(Pull Request)
Add Duration#before and #after as aliases for #ago and #since.(Pull Request)
Added
Module#delegate_missing_toto delegate method calls notdefined for the current object to a proxy object.(Pull Request)Added
Date#all_daywhich returns a range representing the whole dayof the current date & time.(Pull Request)Introduced the
assert_changesandassert_no_changesmethods for tests.(Pull Request)The
travelandtravel_tomethods now raise on nested calls.(Pull Request)Update
DateTime#changeto support usec and nsec.(Pull Request)
13. Credits
See thefull list of contributors to Rails forthe many people who spent many hours making Rails, the stable and robustframework it is. Kudos to all of them.