1. Upgrading to Rails 5.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 5.1 in case you haven't and make sure your application still runs as expected before attempting an update to Rails 5.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 Storage
Active Storage facilitates uploading files to a cloud storage service like Amazon S3, Google Cloud Storage, or Microsoft Azure Storage and attaching those files to Active Record objects. It comes with a local disk-based service for development and testing and supports mirroring files to subordinate services for backups and migrations. You can read more about Active Storage in the Active Storage Overview guide.
2.2. Redis Cache Store
Rails 5.2 ships with built-in Redis cache store. You can read more about this in the Caching with Rails: An Overview guide.
2.3. HTTP/2 Early Hints
Rails 5.2 supports HTTP/2 Early Hints.
To start the server with Early Hints enabled pass --early-hints
to bin/rails server.
2.4. Credentials
Added config/credentials.yml.enc file to store production app secrets.
It allows saving any authentication credentials for third-party services
directly in repository encrypted with a key in the config/master.key file or
the RAILS_MASTER_KEY environment variable.
This will eventually replace Rails.application.secrets and the encrypted
secrets introduced in Rails 5.1.
Furthermore, Rails 5.2
opens API underlying Credentials,
so you can easily deal with other encrypted configurations, keys, and files.
You can read more about this in the
Securing Rails Applications
guide.
2.5. Content Security Policy
Rails 5.2 ships with a new DSL that allows you to configure a Content Security Policy for your application. You can configure a global default policy and then override it on a per-resource basis and even use lambdas to inject per-request values into the header such as account subdomains in a multi-tenant application. You can read more about this in the Securing Rails Applications guide.
3. Railties
Please refer to the Changelog for detailed changes.
3.1. Deprecations
Deprecate
capify!method in generators and templates. (Pull Request)Passing the environment's name as a regular argument to the
rails dbconsoleandrails consolecommands is deprecated. The-eoption should be used instead. (Commit)Deprecate using subclass of
Rails::Applicationto start the Rails server. (Pull Request)Deprecate
after_bundlecallback in Rails plugin templates. (Pull Request)
3.2. Notable changes
Added a shared section to
config/database.ymlthat will be loaded for all environments. (Pull Request)Add
railtie.rbto the plugin generator. (Pull Request)Clear screenshot files in
tmp:cleartask. (Pull Request)Skip unused components when running
bin/rails app:update. If the initial app generation skipped Action Cable, Active Record, etc., the update task honors those skips too. (Pull Request)Allow passing a custom connection name to the
rails dbconsolecommand when using a 3-level database configuration. Example:bin/rails dbconsole -c replica. (Commit)Properly expand shortcuts for environment's name running the
consoleanddbconsolecommands. (Commit)Add
bootsnapto defaultGemfile. (Pull Request)Support
-as a platform-agnostic way to run a script from stdin withrails runner(Pull Request)Add
ruby x.x.xversion toGemfileand create.ruby-versionroot file containing the current Ruby version when new Rails applications are created. (Pull Request)Add
--skip-action-cableoption to the plugin generator. (Pull Request)Add
git_sourcetoGemfilefor plugin generator. (Pull Request)Skip unused components when running
bin/railsin Rails plugin. (Commit)Optimize indentation for generator actions. (Pull Request)
Optimize routes indentation. (Pull Request)
Add
--skip-yarnoption to the plugin generator. (Pull Request)Support multiple versions arguments for
gemmethod of Generators. (Pull Request)Derive
secret_key_basefrom the app name in development and test environments. (Pull Request)Add
mini_magickto defaultGemfileas comment. (Pull Request)rails newandrails plugin newgetActive Storageby default. Add ability to skipActive Storagewith--skip-active-storageand do so automatically when--skip-active-recordis used. (Pull Request)
4. Action Cable
Please refer to the Changelog for detailed changes.
4.1. Removals
- Removed deprecated evented redis adapter. (Commit)
4.2. Notable changes
Add support for
host,port,dbandpasswordoptions in cable.yml (Pull Request)Hash long stream identifiers when using PostgreSQL adapter. (Pull Request)
5. Action Pack
Please refer to the Changelog for detailed changes.
5.1. Removals
- Remove deprecated
ActionController::ParamsParser::ParseError. (Commit)
5.2. Deprecations
- Deprecate
#success?,#missing?and#error?aliases ofActionDispatch::TestResponse. (Pull Request)
5.3. Notable changes
Add support for recyclable cache keys with fragment caching. (Pull Request)
Change the cache key format for fragments to make it easier to debug key churn. (Pull Request)
AEAD encrypted cookies and sessions with GCM. (Pull Request)
Protect from forgery by default. (Pull Request)
Enforce signed/encrypted cookie expiry server side. (Pull Request)
Cookies
:expiresoption supportsActiveSupport::Durationobject. (Pull Request)Use Capybara registered
:pumaserver config. (Pull Request)Simplify cookies middleware with key rotation support. (Pull Request)
Add ability to enable Early Hints for HTTP/2. (Pull Request)
Add headless chrome support to System Tests. (Pull Request)
Add
:allow_other_hostoption toredirect_backmethod. (Pull Request)Make
assert_recognizesto traverse mounted engines. (Pull Request)Add DSL for configuring Content-Security-Policy header. (Pull Request, Commit, Commit)
Register most popular audio/video/font MIME types supported by modern browsers. (Pull Request)
Changed the default system test screenshot output from
inlinetosimple. (Commit)Add headless firefox support to System Tests. (Pull Request)
Add secure
X-Download-OptionsandX-Permitted-Cross-Domain-Policiesto default headers set. (Commit)Changed the system tests to set Puma as default server only when the user haven't specified manually another server. (Pull Request)
Add
Referrer-Policyheader to default headers set. (Commit)Matches behavior of
Hash#eachinActionController::Parameters#each. (Pull Request)Add support for automatic nonce generation for Rails UJS. (Commit)
Update the default HSTS max-age value to 31536000 seconds (1 year) to meet the minimum max-age requirement for https://hstspreload.org/. (Commit)
Add alias method
to_hashtoto_hforcookies. Add alias methodto_htoto_hashforsession. (Commit)
6. Action View
Please refer to the Changelog for detailed changes.
6.1. Removals
- Remove deprecated Erubis ERB handler. (Commit)
6.2. Deprecations
- Deprecate
image_althelper which used to add default alt text to the images generated byimage_tag. (Pull Request)
6.3. Notable changes
Add
:jsontype toauto_discovery_link_tagto support JSON Feeds. (Pull Request)Add
srcsetoption toimage_taghelper. (Pull Request)Fix issues with
field_error_procwrappingoptgroupand select divideroption. (Pull Request)Change
form_withto generate ids by default. (Commit)Add
preload_link_taghelper. (Pull Request)Allow the use of callable objects as group methods for grouped selects. (Pull Request)
7. Action Mailer
Please refer to the Changelog for detailed changes.
7.1. Notable changes
Allow Action Mailer classes to configure their delivery job. (Pull Request)
Add
assert_enqueued_email_withtest helper. (Pull Request)
8. Active Record
Please refer to the Changelog for detailed changes.
8.1. Removals
Remove deprecated
#migration_keys. (Pull Request)Remove deprecated support to
quoted_idwhen typecasting an Active Record object. (Commit)Remove deprecated argument
defaultfromindex_name_exists?. (Commit)Remove deprecated support to passing a class to
:class_nameon associations. (Commit)Remove deprecated methods
initialize_schema_migrations_tableandinitialize_internal_metadata_table. (Commit)Remove deprecated method
supports_migrations?. (Commit)Remove deprecated method
supports_primary_key?. (Commit)Remove deprecated method
ActiveRecord::Migrator.schema_migrations_table_name. (Commit)Remove deprecated argument
namefrom#indexes. (Commit)Remove deprecated arguments from
#verify!. (Commit)Remove deprecated configuration
.error_on_ignored_order_or_limit. (Commit)Remove deprecated method
#scope_chain. (Commit)Remove deprecated method
#sanitize_conditions. (Commit)
8.2. Deprecations
Deprecate
supports_statement_cache?. (Pull Request)Deprecate passing arguments and block at the same time to
countandsuminActiveRecord::Calculations. (Pull Request)Deprecate delegating to
arelinRelation. (Pull Request)Deprecate
set_statemethod inTransactionState. (Commit)Deprecate
expand_hash_conditions_for_aggregateswithout replacement. (Commit)
8.3. Notable changes
When calling the dynamic fixture accessor method with no arguments, it now returns all fixtures of this type. Previously this method always returned an empty array. (Pull Request)
Fix inconsistency with changed attributes when overriding Active Record attribute reader. (Pull Request)
Support Descending Indexes for MySQL. (Pull Request)
Fix
bin/rails db:forwardfirst migration. (Commit)Raise error
UnknownMigrationVersionErroron the movement of migrations when the current migration does not exist. (Commit)Respect
SchemaDumper.ignore_tablesin rake tasks for databases structure dump. (Pull Request)Add
ActiveRecord::Base#cache_versionto support recyclable cache keys via the new versioned entries inActiveSupport::Cache. This also means thatActiveRecord::Base#cache_keywill now return a stable key that does not include a timestamp any more. (Pull Request)Prevent creation of bind param if casted value is nil. (Pull Request)
Use bulk INSERT to insert fixtures for better performance. (Pull Request)
Merging two relations representing nested joins no longer transforms the joins of the merged relation into LEFT OUTER JOIN. (Pull Request)
Fix transactions to apply state to child transactions. Previously, if you had a nested transaction and the outer transaction was rolledback, the record from the inner transaction would still be marked as persisted. It was fixed by applying the state of the parent transaction to the child transaction when the parent transaction is rolledback. This will correctly mark records from the inner transaction as not persisted. (Commit)
Fix eager loading/preloading association with scope including joins. (Pull Request)
Prevent errors raised by
sql.active_recordnotification subscribers from being converted intoActiveRecord::StatementInvalidexceptions. (Pull Request)Skip query caching when working with batches of records (
find_each,find_in_batches,in_batches). (Commit)Change sqlite3 boolean serialization to use 1 and 0. SQLite natively recognizes 1 and 0 as true and false, but does not natively recognize 't' and 'f' as was previously serialized. (Pull Request)
Values constructed using multi-parameter assignment will now use the post-type-cast value for rendering in single-field form inputs. (Commit)
ApplicationRecordis no longer generated when generating models. If you need to generate it, it can be created withrails g application_record. (Pull Request)Relation#ornow accepts two relations who have different values forreferencesonly, asreferencescan be implicitly called bywhere. (Commit)When using
Relation#or, extract the common conditions and put them before the OR condition. (Pull Request)Add
binaryfixture helper method. (Pull Request)Automatically guess the inverse associations for STI. (Pull Request)
Add new error class
LockWaitTimeoutwhich will be raised when lock wait timeout exceeded. (Pull Request)Update payload names for
sql.active_recordinstrumentation to be more descriptive. (Pull Request)Use given algorithm while removing index from database. (Pull Request)
Passing a
SettoRelation#wherenow behaves the same as passing an array. (Commit)PostgreSQL
tsrangenow preserves subsecond precision. (Pull Request)Raises when calling
lock!in a dirty record. (Commit)Fixed a bug where column orders for an index weren't written to
db/schema.rbwhen using the SQLite adapter. (Pull Request)Fix
bin/rails db:migratewith specifiedVERSION.bin/rails db:migratewith empty VERSION behaves as withoutVERSION. Check a format ofVERSION: Allow a migration version number or name of a migration file. Raise error if format ofVERSIONis invalid. Raise error if target migration doesn't exist. (Pull Request)Add new error class
StatementTimeoutwhich will be raised when statement timeout exceeded. (Pull Request)update_allwill now pass its values toType#castbefore passing them toType#serialize. This means thatupdate_all(foo: 'true')will properly persist a boolean. (Commit)Require raw SQL fragments to be explicitly marked when used in relation query methods. (Commit, Commit)
Add
#up_onlyto database migrations for code that is only relevant when migrating up, e.g. populating a new column. (Pull Request)Add new error class
QueryCanceledwhich will be raised when canceling statement due to user request. (Pull Request)Don't allow scopes to be defined which conflict with instance methods on
Relation. (Pull Request)Add support for PostgreSQL operator classes to
add_index. (Pull Request)Log database query callers. (Pull Request, Pull Request, Pull Request)
Undefine attribute methods on descendants when resetting column information. (Pull Request)
Using subselect for
delete_allwithlimitoroffset. (Commit)Fixed inconsistency with
first(n)when used withlimit(). Thefirst(n)finder now respects thelimit(), making it consistent withrelation.to_a.first(n), and also with the behavior oflast(n). (Pull Request)Fix nested
has_many :throughassociations on unpersisted parent instances. (Commit)Take into account association conditions when deleting through records. (Commit)
Don't allow destroyed object mutation after
saveorsave!is called. (Commit)Fix relation merger issue with
left_outer_joins. (Pull Request)Support for PostgreSQL foreign tables. (Pull Request)
Clear the transaction state when an Active Record object is duped. (Pull Request)
Fix not expanded problem when passing an Array object as argument to the where method using
composed_ofcolumn. (Pull Request)Make
reflection.klassraise ifpolymorphic?not to be misused. (Commit)Fix
#columns_for_distinctof MySQL and PostgreSQL to makeActiveRecord::FinderMethods#limited_ids_foruse correct primary key values even ifORDER BYcolumns include other table's primary key. (Commit)Fix
dependent: :destroyissue for has_one/belongs_to relationship where the parent class was getting deleted when the child was not. (Commit)Idle database connections (previously just orphaned connections) are now periodically reaped by the connection pool reaper. (Commit)
9. Active Model
Please refer to the Changelog for detailed changes.
9.1. Notable changes
Fix methods
#keys,#valuesinActiveModel::Errors. Change#keysto only return the keys that don't have empty messages. Change#valuesto only return the not empty values. (Pull Request)Add method
#merge!forActiveModel::Errors. (Pull Request)Allow passing a Proc or Symbol to length validator options. (Pull Request)
Execute
ConfirmationValidatorvalidation when_confirmation's value isfalse. (Pull Request)Models using the attributes API with a proc default can now be marshalled. (Commit)
Do not lose all multiple
:includeswith options in serialization. (Commit)
10. Active Support
Please refer to the Changelog for detailed changes.
10.1. Removals
Remove deprecated
:ifand:unlessstring filter for callbacks. (Commit)Remove deprecated
halt_callback_chains_on_return_falseoption. (Commit)
10.2. Deprecations
Deprecate
Module#reachable?method. (Pull Request)Deprecate
secrets.secret_token. (Commit)
10.3. Notable changes
Add
fetch_valuesforHashWithIndifferentAccess. (Pull Request)Add support for
:offsettoTime#change. (Commit)Add support for
:offsetand:zonetoActiveSupport::TimeWithZone#change. (Commit)Pass gem name and deprecation horizon to deprecation notifications. (Pull Request)
Add support for versioned cache entries. This enables the cache stores to recycle cache keys, greatly saving on storage in cases with frequent churn. Works together with the separation of
#cache_keyand#cache_versionin Active Record and its use in Action Pack's fragment caching. (Pull Request)Add
ActiveSupport::CurrentAttributesto provide a thread-isolated attributes singleton. Primary use case is keeping all the per-request attributes easily available to the whole system. (Pull Request)#singularizeand#pluralizenow respect uncountables for the specified locale. (Commit)Add default option to
class_attribute. (Pull Request)Add
Date#prev_occurringandDate#next_occurringto return specified next/previous occurring day of week. (Pull Request)Add default option to module and class attribute accessors. (Pull Request)
Cache:
write_multi. (Pull Request)Default
ActiveSupport::MessageEncryptorto use AES 256 GCM encryption. (Pull Request)Add
freeze_timehelper which freezes time toTime.nowin tests. (Pull Request)Make the order of
Hash#reverse_merge!consistent withHashWithIndifferentAccess. (Pull Request)Add purpose and expiry support to
ActiveSupport::MessageVerifierandActiveSupport::MessageEncryptor. (Pull Request)Update
String#camelizeto provide feedback when wrong option is passed. (Pull Request)Module#delegate_missing_tonow raisesDelegationErrorif target is nil, similar toModule#delegate. (Pull Request)Add
ActiveSupport::EncryptedFileandActiveSupport::EncryptedConfiguration. (Pull Request)Add
config/credentials.yml.encto store production app secrets. (Pull Request)Add key rotation support to
MessageEncryptorandMessageVerifier. (Pull Request)Return an instance of
HashWithIndifferentAccessfromHashWithIndifferentAccess#transform_keys. (Pull Request)Hash#slicenow falls back to Ruby 2.5+'s built-in definition if defined. (Commit)IO#to_jsonnow returns theto_srepresentation, rather than attempting to convert to an array. This fixes a bug whereIO#to_jsonwould raise anIOErrorwhen called on an unreadable object. (Pull Request)Add same method signature for
Time#prev_dayandTime#next_dayin accordance withDate#prev_day,Date#next_day. Allows pass argument forTime#prev_dayandTime#next_day. (Commit)Add same method signature for
Time#prev_monthandTime#next_monthin accordance withDate#prev_month,Date#next_month. Allows pass argument forTime#prev_monthandTime#next_month. (Commit)Add same method signature for
Time#prev_yearandTime#next_yearin accordance withDate#prev_year,Date#next_year. Allows pass argument forTime#prev_yearandTime#next_year. (Commit)Fix acronym support in
humanize. (Commit)Allow
Range#include?on TWZ ranges. (Pull Request)Cache: Enable compression by default for values > 1kB. (Pull Request)
Redis cache store. (Pull Request, Pull Request)
Handle
TZInfo::AmbiguousTimeerrors. (Pull Request)MemCacheStore: Support expiring counters. (Commit)
Make
ActiveSupport::TimeZone.allreturn only time zones that are inActiveSupport::TimeZone::MAPPING. (Pull Request)Changed default behavior of
ActiveSupport::SecurityUtils.secure_compare, to make it not leak length information even for variable length string. Renamed oldActiveSupport::SecurityUtils.secure_comparetofixed_length_secure_compare, and started raisingArgumentErrorin case of length mismatch of passed strings. (Pull Request)Use SHA-1 to generate non-sensitive digests, such as the ETag header. (Pull Request, Pull Request)
assert_changeswill always assert that the expression changes, regardless offrom:andto:argument combinations. (Pull Request)Add missing instrumentation for
read_multiinActiveSupport::Cache::Store. (Pull Request)Support hash as first argument in
assert_difference. This allows to specify multiple numeric differences in the same assertion. (Pull Request)Caching: MemCache and Redis
read_multiandfetch_multispeedup. Read from the local in-memory cache before consulting the backend. (Commit)
11. Active Job
Please refer to the Changelog for detailed changes.
11.1. Notable changes
- Allow block to be passed to
ActiveJob::Base.discard_onto allow custom handling of discard jobs. (Pull Request)
12. Ruby on Rails Guides
Please refer to the Changelog for detailed changes.
12.1. Notable changes
Add Threading and Code Execution in Rails Guide. (Pull Request)
Add Active Storage Overview Guide. (Pull Request)
13. 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. Kudos to all of them.