Rails 5 Generate Secret Key
- Rails 5 Generate Secret Key Card
- Rails Generate Model Reference
- Rails Generate View
- Rails Generate Model
- Rails 5 Generate Secret Key Review
- Rails Generate Secret
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
- Jcoyne changed the title Missing devise secret key with Rails 5.2.0.beta1 Missing devise secret key with Rails 5.2.0.beta2 Nov 28, 2017 gencer added a commit to gencer/devise that referenced this issue Nov 30, 2017.
- Message verifiers can be used to generate and verify signed messages. This can be useful to safely transport sensitive data like remember-me tokens and friends. The method Rails.application.messageverifier returns a new message verifier that signs messages with a key derived from secretkeybase and the given message verifier name.
- Mar 26, 2018 The second file, config/master.key, is the file where your RAILSMASTERKEY will be placed. The RAILSMASTERKEY is the key that Rails will use to decrypt your config/credentials.yml.enc.
- Ruby-on-rails - generate - rails secret key base rails 5 Answering my own question - secrettoken is used to prevent cookie tampering in Rails. Every cookie has a checksum saved with it, so users won't modify cookie contents (and change saved user id to steal someone's account, for example).
Dec 22, 2017 Rails 5.1 introduced Encrypted Secrets to help simplify the management of your application secrets (things such as service credentials and the secretkeybase). This article details the feature and its usage. Why Encrypted Secrets? Since Rails 4.1, the framework has given you the ability to centrally store secrets in the config/secrets.yml file.
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
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)
The Sims 4 City Living CD Key GeneratorWelcome back to our portal, to day we will discuss about The Sims 4 City Living CD Key Generator,a new key generator for one of the newest version of, City Living version. We offer this keygen, for free, a full database of working keys. Sims 4 city living key generator. You’ve never seen a city like this in The Sims! The generator was meant to generate key codes for: Windows/PC, Xbox 360/ONE and Playstation 3/4.The Sims 4 City Living is set in the rich, diverse city of San Myshuno, a beautiful coastal city tucked up against the nearby mountains.
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.
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.
Rails 5 Generate Secret Key Card
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 4.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 4.0 in case youhaven't and make sure your application still runs as expected before attemptingan update to Rails 4.1. A list of things to watch out for when upgrading isavailable in theUpgrading Ruby on Railsguide.
2 Major Features
2.1 Spring Application Preloader
Spring is a Rails application preloader. It speeds up development by keepingyour application running in the background so you don't need to boot it everytime you run a test, rake task or migration.
New Rails 4.1 applications will ship with 'springified' binstubs. This meansthat bin/rails and bin/rake will automatically take advantage of preloadedspring environments.
Running rake tasks:
Running a Rails command:
Spring introspection:
Have a look at theSpring README tosee all available features.
See the Upgrading Ruby on Railsguide on how to migrate existing applications to use this feature.
2.2 config/secrets.yml
Rails 4.1 generates a new secrets.yml file in the config folder. By default,this file contains the application's secret_key_base, but it could also beused to store other secrets such as access keys for external APIs.
The secrets added to this file are accessible via Rails.application.secrets.For example, with the following config/secrets.yml:
Rails.application.secrets.some_api_key returns SOMEKEY in the developmentenvironment.
See the Upgrading Ruby on Railsguide on how to migrate existing applications to use this feature.
2.3 Action Pack Variants
We often want to render different HTML/JSON/XML templates for phones,tablets, and desktop browsers. Variants make it easy.
The request variant is a specialization of the request format, like :tablet,:phone, or :desktop.
You can set the variant in a before_action:
Respond to variants in the action just like you respond to formats:
Provide separate templates for each format and variant:
You can also simplify the variants definition using the inline syntax:
2.4 Action Mailer Previews
Action Mailer previews provide a way to see how emails look by visitinga special URL that renders them.
You implement a preview class whose methods return the mail object you'd liketo check:
The preview is available in http://localhost:3000/rails/mailers/notifier/welcome,and a list of them in http://localhost:3000/rails/mailers.
By default, these preview classes live in test/mailers/previews.This can be configured using the preview_path option.
See itsdocumentationfor a detailed write up.
2.5 Active Record enums
Declare an enum attribute where the values map to integers in the database, butcan be queried by name.
See itsdocumentationfor a detailed write up.
2.6 Message Verifiers
Message verifiers can be used to generate and verify signed messages. This canbe useful to safely transport sensitive data like remember-me tokens andfriends.
The method Rails.application.message_verifier returns a new message verifierthat signs messages with a key derived from secret_key_base and the givenmessage verifier name:
Rails Generate Model Reference
2.7 Module#concerning
A natural, low-ceremony way to separate responsibilities within a class:
This example is equivalent to defining a EventTracking module inline,extending it with ActiveSupport::Concern, then mixing it in to theTodo class.
See itsdocumentationfor a detailed write up and the intended use cases.
2.8 CSRF protection from remote <script> tags
Cross-site request forgery (CSRF) protection now covers GET requests withJavaScript responses, too. That prevents a third-party site from referencingyour JavaScript URL and attempting to run it to extract sensitive data.
This means any of your tests that hit .js URLs will now fail CSRF protectionunless they use xhr. Upgrade your tests to be explicit about expectingXmlHttpRequests. Instead of post :create, format: :js, switch to the explicitxhr :post, :create, format: :js.
3 Railties
Please refer to theChangelogfor detailed changes.
3.1 Removals
Removed
update:application_controllerrake task.Removed deprecated
Rails.application.railties.engines.Removed deprecated
threadsafe!from Rails Config.Removed deprecated
ActiveRecord::Generators::ActiveModel#update_attributesinfavor ofActiveRecord::Generators::ActiveModel#update.Removed deprecated
config.whiny_nilsoption.Removed deprecated rake tasks for running tests:
rake test:uncommittedandrake test:recent.
3.2 Notable changes
The Spring applicationpreloader is now installedby default for new applications. It uses the development group ofthe
Gemfile, so will not be installed inproduction. (Pull Request)BACKTRACEenvironment variable to show unfiltered backtraces for testfailures. (Commit)Exposed
MiddlewareStack#unshiftto environmentconfiguration. (Pull Request)Added
Application#message_verifiermethod to return a messageverifier. (Pull Request)The
test_help.rbfile which is required by the default generated testhelper will automatically keep your test database up-to-date withdb/schema.rb(ordb/structure.sql). It raises an error ifreloading the schema does not resolve all pending migrations. Opt outwithconfig.active_record.maintain_test_schema = false. (PullRequest)Introduce
Rails.gem_versionas a convenience method to returnGem::Version.new(Rails.version), suggesting a more reliable way to performversion comparison. (Pull Request)
4 Action Pack
Please refer to theChangelogfor detailed changes.
4.1 Removals
Removed deprecated Rails application fallback for integration testing, set
ActionDispatch.test_appinstead.Removed deprecated
page_cache_extensionconfig.Removed deprecated
ActionController::RecordIdentifier, useActionView::RecordIdentifierinstead.Removed deprecated constants from Action Controller:
Rails Generate View
| Removed | Successor |
|---|---|
| ActionController::AbstractRequest | ActionDispatch::Request |
| ActionController::Request | ActionDispatch::Request |
| ActionController::AbstractResponse | ActionDispatch::Response |
| ActionController::Response | ActionDispatch::Response |
| ActionController::Routing | ActionDispatch::Routing |
| ActionController::Integration | ActionDispatch::Integration |
| ActionController::IntegrationTest | ActionDispatch::IntegrationTest |
Rails Generate Model
4.2 Notable changes
protect_from_forgeryalso prevents cross-origin<script>tags.Update your tests to usexhr :get, :foo, format: :jsinstead ofget :foo, format: :js.(Pull Request)#url_fortakes a hash with options inside anarray. (Pull Request)Added
session#fetchmethod fetch behaves similarly toHash#fetch,with the exception that the returned value is always saved into thesession. (Pull Request)Separated Action View completely from ActionPack. (Pull Request)
Log which keys were affected by deepmunge. (Pull Request)
New config option
config.action_dispatch.perform_deep_mungeto opt out ofparams 'deep munging' that was used to address security vulnerabilityCVE-2013-0155. (Pull Request)New config option
config.action_dispatch.cookies_serializerfor specifying aserializer for the signed and encrypted cookie jars. (Pull Requests1,2 /More Details)Added
render :plain,render :htmlandrender:body. (Pull Request /More Details)
5 Action Mailer
Please refer to theChangelogfor detailed changes.
5.1 Notable changes
Added mailer previews feature based on 37 Signals mail_viewgem. (Commit)
Instrument the generation of Action Mailer messages. The time it takes togenerate a message is written to the log. (Pull Request)
6 Active Record
Please refer to theChangelogfor detailed changes.
6.1 Removals
Removed deprecated nil-passing to the following
SchemaCachemethods:primary_keys,tables,columnsandcolumns_hash.Removed deprecated block filter from
ActiveRecord::Migrator#migrate.Removed deprecated String constructor from
ActiveRecord::Migrator.Removed deprecated
scopeuse without passing a callable object.Removed deprecated
transaction_joinable=in favor ofbegin_transactionwith a:joinableoption.Removed deprecated
decrement_open_transactions.Removed deprecated
increment_open_transactions.Removed deprecated
PostgreSQLAdapter#outside_transaction?method. You can use#transaction_open?instead.Removed deprecated
ActiveRecord::Fixtures.find_table_namein favor ofActiveRecord::Fixtures.default_fixture_model_name.Removed deprecated
columns_for_removefromSchemaStatements.Removed deprecated
SchemaStatements#distinct.Moved deprecated
ActiveRecord::TestCaseinto the Rails testsuite. The class is no longer public and is only used for internalRails tests.Removed support for deprecated option
:restrictfor:dependentin associations.Removed support for deprecated
:delete_sql,:insert_sql,:finder_sqland:counter_sqloptions in associations.Removed deprecated method
type_cast_codefrom Column.Removed deprecated
ActiveRecord::Base#connectionmethod.Make sure to access it via the class.Removed deprecation warning for
auto_explain_threshold_in_seconds.Removed deprecated
:distinctoption fromRelation#count.Removed deprecated methods
partial_updates,partial_updates?andpartial_updates=.Removed deprecated method
scoped.Removed deprecated method
default_scopes?.Remove implicit join references that were deprecated in 4.0.
Removed
activerecord-deprecated_findersas a dependency.Please see the gem READMEfor more info.Removed usage of
implicit_readonly. Please usereadonlymethodexplicitly to mark records asreadonly. (Pull Request)
6.2 Deprecations
Deprecated
quoted_locking_columnmethod, which isn't used anywhere.Deprecated
ConnectionAdapters::SchemaStatements#distinct,as it is no longer used by internals. (Pull Request)Deprecated
rake db:test:*tasks as the test database is nowautomatically maintained. See railties release notes. (PullRequest)Deprecate unused
ActiveRecord::Base.symbolized_base_classandActiveRecord::Base.symbolized_sti_namewithoutreplacement. Commit
6.3 Notable changes
- Default scopes are no longer overridden by chained conditions.
Before this change when you defined a default_scope in a model it was overridden by chained conditions in the same field. Now it is merged like any other scope. More Details.
Added
ActiveRecord::Base.to_paramfor convenient 'pretty' URLs derived froma model's attribute ormethod. (Pull Request)Added
ActiveRecord::Base.no_touching, which allows ignoring touch onmodels. (Pull Request)Unify boolean type casting for
MysqlAdapterandMysql2Adapter.type_castwill return1fortrueand0forfalse. (Pull Request).unscopenow removes conditions specified indefault_scope. (Commit)Added
ActiveRecord::QueryMethods#rewherewhich will overwrite an existing,named where condition. (Commit)Extended
ActiveRecord::Base#cache_keyto take an optional list of timestampattributes of which the highest will be used. (Commit)Added
ActiveRecord::Base#enumfor declaring enum attributes where the valuesmap to integers in the database, but can be queried byname. (Commit)Type cast json values on write, so that the value is consistent with readingfrom the database. (Pull Request)
Type cast hstore values on write, so that the value is consistentwith reading from the database. (Commit)
Make
next_migration_numberaccessible for third partygenerators. (Pull Request)Calling
update_attributeswill now throw anArgumentErrorwhenever itgets anilargument. More specifically, it will throw an error if theargument that it gets passed does not respond to tostringify_keys. (Pull Request)CollectionAssociation#first/#last(e.g.has_many) use aLIMITedquery to fetch results rather than loading the entirecollection. (Pull Request)inspectRome total war cd key generator download. on Active Record model classes does not initiate a newconnection. This means that callinginspect, when the database is missing,will no longer raise an exception. (Pull Request)Removed column restrictions for
count, let the database raise if the SQL isinvalid. (Pull Request)Rails now automatically detects inverse associations. If you do not set the
:inverse_ofoption on the association, then Active Record will guess theinverse association based on heuristics. (Pull Request)Handle aliased attributes in ActiveRecord::Relation. When using symbol keys,ActiveRecord will now translate aliased attribute names to the actual columnname used in the database. (Pull Request)
The ERB in fixture files is no longer evaluated in the context of the mainobject. Helper methods used by multiple fixtures should be defined on modulesincluded in
ActiveRecord::FixtureSet.context_class. (Pull Request)Don't create or drop the test database if RAILS_ENV is specifiedexplicitly. (Pull Request)
Relationno longer has mutator methods like#map!and#delete_if. Convertto anArrayby calling#to_abefore using these methods. (Pull Request)find_in_batches,find_each,Result#eachandEnumerable#index_bynowreturn anEnumeratorthat can calculate itssize. (Pull Request)scope,enumand Associations now raise on 'dangerous' nameconflicts. (Pull Request,Pull Request)secondthroughfifthmethods act like thefirstfinder. (Pull Request)Make
touchfire theafter_commitandafter_rollbackcallbacks. (Pull Request)Enable partial indexes for
sqlite >= 3.8.0.(Pull Request)Make
change_column_nullrevertible. (Commit)Added a flag to disable schema dump after migration. This is set to
falseby default in the production environment for new applications.(Pull Request)
7 Active Model
Please refer to theChangelogfor detailed changes.
7.1 Deprecations
- Deprecate
Validator#setup. This should be done manually now in thevalidator's constructor. (Commit)
7.2 Notable changes
Added new API methods
reset_changesandchanges_appliedtoActiveModel::Dirtythat control changes state.Ability to specify multiple contexts when defining avalidation. (Pull Request)
attribute_changed?now accepts a hash to check if the attribute was changed:fromand/or:toa givenvalue. (Pull Request)
8 Active Support
Please refer to theChangelogfor detailed changes.
8.1 Removals
Rails 5 Generate Secret Key Review
Removed
MultiJSONdependency. As a result,ActiveSupport::JSON.decodeno longer accepts an options hash forMultiJSON. (Pull Request / More Details)Removed support for the
encode_jsonhook used for encoding custom objects intoJSON. This feature has been extracted into the activesupport-json_encodergem.(Related Pull Request /More Details)Removed deprecated
ActiveSupport::JSON::Variablewith no replacement.Removed deprecated
String#encoding_aware?core extensions (core_ext/string/encoding).Removed deprecated
Module#local_constant_namesin favor ofModule#local_constants.Removed deprecated
DateTime.local_offsetin favor ofDateTime.civil_from_format.Removed deprecated
Loggercore extensions (core_ext/logger.rb).Removed deprecated
Time#time_with_datetime_fallback,Time#utc_timeandTime#local_timein favor ofTime#utcandTime#local.Removed deprecated
Hash#diffwith no replacement.Removed deprecated
Date#to_time_in_current_zonein favor ofDate#in_time_zone.Removed deprecated
Proc#bindwith no replacement.Removed deprecated
Array#uniq_byandArray#uniq_by!, use nativeArray#uniqandArray#uniq!instead.Removed deprecated
ActiveSupport::BasicObject, useActiveSupport::ProxyObjectinstead.Removed deprecated
BufferedLogger, useActiveSupport::Loggerinstead.Removed deprecated
assert_presentandassert_blankmethods, useassertobject.blank?andassert object.present?instead.Remove deprecated
#filtermethod for filter objects, use the correspondingmethod instead (e.g.#beforefor a before filter).Removed 'cow' => 'kine' irregular inflection from defaultinflections. (Commit)
8.2 Deprecations
Deprecated
Numeric#{ago,until,since,from_now}, the user is expected toexplicitly convert the value into an AS::Duration, i.e.5.ago=>5.seconds.ago(Pull Request)Deprecated the require path
active_support/core_ext/object/to_json. Requireactive_support/core_ext/object/jsoninstead. (Pull Request)Deprecated
ActiveSupport::JSON::Encoding::CircularReferenceError. This featurehas been extracted into the activesupport-json_encodergem.(Pull Request /More Details)Deprecated
ActiveSupport.encode_big_decimal_as_stringoption. This feature hasbeen extracted into the activesupport-json_encodergem.(Pull Request /More Details)Deprecate custom
BigDecimalserialization. (Pull Request)
8.3 Notable changes
ActiveSupport's JSON encoder has been rewritten to take advantage of theJSON gem rather than doing custom encoding in pure-Ruby.(Pull Request /More Details)Improved compatibility with the JSON gem.(Pull Request /More Details)
Added
ActiveSupport::Testing::TimeHelpers#traveland#travel_to. Thesemethods change current time to the given time or duration by stubbingTime.nowandDate.today.Added
ActiveSupport::Testing::TimeHelpers#travel_back. This method returnsthe current time to the original state, by removing the stubs added bytravelandtravel_to. (Pull Request)Added
Numeric#in_milliseconds, like1.hour.in_milliseconds, so we can feedthem to JavaScript functions likegetTime(). (Commit)Added
Date#middle_of_day,DateTime#middle_of_dayandTime#middle_of_daymethods. Also addedmidday,noon,at_midday,at_noonandat_middle_of_dayasaliases. (Pull Request)Added
Date#all_week/month/quarter/yearfor generating dateranges. (Pull Request)Added
Time.zone.yesterdayandTime.zone.tomorrow. (Pull Request)Added
String#remove(pattern)as a short-hand for the common pattern ofString#gsub(pattern,'). (Commit)Added
Hash#compactandHash#compact!for removing items with nil valuefrom hash. (Pull Request)blank?andpresent?commit to returnsingletons. (Commit)Default the new
I18n.enforce_available_localesconfig totrue, meaningI18nwill make sure that all locales passed to it must be declared in theavailable_localeslist. (Pull Request)Introduce
Module#concerning: a natural, low-ceremony way to separateresponsibilities within aclass. (Commit)Added
Object#presence_into simplify adding values to a permitted list.(Commit)
9 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.
Rails Generate Secret
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.