Rails 5.2 Generate Master Key
Option 2: create a RAILSMASTERKEY ENV variable. Rails will detect it and use it as your master key, e.g. In heroku: heroku config:set RAILSMASTERKEY= your-master-key-here. $ heroku config:set RAILSMASTERKEY=your-master-key Example: $ heroku config:set RAILSMASTERKEY=123456789 (The are placeholders) Rails will detect this variable and use it as your master key (instead of looking for it in master.key file).
- Rails 5.2 Generate Master Key Chain
- Rails Generate Controller
- Rails 5.2 Generate Master Key Lock
- Rails Generate Model Foreign Key
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 with Webpack, a JavaScriptasset bundler, more easily using the new Webpackergem. 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 featureslike data-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 the sekrets gem.
Run bin/rails secrets:setup to setup 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.
2.7 Direct & resolved routes
Rails 5.1 adds two new methods, resolve and direct, to the routingDSL. The resolve method allows customizing polymorphic mapping of models.
This will generate the singular URL /basket instead of the usual /baskets/:id.
The direct method allows creation of custom URL helpers.
The return value of the block must be a valid argument for the url_formethod. So, you can pass a valid string URL, Hash, Array, anActive Model instance, or an Active Model class.
2.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 and form_tag for custom URLs.
Rails 5.1 combines both of these interfaces with form_with, andcan generate form tags based on URLs, scopes or models.
Using just a URL:
Adding a scope prefixes the input field names:
Rails 5.2 Generate Master Key Chain
Using a model infers both the URL and scope:
An existing model makes an update form and fills out field values:
3 Incompatibilities
The following changes may require immediate action upon upgrade.
3.1 Transactional tests with multiple connections
Rails Generate Controller
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 the Changelog 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 the Changelog 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 the Changelog 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 the Changelog 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 the Changelog 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 the Changelog 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 the Changelog 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 the Changelog 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 the Changelog 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.
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 on the rubyonrails-docs mailing list.
1 Upgrading to Rails 5.2
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.1 in case youhaven't and make sure your application still runs as expected before attemptingan update to Rails 5.2. A list of things to watch out for when upgrading isavailable in theUpgrading Ruby on Railsguide.
2 Major Features
2.1 Active Storage
Active Storagefacilitates uploading files to a cloud storage service likeAmazon S3, Google Cloud Storage, or Microsoft Azure Storage and attachingthose files to Active Record objects. It comes with a local disk-based servicefor development and testing and supports mirroring files to subordinateservices for backups and migrations.You can read more about Active Storage in theActive 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 theCaching with Rails: An Overviewguide.
2.3 HTTP/2 Early Hints
Rails 5.2 supports HTTP/2 Early Hints.To start the server with Early Hints enabled pass --early-hintsto 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 servicesdirectly in repository encrypted with a key in the config/master.key file orthe RAILS_MASTER_KEY environment variable.This will eventually replace Rails.application.secrets and the encryptedsecrets introduced in Rails 5.1.Furthermore, Rails 5.2opens API underlying Credentials,so you can easily deal with other encrypted configurations, keys, and files.You can read more about this in theSecuring Rails Applicationsguide.
2.5 Content Security Policy
Rails 5.2 ships with a new DSL that allows you to configure aContent Security Policyfor your application. You can configure a global default policy and thenoverride it on a per-resource basis and even use lambdas to inject per-requestvalues into the header such as account subdomains in a multi-tenant application.You can read more about this in theSecuring Rails Applicationsguide.
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 forall 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 applicationsare 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 testenvironments.(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
Generator product key windows 10 pro. 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 keychurn.(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 modernbrowsers.(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-Policiestodefault headers set.(Commit)Changed the system tests to set Puma as default server only when theuser 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 tothe images generated byimage_tag.(Pull Request)
6.3 Notable changes
Add
:jsontype toauto_discovery_link_tagto supportJSON Feeds.(Pull Request)Add
srcsetoption toimage_taghelper.(Pull Request)Fix issues with
field_error_procwrappingoptgroupandselect 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 typecastingan 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 nowreturns all fixtures of this type. Previously this method always returnedan empty array.(Pull Request)
Fix inconsistency with changed attributes when overridingActive 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 migrationswhen the current migration does not exist.(Commit)Respect
SchemaDumper.ignore_tablesin rake tasks fordatabases structure dump.(Pull Request)Add
ActiveRecord::Base#cache_versionto support recyclable cache keys viathe new versioned entries inActiveSupport::Cache. This also means thatActiveRecord::Base#cache_keywill now return a stable key thatdoes 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 transformsthe 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 wasrolledback, the record from the inner transaction would still be markedas persisted. It was fixed by applying the state of the parenttransaction to the child transaction when the parent transaction isrolledback. This will correctly mark records from the inner transactionas not persisted.(Commit)
Fix eager loading/preloading association with scope including joins.(Pull Request)
Prevent errors raised by
sql.active_recordnotification subscribersfrom 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 nativelyrecognize 't' and 'f' as was previously serialized.(Pull Request)
Values constructed using multi-parameter assignment will now use thepost-type-cast value for rendering in single-field form inputs.(Commit)
ApplicationRecordis no longer generated when generating models. If youneed 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 andput 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 raisedwhen lock wait timeout exceeded.(Pull Request)Update payload names for
sql.active_recordinstrumentation to bemore descriptive.(Pull Request)Use given algorithm while removing index from database.(Pull Request)
Passing a
SettoRelation#wherenow behaves the same as passingan 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 numberor 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 raisedwhen statement timeout exceeded.(Pull Request)update_allwill now pass its values toType#castbefore passing them toType#serialize. This means thatupdate_all(foo: 'true')will properlypersist a boolean.(Commit)Require raw SQL fragments to be explicitly marked when used inrelation query methods.(Commit,Commit)
Add
#up_onlyto database migrations for code that is only relevant whenmigrating up, e.g. populating a new column.(Pull Request)Add new error class
QueryCanceledwhich will be raisedwhen canceling statement due to user request.(Pull Request)Don't allow scopes to be defined which conflict with instance methodson
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 consistentwithrelation.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 argumentto 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 valueseven ifORDER BYcolumns include other table's primary key.(Commit)Fix
dependent: :destroyissue for has_one/belongs_to relationship wherethe parent class was getting deleted when the child was not.(Commit)Idle database connections (previously just orphaned connections) are nowperiodically 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 valueisfalse.(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 torecycle 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-isolatedattributes singleton. Primary use case is keeping all the per-requestattributes easily available to the whole system.(Pull Request)#singularizeand#pluralizenow respect uncountables forthe specified locale.(Commit)Add default option to
class_attribute.(Pull Request)Add
Date#prev_occurringandDate#next_occurringto returnspecified 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!consistentwithHashWithIndifferentAccess.(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 thanattempting 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 behaviour 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 raisingArgumentErrorincase 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 customhandling of discard jobs.(Pull Request)
12 Ruby on Rails Guides
Please refer to the Changelog for detailed changes.
12.1 Notable changes
AddThreading and Code Execution in RailsGuide.(Pull Request)
Add Active Storage Overview Guide.(Pull Request)
13 Credits
See thefull list of contributors to Railsfor the many people who spent many hours making Rails, the stable and robustframework it is. Kudos to all of them.
Feedback
You're encouraged to help improve the quality of this guide.
Rails 5.2 Generate Master Key Lock
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.
Rails Generate Model Foreign Key
And last but not least, any kind of discussion regarding Ruby on Rails documentation is very welcome on the rubyonrails-docs mailing list.