diff options
Diffstat (limited to 'guides/source')
29 files changed, 660 insertions, 304 deletions
diff --git a/guides/source/2_3_release_notes.md b/guides/source/2_3_release_notes.md index f85415ee42..ee9a499953 100644 --- a/guides/source/2_3_release_notes.md +++ b/guides/source/2_3_release_notes.md @@ -52,7 +52,7 @@ After some versions without an upgrade, Rails 2.3 offers some new features for R Documentation ------------- -The [Ruby on Rails guides](https://guides.rubyonrails.org/) project has published several additional guides for Rails 2.3. In addition, a [separate site](http://edgeguides.rubyonrails.org/) maintains updated copies of the Guides for Edge Rails. Other documentation efforts include a relaunch of the [Rails wiki](http://newwiki.rubyonrails.org/) and early planning for a Rails Book. +The [Ruby on Rails guides](https://guides.rubyonrails.org/) project has published several additional guides for Rails 2.3. In addition, a [separate site](https://edgeguides.rubyonrails.org/) maintains updated copies of the Guides for Edge Rails. Other documentation efforts include a relaunch of the [Rails wiki](http://newwiki.rubyonrails.org/) and early planning for a Rails Book. * More Information: [Rails Documentation Projects](https://weblog.rubyonrails.org/2009/1/15/rails-documentation-projects) diff --git a/guides/source/3_0_release_notes.md b/guides/source/3_0_release_notes.md index 9d15dfb2aa..e793146c2c 100644 --- a/guides/source/3_0_release_notes.md +++ b/guides/source/3_0_release_notes.md @@ -153,7 +153,7 @@ More information: - [New Action Mailer API in Rails 3](http://lindsaar.net/2010/ Documentation ------------- -The documentation in the Rails tree is being updated with all the API changes, additionally, the [Rails Edge Guides](http://edgeguides.rubyonrails.org/) are being updated one by one to reflect the changes in Rails 3.0. The guides at [guides.rubyonrails.org](https://guides.rubyonrails.org/) however will continue to contain only the stable version of Rails (at this point, version 2.3.5, until 3.0 is released). +The documentation in the Rails tree is being updated with all the API changes, additionally, the [Rails Edge Guides](https://edgeguides.rubyonrails.org/) are being updated one by one to reflect the changes in Rails 3.0. The guides at [guides.rubyonrails.org](https://guides.rubyonrails.org/) however will continue to contain only the stable version of Rails (at this point, version 2.3.5, until 3.0 is released). More Information: - [Rails Documentation Projects](https://weblog.rubyonrails.org/2009/1/15/rails-documentation-projects) diff --git a/guides/source/4_0_release_notes.md b/guides/source/4_0_release_notes.md index eaae695dff..c9bc7f937b 100644 --- a/guides/source/4_0_release_notes.md +++ b/guides/source/4_0_release_notes.md @@ -70,7 +70,7 @@ Major Features ### ActionPack -* **Strong parameters** ([commit](https://github.com/rails/rails/commit/a8f6d5c6450a7fe058348a7f10a908352bb6c7fc)) - Only allow whitelisted parameters to update model objects (`params.permit(:title, :text)`). +* **Strong parameters** ([commit](https://github.com/rails/rails/commit/a8f6d5c6450a7fe058348a7f10a908352bb6c7fc)) - Only allow permitted parameters to update model objects (`params.permit(:title, :text)`). * **Routing concerns** ([commit](https://github.com/rails/rails/commit/0dd24728a088fcb4ae616bb5d62734aca5276b1b)) - In the routing DSL, factor out common subroutes (`comments` from `/posts/1/comments` and `/videos/1/comments`). * **ActionController::Live** ([commit](https://github.com/rails/rails/commit/af0a9f9eefaee3a8120cfd8d05cbc431af376da3)) - Stream JSON with `response.stream`. * **Declarative ETags** ([commit](https://github.com/rails/rails/commit/ed5c938fa36995f06d4917d9543ba78ed506bb8d)) - Add controller-level etag additions that will be part of the action etag computation. @@ -196,7 +196,7 @@ Please refer to the [Changelog](https://github.com/rails/rails/blob/4-0-stable/a ### Deprecations -* Deprecate `ActiveSupport::TestCase#pending` method, use `skip` from MiniTest instead. +* Deprecate `ActiveSupport::TestCase#pending` method, use `skip` from minitest instead. * `ActiveSupport::Benchmarkable#silence` has been deprecated due to its lack of thread safety. It will be removed without replacement in Rails 4.1. diff --git a/guides/source/4_1_release_notes.md b/guides/source/4_1_release_notes.md index 0c7bd01cac..b236f7ca24 100644 --- a/guides/source/4_1_release_notes.md +++ b/guides/source/4_1_release_notes.md @@ -719,7 +719,7 @@ for detailed changes. responsibilities within a class. ([Commit](https://github.com/rails/rails/commit/1eee0ca6de975b42524105a59e0521d18b38ab81)) -* Added `Object#presence_in` to simplify value whitelisting. +* Added `Object#presence_in` to simplify adding values to a permitted list. ([Commit](https://github.com/rails/rails/commit/4edca106daacc5a159289eae255207d160f22396)) diff --git a/guides/source/5_0_release_notes.md b/guides/source/5_0_release_notes.md index e57ef03518..d63921507d 100644 --- a/guides/source/5_0_release_notes.md +++ b/guides/source/5_0_release_notes.md @@ -169,7 +169,7 @@ It includes some of these notable advancements: instead of waiting for the suite to complete. - Defer test output until the end of a full test run using the `-d` option. - Complete exception backtrace output using `-b` option. -- Integration with `Minitest` to allow options like `-s` for test seed data, +- Integration with minitest to allow options like `-s` for test seed data, `-n` for running specific test by name, `-v` for better verbose output and so forth. - Colored test output. diff --git a/guides/source/6_0_release_notes.md b/guides/source/6_0_release_notes.md new file mode 100644 index 0000000000..f3ed21dc45 --- /dev/null +++ b/guides/source/6_0_release_notes.md @@ -0,0 +1,175 @@ +**DO NOT READ THIS FILE ON GITHUB, GUIDES ARE PUBLISHED ON https://guides.rubyonrails.org.** + +Ruby on Rails 6.0 Release Notes +=============================== + +Highlights in Rails 6.0: + +* Parallel Testing + +These release notes cover only the major changes. To learn about various bug +fixes and changes, please refer to the change logs or check out the [list of +commits](https://github.com/rails/rails/commits/6-0-stable) in the main Rails +repository on GitHub. + +-------------------------------------------------------------------------------- + +Upgrading to Rails 6.0 +---------------------- + +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.2 in case you +haven't and make sure your application still runs as expected before attempting +an update to Rails 6.0. A list of things to watch out for when upgrading is +available in the +[Upgrading Ruby on Rails](upgrading_ruby_on_rails.html#upgrading-from-rails-5-2-to-rails-6-0) +guide. + +Major Features +-------------- + +### Parallel Testing + +[Pull Request](https://github.com/rails/rails/pull/31900) + +[Parallel Testing](testing.html#parallel-testing) allows you to parallelize your +test suite. While forking processes is the default method, threading is +supported as well. Running tests in parallel reduces the time it takes +your entire test suite to run. + +Railties +-------- + +Please refer to the [Changelog][railties] for detailed changes. + +### Removals + +### Deprecations + +### Notable changes + +Action Cable +------------ + +Please refer to the [Changelog][action-cable] for detailed changes. + +### Removals + +### Deprecations + +### Notable changes + +Action Pack +----------- + +Please refer to the [Changelog][action-pack] for detailed changes. + +### Removals + +### Deprecations + +### Notable changes + +Action View +----------- + +Please refer to the [Changelog][action-view] for detailed changes. + +### Removals + +### Deprecations + +### Notable changes + +Action Mailer +------------- + +Please refer to the [Changelog][action-mailer] for detailed changes. + +### Removals + +### Deprecations + +### Notable changes + +Active Record +------------- + +Please refer to the [Changelog][active-record] for detailed changes. + +### Removals + +### Deprecations + +### Notable changes + +Active Storage +-------------- + +Please refer to the [Changelog][active-storage] for detailed changes. + +### Removals + +### Deprecations + +### Notable changes + +Active Model +------------ + +Please refer to the [Changelog][active-model] for detailed changes. + +### Removals + +### Deprecations + +### Notable changes + +Active Support +-------------- + +Please refer to the [Changelog][active-support] for detailed changes. + +### Removals + +### Deprecations + +### Notable changes + +Active Job +---------- + +Please refer to the [Changelog][active-job] for detailed changes. + +### Removals + +### Deprecations + +### Notable changes + +Ruby on Rails Guides +-------------------- + +Please refer to the [Changelog][guides] for detailed changes. + +### Notable changes + +Credits +------- + +See the +[full list of contributors to Rails](http://contributors.rubyonrails.org/) +for the many people who spent many hours making Rails, the stable and robust +framework it is. Kudos to all of them. + +[railties]: https://github.com/rails/rails/blob/6-0-stable/railties/CHANGELOG.md +[action-pack]: https://github.com/rails/rails/blob/6-0-stable/actionpack/CHANGELOG.md +[action-view]: https://github.com/rails/rails/blob/6-0-stable/actionview/CHANGELOG.md +[action-mailer]: https://github.com/rails/rails/blob/6-0-stable/actionmailer/CHANGELOG.md +[action-cable]: https://github.com/rails/rails/blob/6-0-stable/actioncable/CHANGELOG.md +[active-record]: https://github.com/rails/rails/blob/6-0-stable/activerecord/CHANGELOG.md +[active-storage]: https://github.com/rails/rails/blob/6-0-stable/activestorage/CHANGELOG.md +[active-model]: https://github.com/rails/rails/blob/6-0-stable/activemodel/CHANGELOG.md +[active-support]: https://github.com/rails/rails/blob/6-0-stable/activesupport/CHANGELOG.md +[active-job]: https://github.com/rails/rails/blob/6-0-stable/activejob/CHANGELOG.md +[guides]: https://github.com/rails/rails/blob/6-0-stable/guides/CHANGELOG.md diff --git a/guides/source/action_controller_overview.md b/guides/source/action_controller_overview.md index 7ce1f5c2a3..43bc9306ce 100644 --- a/guides/source/action_controller_overview.md +++ b/guides/source/action_controller_overview.md @@ -193,8 +193,8 @@ In a given request, the method is not actually called for every single generated With strong parameters, Action Controller parameters are forbidden to be used in Active Model mass assignments until they have been -whitelisted. This means that you'll have to make a conscious decision about -which attributes to allow for mass update. This is a better security +permitted. This means that you'll have to make a conscious decision about +which attributes to permit for mass update. This is a better security practice to help prevent accidentally allowing users to update sensitive model attributes. @@ -241,7 +241,7 @@ Given params.permit(:id) ``` -the key `:id` will pass the whitelisting if it appears in `params` and +the key `:id` will be permitted for inclusion if it appears in `params` and it has a permitted scalar value associated. Otherwise, the key is going to be filtered out, so arrays, hashes, or any other objects cannot be injected. @@ -269,7 +269,7 @@ but be careful because this opens the door to arbitrary input. In this case, `permit` ensures values in the returned structure are permitted scalars and filters out anything else. -To whitelist an entire hash of parameters, the `permit!` method can be +To permit an entire hash of parameters, the `permit!` method can be used: ```ruby @@ -291,7 +291,7 @@ params.permit(:name, { emails: [] }, { family: [ :name ], hobbies: [] }]) ``` -This declaration whitelists the `name`, `emails`, and `friends` +This declaration permits the `name`, `emails`, and `friends` attributes. It is expected that `emails` will be an array of permitted scalar values, and that `friends` will be an array of resources with specific attributes: they should have a `name` attribute (any @@ -326,7 +326,7 @@ parameters when you use `accepts_nested_attributes_for` in combination with a `has_many` association: ```ruby -# To whitelist the following data: +# To permit the following data: # {"book" => {"title" => "Some Book", # "chapters_attributes" => { "1" => {"title" => "First Chapter"}, # "2" => {"title" => "Second Chapter"}}}} @@ -336,7 +336,7 @@ params.require(:book).permit(:title, chapters_attributes: [:title]) Imagine a scenario where you have parameters representing a product name and a hash of arbitrary data associated with that product, and -you want to whitelist the product name attribute and also the whole +you want to permit the product name attribute and also the whole data hash: ```ruby @@ -349,7 +349,7 @@ end The strong parameter API was designed with the most common use cases in mind. It is not meant as a silver bullet to handle all of your -whitelisting problems. However, you can easily mix the API with your +parameter filtering problems. However, you can easily mix the API with your own code to adapt to your situation. Session diff --git a/guides/source/action_mailer_basics.md b/guides/source/action_mailer_basics.md index 6c5f03ab38..041a427f7c 100644 --- a/guides/source/action_mailer_basics.md +++ b/guides/source/action_mailer_basics.md @@ -422,6 +422,21 @@ use the rendered text for the text part. The render command is the same one used inside of Action Controller, so you can use all the same options, such as `:text`, `:inline` etc. +If you would like to render a template located outside of the default `app/views/mailer_name/` directory, you can apply the `prepend_view_path`, like so: + +```ruby +class UserMailer < ApplicationMailer + prepend_view_path "custom/path/to/mailer/view" + + # This will try to load "custom/path/to/mailer/view/welcome_email" template + def welcome_email + # ... + end +end +``` + +You can also consider using the [append_view_path](https://guides.rubyonrails.org/action_view_overview.html#view-paths) method. + #### Caching mailer view You can perform fragment caching in mailer views like in application views using the `cache` method. @@ -772,7 +787,7 @@ files (environment.rb, production.rb, etc...) |`sendmail_settings`|Allows you to override options for the `:sendmail` delivery method.<ul><li>`:location` - The location of the sendmail executable. Defaults to `/usr/sbin/sendmail`.</li><li>`:arguments` - The command line arguments to be passed to sendmail. Defaults to `-i`.</li></ul>| |`raise_delivery_errors`|Whether or not errors should be raised if the email fails to be delivered. This only works if the external email server is configured for immediate delivery.| |`delivery_method`|Defines a delivery method. Possible values are:<ul><li>`:smtp` (default), can be configured by using `config.action_mailer.smtp_settings`.</li><li>`:sendmail`, can be configured by using `config.action_mailer.sendmail_settings`.</li><li>`:file`: save emails to files; can be configured by using `config.action_mailer.file_settings`.</li><li>`:test`: save emails to `ActionMailer::Base.deliveries` array.</li></ul>See [API docs](http://api.rubyonrails.org/classes/ActionMailer/Base.html) for more info.| -|`perform_deliveries`|Determines whether deliveries are actually carried out when the `deliver` method is invoked on the Mail message. By default they are, but this can be turned off to help functional testing.| +|`perform_deliveries`|Determines whether deliveries are actually carried out when the `deliver` method is invoked on the Mail message. By default they are, but this can be turned off to help functional testing. If this value is `false`, `deliveries` array will not be populated even if `delivery_method` is `:test`.| |`deliveries`|Keeps an array of all the emails sent out through the Action Mailer with delivery_method :test. Most useful for unit and functional testing.| |`default_options`|Allows you to set default values for the `mail` method options (`:from`, `:reply_to`, etc.).| diff --git a/guides/source/active_record_callbacks.md b/guides/source/active_record_callbacks.md index 5b06ff78bb..5946acb412 100644 --- a/guides/source/active_record_callbacks.md +++ b/guides/source/active_record_callbacks.md @@ -319,6 +319,14 @@ class Order < ApplicationRecord end ``` +As the proc is evaluated in the context of the object, it is also possible to write this as: + +```ruby +class Order < ApplicationRecord + before_save :normalize_card_number, if: Proc.new { paid_with_card? } +end +``` + ### Multiple Conditions for Callbacks When writing conditional callbacks, it is possible to mix both `:if` and `:unless` in the same callback declaration: diff --git a/guides/source/active_record_migrations.md b/guides/source/active_record_migrations.md index cfa444fda0..4d195988f8 100644 --- a/guides/source/active_record_migrations.md +++ b/guides/source/active_record_migrations.md @@ -491,6 +491,9 @@ NOTE: Active Record only supports single column foreign keys. `execute` and `structure.sql` are required to use composite foreign keys. See [Schema Dumping and You](#schema-dumping-and-you). +NOTE: The SQLite3 adapter doesn't support `add_foreign_key` since SQLite supports +only [a limited subset of ALTER TABLE](https://www.sqlite.org/lang_altertable.html). + Removing a foreign key is easy as well: ```ruby @@ -923,9 +926,10 @@ your database schema. It tends to be faster and less error prone to create a new instance of your application's database by loading the schema file via `rails db:schema:load` -than it is to replay the entire migration history. Old migrations may fail to -apply correctly if those migrations use changing external dependencies or rely -on application code which evolves separately from your migrations. +than it is to replay the entire migration history. +[Old migrations](#old-migrations) may fail to apply correctly if those +migrations use changing external dependencies or rely on application code which +evolves separately from your migrations. Schema files are also useful if you want a quick look at what attributes an Active Record object has. This information is not in the model's code and is @@ -1042,3 +1046,21 @@ end This is generally a much cleaner way to set up the database of a blank application. + +Old Migrations +-------------- + +The `db/schema.rb` or `db/structure.sql` is a snapshot of the current state of your +database and is the authoritative source for rebuilding that database. This +makes it possible to delete old migration files. + +When you delete migration files in the `db/migrate/` directory, any environment +where `rails db:migrate` was run when those files still existed will hold a reference +to the migration timestamp specific to them inside an internal Rails database +table named `schema_migrations`. This table is used to keep track of whether +migrations have been executed in a specific environment. + +If you run the `rails db:migrate:status` command, which displays the status +(up or down) of each migration, you should see `********** NO FILE **********` +displayed next to any deleted migration file which was once executed on a +specific environment but can no longer be found in the `db/migrate/` directory. diff --git a/guides/source/active_record_querying.md b/guides/source/active_record_querying.md index a2890b9b7a..91cc175095 100644 --- a/guides/source/active_record_querying.md +++ b/guides/source/active_record_querying.md @@ -1277,16 +1277,6 @@ class Article < ApplicationRecord end ``` -This is exactly the same as defining a class method, and which you use is a matter of personal preference: - -```ruby -class Article < ApplicationRecord - def self.published - where(published: true) - end -end -``` - Scopes are also chainable within scopes: ```ruby diff --git a/guides/source/active_storage_overview.md b/guides/source/active_storage_overview.md index 6933717c2b..1c15d075b9 100644 --- a/guides/source/active_storage_overview.md +++ b/guides/source/active_storage_overview.md @@ -174,7 +174,7 @@ google: Add the [`google-cloud-storage`](https://github.com/GoogleCloudPlatform/google-cloud-ruby/tree/master/google-cloud-storage) gem to your `Gemfile`: ```ruby -gem "google-cloud-storage", "~> 1.8", require: false +gem "google-cloud-storage", "~> 1.11", require: false ``` ### Mirror Service diff --git a/guides/source/active_support_core_extensions.md b/guides/source/active_support_core_extensions.md index dfd21915b0..f9fc7044ba 100644 --- a/guides/source/active_support_core_extensions.md +++ b/guides/source/active_support_core_extensions.md @@ -2156,6 +2156,19 @@ This method is an alias of `Array#<<`. NOTE: Defined in `active_support/core_ext/array/prepend_and_append.rb`. +### Extracting + +The method `extract!` removes and returns the elements for which the block returns a true value. +If no block is given, an Enumerator is returned instead. + +```ruby +numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] +odd_numbers = numbers.extract! { |number| number.odd? } # => [1, 3, 5, 7, 9] +numbers # => [0, 2, 4, 6, 8] +``` + +NOTE: Defined in `active_support/core_ext/array/extract.rb`. + ### Options Extraction When the last argument in a method call is a hash, except perhaps for a `&block` argument, Ruby allows you to omit the brackets: diff --git a/guides/source/active_support_instrumentation.md b/guides/source/active_support_instrumentation.md index 3568c47dd8..69c6a6e414 100644 --- a/guides/source/active_support_instrumentation.md +++ b/guides/source/active_support_instrumentation.md @@ -319,17 +319,18 @@ Action Mailer ### deliver.action_mailer -| Key | Value | -| ------------- | -------------------------------------------- | -| `:mailer` | Name of the mailer class | -| `:message_id` | ID of the message, generated by the Mail gem | -| `:subject` | Subject of the mail | -| `:to` | To address(es) of the mail | -| `:from` | From address of the mail | -| `:bcc` | BCC addresses of the mail | -| `:cc` | CC addresses of the mail | -| `:date` | Date of the mail | -| `:mail` | The encoded form of the mail | +| Key | Value | +| --------------------- | ---------------------------------------------------- | +| `:mailer` | Name of the mailer class | +| `:message_id` | ID of the message, generated by the Mail gem | +| `:subject` | Subject of the mail | +| `:to` | To address(es) of the mail | +| `:from` | From address of the mail | +| `:bcc` | BCC addresses of the mail | +| `:cc` | CC addresses of the mail | +| `:date` | Date of the mail | +| `:mail` | The encoded form of the mail | +| `:perform_deliveries` | Whether delivery of this message is performed or not | ```ruby { @@ -339,7 +340,8 @@ Action Mailer to: ["users@rails.com", "dhh@rails.com"], from: ["me@rails.com"], date: Sat, 10 Mar 2012 14:18:09 +0100, - mail: "..." # omitted for brevity + mail: "...", # omitted for brevity + perform_deliveries: true } ``` @@ -458,6 +460,14 @@ Active Job | `:adapter` | QueueAdapter object processing the job | | `:job` | Job object | +### enqueue_retry.active_job + +| Key | Value | +| ------------ | -------------------------------------- | +| `:job` | Job object | +| `:adapter` | QueueAdapter object processing the job | +| `:error` | The error that caused the retry | + ### perform_start.active_job | Key | Value | @@ -472,6 +482,22 @@ Active Job | `:adapter` | QueueAdapter object processing the job | | `:job` | Job object | +### retry_stopped.active_job + +| Key | Value | +| ------------ | -------------------------------------- | +| `:adapter` | QueueAdapter object processing the job | +| `:job` | Job object | +| `:error` | The error that caused the retry | + +### discard.active_job + +| Key | Value | +| ------------ | -------------------------------------- | +| `:adapter` | QueueAdapter object processing the job | +| `:job` | Job object | +| `:error` | The error that caused the discard | + Action Cable ------------ diff --git a/guides/source/api_documentation_guidelines.md b/guides/source/api_documentation_guidelines.md index 6efd9296dc..b6ee7354f9 100644 --- a/guides/source/api_documentation_guidelines.md +++ b/guides/source/api_documentation_guidelines.md @@ -53,7 +53,7 @@ Documentation has to be concise but comprehensive. Explore and document edge cas The proper names of Rails components have a space in between the words, like "Active Support". `ActiveRecord` is a Ruby module, whereas Active Record is an ORM. All Rails documentation should consistently refer to Rails components by their proper name, and if in your next blog post or presentation you remember this tidbit and take it into account that'd be phenomenal. -Spell names correctly: Arel, Test::Unit, RSpec, HTML, MySQL, JavaScript, ERB. When in doubt, please have a look at some authoritative source like their official documentation. +Spell names correctly: Arel, minitest, RSpec, HTML, MySQL, JavaScript, ERB. When in doubt, please have a look at some authoritative source like their official documentation. Use the article "an" for "SQL", as in "an SQL statement". Also "an SQLite database". diff --git a/guides/source/autoloading_and_reloading_constants.md b/guides/source/autoloading_and_reloading_constants.md index 6298651e4a..b3f923a017 100644 --- a/guides/source/autoloading_and_reloading_constants.md +++ b/guides/source/autoloading_and_reloading_constants.md @@ -1350,3 +1350,34 @@ With the [Spring](https://github.com/rails/spring) pre-loader (included with new Occasionally you may need to explicitly eager_load by using `Rails .application.eager_load!` in the setup of your tests -- this might occur if your [tests involve multithreading](https://stackoverflow.com/questions/25796409/in-rails-how-can-i-eager-load-all-code-before-a-specific-rspec-test). + +## Troubleshooting + +### Tracing Autoloads + +Active Support is able to report constants as they are autoloaded. To enable these traces in a Rails application, put the following two lines in some initializer: + +```ruby +ActiveSupport::Dependencies.logger = Rails.logger +ActiveSupport::Dependencies.verbose = true +``` + +### Where is a Given Autoload Triggered? + +If constant `Foo` is being autoloaded, and you'd like to know where is that autoload coming from, just throw + +```ruby +puts caller +``` + +at the top of `foo.rb` and inspect the printed stack trace. + +### Which Constants Have Been Autoloaded? + +At any given time, + +```ruby +ActiveSupport::Dependencies.autoloaded_constants +``` + +has the collection of constants that have been autoloaded so far. diff --git a/guides/source/command_line.md b/guides/source/command_line.md index 2f07417316..7fa0a49203 100644 --- a/guides/source/command_line.md +++ b/guides/source/command_line.md @@ -546,7 +546,7 @@ vendor/tools.rb: INFO: A good description of unit testing in Rails is given in [A Guide to Testing Rails Applications](testing.html) -Rails comes with a test suite called Minitest. Rails owes its stability to the use of tests. The commands available in the `test:` namespace helps in running the different tests you will hopefully write. +Rails comes with a test framework called minitest. Rails owes its stability to the use of tests. The commands available in the `test:` namespace helps in running the different tests you will hopefully write. ### `rails tmp:` diff --git a/guides/source/configuring.md b/guides/source/configuring.md index 6e4f1f9648..4c508f77f1 100644 --- a/guides/source/configuring.md +++ b/guides/source/configuring.md @@ -104,7 +104,7 @@ application. Accepts a valid week day symbol (e.g. `:monday`). * `config.filter_parameters` used for filtering out the parameters that you don't want shown in the logs, such as passwords or credit card -numbers. By default, Rails filters out passwords by adding `Rails.application.config.filter_parameters += [:password]` in `config/initializers/filter_parameter_logging.rb`. Parameters filter works by partial matching regular expression. +numbers. It also filters out sensitive values of database columns when call `#inspect` on an Active Record object. By default, Rails filters out passwords by adding `Rails.application.config.filter_parameters += [:password]` in `config/initializers/filter_parameter_logging.rb`. Parameters filter works by partial matching regular expression. * `config.force_ssl` forces all requests to be served over HTTPS by using the `ActionDispatch::SSL` middleware, and sets `config.action_mailer.default_url_options` to be `{ protocol: 'https' }`. This can be configured by setting `config.ssl_options` - see the [ActionDispatch::SSL documentation](http://api.rubyonrails.org/classes/ActionDispatch/SSL.html) for details. @@ -211,7 +211,7 @@ The full set of methods that can be used in this block are as follows: * `stylesheets` turns on the hook for stylesheets in generators. Used in Rails for when the `scaffold` generator is run, but this hook can be used in other generates as well. Defaults to `true`. * `stylesheet_engine` configures the stylesheet engine (for eg. sass) to be used when generating assets. Defaults to `:css`. * `scaffold_stylesheet` creates `scaffold.css` when generating a scaffolded resource. Defaults to `true`. -* `test_framework` defines which test framework to use. Defaults to `false` and will use Minitest by default. +* `test_framework` defines which test framework to use. Defaults to `false` and will use minitest by default. * `template_engine` defines which template engine to use, such as ERB or Haml. Defaults to `:erb`. ### Configuring Middleware @@ -275,7 +275,7 @@ config.middleware.delete Rack::MethodOverride All these configuration options are delegated to the `I18n` library. -* `config.i18n.available_locales` whitelists the available locales for the app. Defaults to all locale keys found in locale files, usually only `:en` on a new application. +* `config.i18n.available_locales` defines the permitted available locales for the app. Defaults to all locale keys found in locale files, usually only `:en` on a new application. * `config.i18n.default_locale` sets the default locale of an application used for i18n. Defaults to `:en`. @@ -444,7 +444,7 @@ The schema dumper adds two additional configuration options: * `config.action_controller.action_on_unpermitted_parameters` enables logging or raising an exception if parameters that are not explicitly permitted are found. Set to `:log` or `:raise` to enable. The default value is `:log` in development and test environments, and `false` in all other environments. -* `config.action_controller.always_permitted_parameters` sets a list of whitelisted parameters that are permitted by default. The default values are `['controller', 'action']`. +* `config.action_controller.always_permitted_parameters` sets a list of permitted parameters that are permitted by default. The default values are `['controller', 'action']`. * `config.action_controller.enable_fragment_cache_logging` determines whether to log fragment cache reads and writes in verbose format as follows: @@ -516,6 +516,9 @@ Defaults to `'signed cookie'`. signed and encrypted cookies use the AES-256-GCM cipher or the older AES-256-CBC cipher. It defaults to `true`. +* `config.action_dispatch.use_cookies_with_metadata` enables writing + cookies with the purpose and expiry metadata embedded. It defaults to `true`. + * `config.action_dispatch.perform_deep_munge` configures whether `deep_munge` method should be performed on the parameters. See [Security Guide](security.html#unsafe-query-generation) for more information. It defaults to `true`. @@ -908,7 +911,15 @@ $ echo $DATABASE_URL postgresql://localhost/my_database $ rails runner 'puts ActiveRecord::Base.configurations' -{"development"=>{"adapter"=>"postgresql", "host"=>"localhost", "database"=>"my_database"}} +#<ActiveRecord::DatabaseConfigurations:0x00007fd50e209a28> + +$ rails runner 'puts ActiveRecord::Base.configurations.inspect' +#<ActiveRecord::DatabaseConfigurations:0x00007fc8eab02880 @configurations=[ + #<ActiveRecord::DatabaseConfigurations::UrlConfig:0x00007fc8eab020b0 + @env_name="development", @spec_name="primary", + @config={"adapter"=>"postgresql", "database"=>"my_database", "host"=>"localhost"} + @url="postgresql://localhost/my_database"> + ] ``` Here the adapter, host, and database match the information in `ENV['DATABASE_URL']`. @@ -925,7 +936,15 @@ $ echo $DATABASE_URL postgresql://localhost/my_database $ rails runner 'puts ActiveRecord::Base.configurations' -{"development"=>{"adapter"=>"postgresql", "host"=>"localhost", "database"=>"my_database", "pool"=>5}} +#<ActiveRecord::DatabaseConfigurations:0x00007fd50e209a28> + +$ rails runner 'puts ActiveRecord::Base.configurations.inspect' +#<ActiveRecord::DatabaseConfigurations:0x00007fc8eab02880 @configurations=[ + #<ActiveRecord::DatabaseConfigurations::UrlConfig:0x00007fc8eab020b0 + @env_name="development", @spec_name="primary", + @config={"adapter"=>"postgresql", "database"=>"my_database", "host"=>"localhost", "pool"=>5} + @url="postgresql://localhost/my_database"> + ] ``` Since pool is not in the `ENV['DATABASE_URL']` provided connection information its information is merged in. Since `adapter` is duplicate, the `ENV['DATABASE_URL']` connection information wins. @@ -941,7 +960,15 @@ $ echo $DATABASE_URL postgresql://localhost/my_database $ rails runner 'puts ActiveRecord::Base.configurations' -{"development"=>{"adapter"=>"sqlite3", "database"=>"NOT_my_database"}} +#<ActiveRecord::DatabaseConfigurations:0x00007fd50e209a28> + +$ rails runner 'puts ActiveRecord::Base.configurations.inspect' +#<ActiveRecord::DatabaseConfigurations:0x00007fc8eab02880 @configurations=[ + #<ActiveRecord::DatabaseConfigurations::UrlConfig:0x00007fc8eab020b0 + @env_name="development", @spec_name="primary", + @config={"adapter"=>"sqlite3", "database"=>"NOT_my_database"} + @url="sqlite3:NOT_my_database"> + ] ``` Here the connection information in `ENV['DATABASE_URL']` is ignored, note the different adapter and database name. @@ -989,6 +1016,14 @@ development: If your development database has a root user with an empty password, this configuration should work for you. Otherwise, change the username and password in the `development` section as appropriate. +Advisory Locks are enabled by default on MySQL and are used to make database migrations concurrent safe. You can disable advisory locks by setting `advisory_locks` to `false`: + +```yaml +production: + adapter: mysql2 + advisory_locks: false +``` + #### Configuring a PostgreSQL Database If you choose to use PostgreSQL, your `config/database.yml` will be customized to use PostgreSQL databases: @@ -1001,12 +1036,13 @@ development: pool: 5 ``` -Prepared Statements are enabled by default on PostgreSQL. You can disable prepared statements by setting `prepared_statements` to `false`: +By default Active Record uses database features like prepared statements and advisory locks. You might need to disable those features if you're using an external connection pooler like PgBouncer: ```yaml production: adapter: postgresql prepared_statements: false + advisory_locks: false ``` If enabled, Active Record will create up to `1000` prepared statements per database connection by default. To modify this behavior you can set `statement_limit` to a different value: diff --git a/guides/source/contributing_to_ruby_on_rails.md b/guides/source/contributing_to_ruby_on_rails.md index 3147b00f3b..b5e40aa40f 100644 --- a/guides/source/contributing_to_ruby_on_rails.md +++ b/guides/source/contributing_to_ruby_on_rails.md @@ -239,7 +239,6 @@ Now get busy and add/edit code. You're on your branch now, so you can write what * Include tests that fail without your code, and pass with it. * Update the (surrounding) documentation, examples elsewhere, and the guides: whatever is affected by your contribution. - TIP: Changes that are cosmetic in nature and do not add anything substantial to the stability, functionality, or testability of Rails will generally not be accepted (read more about [our rationales behind this decision](https://github.com/rails/rails/pull/13771#issuecomment-32746700)). #### Follow the Coding Conventions @@ -254,12 +253,24 @@ Rails follows a simple set of coding style conventions: * Prefer class << self over self.method for class methods. * Use `my_method(my_arg)` not `my_method( my_arg )` or `my_method my_arg`. * Use `a = b` and not `a=b`. -* Use assert_not methods instead of refute. +* Use assert\_not methods instead of refute. * Prefer `method { do_stuff }` instead of `method{do_stuff}` for single-line blocks. * Follow the conventions in the source you see used already. The above are guidelines - please use your best judgment in using them. +Additionally, we have [RuboCop](https://www.rubocop.org/) rules defined to codify some of our coding conventions. You can run RuboCop locally against the file that you have modified before submitting a pull request: + +```bash +$ rubocop actionpack/lib/action_controller/metal/strong_parameters.rb +Inspecting 1 file +. + +1 file inspected, no offenses detected +``` + +For `rails-ujs` CoffeeScript and JavaScript files, you can run `npm run lint` in `actionview` folder. + ### Benchmark Your Code For changes that might have an impact on performance, please benchmark your diff --git a/guides/source/development_dependencies_install.md b/guides/source/development_dependencies_install.md index 057bcf2c1b..07538a1cb7 100644 --- a/guides/source/development_dependencies_install.md +++ b/guides/source/development_dependencies_install.md @@ -350,57 +350,78 @@ prerequisite for installing this package manager is that On macOS, you can run: ```bash -brew install yarn +$ brew install yarn ``` On Ubuntu, you can run: ```bash -curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add - -echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list +$ curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add - +$ echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list -sudo apt-get update && sudo apt-get install yarn +$ sudo apt-get update && sudo apt-get install yarn ``` On Fedora or CentOS, just run: ```bash -sudo wget https://dl.yarnpkg.com/rpm/yarn.repo -O /etc/yum.repos.d/yarn.repo +$ sudo wget https://dl.yarnpkg.com/rpm/yarn.repo -O /etc/yum.repos.d/yarn.repo -sudo yum install yarn +$ sudo yum install yarn ``` Finally, after installing Yarn, you will need to run the following command inside of the `activestorage` directory to install the dependencies: ```bash -yarn install +$ yarn install ``` -Extracting previews, tested in ActiveStorage's test suite requires third-party -applications, FFmpeg for video and muPDF for PDFs, and on macOS also XQuartz -and Poppler. Without these applications installed, ActiveStorage tests will +Extracting previews, tested in Active Storage's test suite requires third-party +applications, ImageMagick for images, FFmpeg for video and muPDF for PDFs, and on macOS also XQuartz +and Poppler. Without these applications installed, Active Storage tests will raise errors. On macOS you can run: ```bash -brew install ffmpeg -brew cask install xquartz -brew install mupdf-tools -brew install poppler +$ brew install ffmpeg +$ brew install imagemagick +$ brew cask install xquartz +$ brew install mupdf-tools +$ brew install poppler ``` On Ubuntu, you can run: ```bash -sudo apt-get update && install ffmpeg -sudo apt-get update && install mupdf mupdf-tools +$ sudo apt-get update +$ sudo apt-get install ffmpeg +$ sudo apt-get install imagemagick +$ sudo apt-get install mupdf mupdf-tools ``` On Fedora or CentOS, just run: ```bash -sudo yum install ffmpeg -sudo yum install mupdf +$ sudo yum install ffmpeg +$ sudo yum install imagemagick +$ sudo yum install mupdf +``` + +FreeBSD users can just run: + +```bash +# pkg install imagemagick +# pkg install ffmpeg +# pkg install mupdf +``` + +On Arch Linux, you can run: + +```bash +$ sudo pacman -S ffmpeg +$ sudo pacman -S imagemagick +$ sudo pacman -S mupdf mupdf-tools +$ sudo pacman -S poppler ``` diff --git a/guides/source/documents.yaml b/guides/source/documents.yaml index 4dee34b1e7..8f2312458d 100644 --- a/guides/source/documents.yaml +++ b/guides/source/documents.yaml @@ -202,6 +202,11 @@ url: upgrading_ruby_on_rails.html description: This guide helps in upgrading applications to latest Ruby on Rails versions. - + name: Ruby on Rails 6.0 Release Notes + work_in_progress: true + url: 6_0_release_notes.html + description: Release notes for Rails 6.0. + - name: Ruby on Rails 5.2 Release Notes url: 5_2_release_notes.html description: Release notes for Rails 5.2. diff --git a/guides/source/form_helpers.md b/guides/source/form_helpers.md index a4f7e6f601..3660772fb9 100644 --- a/guides/source/form_helpers.md +++ b/guides/source/form_helpers.md @@ -22,27 +22,25 @@ NOTE: This guide is not intended to be a complete documentation of available for Dealing with Basic Forms ------------------------ -The most basic form helper is `form_tag`. +The main form helper is `form_with`. ```erb -<%= form_tag do %> +<%= form_with do %> Form contents <% end %> ``` -When called without arguments like this, it creates a `<form>` tag which, when submitted, will POST to the current page. For instance, assuming the current page is `/home/index`, the generated HTML will look like this (some line breaks added for readability): +When called without arguments like this, it creates a form tag which, when submitted, will POST to the current page. For instance, assuming the current page is a home page, the generated HTML will look like this: ```html -<form accept-charset="UTF-8" action="/" method="post"> - <input name="utf8" type="hidden" value="✓" /> +<form accept-charset="UTF-8" action="/" data-remote="true" method="post"> <input name="authenticity_token" type="hidden" value="J7CBxfHalt49OSHp27hblqK20c9PgwJ108nDHX/8Cts=" /> Form contents </form> ``` -You'll notice that the HTML contains an `input` element with type `hidden`. This `input` is important, because the form cannot be successfully submitted without it. The hidden input element with the name `utf8` enforces browsers to properly respect your form's character encoding and is generated for all forms whether their action is "GET" or "POST". - -The second input element with the name `authenticity_token` is a security feature of Rails called **cross-site request forgery protection**, and form helpers generate it for every non-GET form (provided that this security feature is enabled). You can read more about this in the [Security Guide](security.html#cross-site-request-forgery-csrf). +You'll notice that the HTML contains an `input` element with type `hidden`. This `input` is important, because non-GET form cannot be successfully submitted without it. +The hidden input element with the name `authenticity_token` is a security feature of Rails called **cross-site request forgery protection**, and form helpers generate it for every non-GET form (provided that this security feature is enabled). You can read more about this in the [Securing Rails Applications](security.html#cross-site-request-forgery-csrf) guide. ### A Generic Search Form @@ -53,10 +51,10 @@ One of the most basic forms you see on the web is a search form. This form conta * a text input element, and * a submit element. -To create this form you will use `form_tag`, `label_tag`, `text_field_tag`, and `submit_tag`, respectively. Like this: +To create this form you will use `form_with`, `label_tag`, `text_field_tag`, and `submit_tag`, respectively. Like this: ```erb -<%= form_tag("/search", method: "get") do %> +<%= form_with(url: "/search", method: "get") do %> <%= label_tag(:q, "Search for:") %> <%= text_field_tag(:q) %> <%= submit_tag("Search") %> @@ -66,37 +64,18 @@ To create this form you will use `form_tag`, `label_tag`, `text_field_tag`, and This will generate the following HTML: ```html -<form accept-charset="UTF-8" action="/search" method="get"> - <input name="utf8" type="hidden" value="✓" /> +<form accept-charset="UTF-8" action="/search" data-remote="true" method="get"> <label for="q">Search for:</label> <input id="q" name="q" type="text" /> - <input name="commit" type="submit" value="Search" /> + <input name="commit" type="submit" value="Search" data-disable-with="Search" /> </form> ``` -TIP: For every form input, an ID attribute is generated from its name (`"q"` in above example). These IDs can be very useful for CSS styling or manipulation of form controls with JavaScript. - -Besides `text_field_tag` and `submit_tag`, there is a similar helper for _every_ form control in HTML. - -IMPORTANT: Always use "GET" as the method for search forms. This allows users to bookmark a specific search and get back to it. More generally Rails encourages you to use the right HTTP verb for an action. - -### Multiple Hashes in Form Helper Calls - -The `form_tag` helper accepts 2 arguments: the path for the action and an options hash. This hash specifies the method of form submission and HTML options such as the form element's class. - -As with the `link_to` helper, the path argument doesn't have to be a string; it can be a hash of URL parameters recognizable by Rails' routing mechanism, which will turn the hash into a valid URL. However, since both arguments to `form_tag` are hashes, you can easily run into a problem if you would like to specify both. For instance, let's say you write this: - -```ruby -form_tag(controller: "people", action: "search", method: "get", class: "nifty_form") -# => '<form accept-charset="UTF-8" action="/people/search?method=get&class=nifty_form" method="post">' -``` +TIP: Passing `url: my_specified_path` to `form_with` tells the form where to make the request. However, as explained below, you can also pass ActiveRecord objects to the form. -Here, `method` and `class` are appended to the query string of the generated URL because even though you mean to write two hashes, you really only specified one. So you need to tell Ruby which is which by delimiting the first hash (or both) with curly brackets. This will generate the HTML you expect: +TIP: For every form input, an ID attribute is generated from its name (`"q"` in above example). These IDs can be very useful for CSS styling or manipulation of form controls with JavaScript. -```ruby -form_tag({controller: "people", action: "search"}, method: "get", class: "nifty_form") -# => '<form accept-charset="UTF-8" action="/people/search" method="get" class="nifty_form">' -``` +IMPORTANT: Use "GET" as the method for search forms. This allows users to bookmark a specific search and get back to it. More generally Rails encourages you to use the right HTTP verb for an action. ### Helpers for Generating Form Elements @@ -110,7 +89,7 @@ value entered by the user for that field. For example, if the form contains `<%= text_field_tag(:query) %>`, then you would be able to get the value of this field in the controller with `params[:query]`. -When naming inputs, Rails uses certain conventions that make it possible to submit parameters with non-scalar values such as arrays or hashes, which will also be accessible in `params`. You can read more about them in [chapter 7 of this guide](#understanding-parameter-naming-conventions). For details on the precise usage of these helpers, please refer to the [API documentation](http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html). +When naming inputs, Rails uses certain conventions that make it possible to submit parameters with non-scalar values such as arrays or hashes, which will also be accessible in `params`. You can read more about them in chapter [Understanding Parameter Naming Conventions](#understanding-parameter-naming-conventions) of this guide. For details on the precise usage of these helpers, please refer to the [API documentation](http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html). #### Checkboxes @@ -142,7 +121,7 @@ Radio buttons, while similar to checkboxes, are controls that specify a set of o <%= radio_button_tag(:age, "child") %> <%= label_tag(:age_child, "I am younger than 21") %> <%= radio_button_tag(:age, "adult") %> -<%= label_tag(:age_adult, "I'm over 21") %> +<%= label_tag(:age_adult, "I am over 21") %> ``` Output: @@ -151,7 +130,7 @@ Output: <input id="age_child" name="age" type="radio" value="child" /> <label for="age_child">I am younger than 21</label> <input id="age_adult" name="age" type="radio" value="adult" /> -<label for="age_adult">I'm over 21</label> +<label for="age_adult">I am over 21</label> ``` As with `check_box_tag`, the second parameter to `radio_button_tag` is the value of the input. Because these two radio buttons share the same name (`age`), the user will only be able to select one of them, and `params[:age]` will contain either `"child"` or `"adult"`. @@ -215,7 +194,7 @@ There is definitely [no shortage of solutions for this](https://github.com/Moder [Modernizr](https://modernizr.com/), which provides a simple way to add functionality based on the presence of detected HTML5 features. -TIP: If you're using password input fields (for any purpose), you might want to configure your application to prevent those parameters from being logged. You can learn about this in the [Security Guide](security.html#logging). +TIP: If you're using password input fields (for any purpose), you might want to configure your application to prevent those parameters from being logged. You can learn about this in the [Securing Rails Applications](security.html#logging) guide. Dealing with Model Objects -------------------------- @@ -233,10 +212,10 @@ For these helpers the first argument is the name of an instance variable and the will produce output similar to ```erb -<input id="person_name" name="person[name]" type="text" value="Henry"/> +<input id="person_name" name="person[name]" type="text" value="Henry" /> ``` -Upon form submission the value entered by the user will be stored in `params[:person][:name]`. The `params[:person]` hash is suitable for passing to `Person.new` or, if `@person` is an instance of Person, `@person.update`. While the name of an attribute is the most common second parameter to these helpers this is not compulsory. In the example above, as long as person objects have a `name` and a `name=` method Rails will be happy. +Upon form submission the value entered by the user will be stored in `params[:person][:name]`. WARNING: You must pass the name of an instance variable, i.e. `:person` or `"person"`, not an actual instance of your model object. @@ -244,7 +223,7 @@ Rails provides helpers for displaying the validation errors associated with a mo ### Binding a Form to an Object -While this is an increase in comfort it is far from perfect. If `Person` has many attributes to edit then we would be repeating the name of the edited object many times. What we want to do is somehow bind a form to a model object, which is exactly what `form_for` does. +While this is an increase in comfort it is far from perfect. If `Person` has many attributes to edit then we would be repeating the name of the edited object many times. What we want to do is somehow bind a form to a model object, which is exactly what `form_with` with `:model` does. Assume we have a controller for dealing with articles `app/controllers/articles_controller.rb`: @@ -254,10 +233,10 @@ def new end ``` -The corresponding view `app/views/articles/new.html.erb` using `form_for` looks like this: +The corresponding view `app/views/articles/new.html.erb` using `form_with` looks like this: ```erb -<%= form_for @article, url: {action: "create"}, html: {class: "nifty_form"} do |f| %> +<%= form_with model: @article, class: "nifty_form" do |f| %> <%= f.text_field :title %> <%= f.text_area :body, size: "60x12" %> <%= f.submit "Create" %> @@ -267,15 +246,15 @@ The corresponding view `app/views/articles/new.html.erb` using `form_for` looks There are a few things to note here: * `@article` is the actual object being edited. -* There is a single hash of options. Routing options are passed in the `:url` hash, HTML options are passed in the `:html` hash. Also you can provide a `:namespace` option for your form to ensure uniqueness of id attributes on form elements. The namespace attribute will be prefixed with underscore on the generated HTML id. -* The `form_for` method yields a **form builder** object (the `f` variable). +* There is a single hash of options. HTML options (except `id` and `class`) are passed in the `:html` hash. Also you can provide a `:namespace` option for your form to ensure uniqueness of id attributes on form elements. The scope attribute will be prefixed with underscore on the generated HTML id. +* The `form_with` method yields a **form builder** object (the `f` variable). +* If you wish to direct your form request to a particular url, you would use `form_with url: my_nifty_url_path` instead. To see more in depth options on what `form_with` accepts be sure to [check out the API documentation](https://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-form_with). * Methods to create form controls are called **on** the form builder object `f`. The resulting HTML is: ```html -<form class="nifty_form" id="new_article" action="/articles" accept-charset="UTF-8" method="post"> - <input name="utf8" type="hidden" value="✓" /> +<form class="nifty_form" action="/articles" accept-charset="UTF-8" data-remote="true" method="post"> <input type="hidden" name="authenticity_token" value="NRkFyRWxdYNfUg7vYxLOp2SLf93lvnl+QwDWorR42Dp6yZXPhHEb6arhDOIWcqGit8jfnrPwL781/xlrzj63TA==" /> <input type="text" name="article[title]" id="article_title" /> <textarea name="article[body]" id="article_body" cols="60" rows="12"></textarea> @@ -283,16 +262,18 @@ The resulting HTML is: </form> ``` -The name passed to `form_for` controls the key used in `params` to access the form's values. Here the name is `article` and so all the inputs have names of the form `article[attribute_name]`. Accordingly, in the `create` action `params[:article]` will be a hash with keys `:title` and `:body`. You can read more about the significance of input names in the [parameter_names section](#understanding-parameter-naming-conventions). +The object passed as `:model` in `form_with` controls the key used in `params` to access the form's values. Here the name is `article` and so all the inputs have names of the form `article[attribute_name]`. Accordingly, in the `create` action `params[:article]` will be a hash with keys `:title` and `:body`. You can read more about the significance of input names in chapter [Understanding Parameter Naming Conventions](#understanding-parameter-naming-conventions) of this guide. + +TIP: Conventionally your inputs will mirror model attributes. However, they don't have to! If there is other information you need you can include it in your form just as with attributes and access it via `params[:article][:my_nifty_non_attribute_input]`. The helper methods called on the form builder are identical to the model object helpers except that it is not necessary to specify which object is being edited since this is already managed by the form builder. You can create a similar binding without actually creating `<form>` tags with the `fields_for` helper. This is useful for editing additional model objects with the same form. For example, if you had a `Person` model with an associated `ContactDetail` model, you could create a form for creating both like so: ```erb -<%= form_for @person, url: {action: "create"} do |person_form| %> +<%= form_with model: @person do |person_form| %> <%= person_form.text_field :name %> - <%= fields_for @person.contact_detail do |contact_detail_form| %> + <%= fields_for :contact_detail, @person.contact_detail do |contact_detail_form| %> <%= contact_detail_form.text_field :phone_number %> <% end %> <% end %> @@ -301,15 +282,14 @@ You can create a similar binding without actually creating `<form>` tags with th which produces the following output: ```html -<form class="new_person" id="new_person" action="/people" accept-charset="UTF-8" method="post"> - <input name="utf8" type="hidden" value="✓" /> +<form action="/people" accept-charset="UTF-8" data-remote="true" method="post"> <input type="hidden" name="authenticity_token" value="bL13x72pldyDD8bgtkjKQakJCpd4A8JdXGbfksxBDHdf1uC0kCMqe2tvVdUYfidJt0fj3ihC4NxiVHv8GVYxJA==" /> <input type="text" name="person[name]" id="person_name" /> <input type="text" name="contact_detail[phone_number]" id="contact_detail_phone_number" /> </form> ``` -The object yielded by `fields_for` is a form builder like the one yielded by `form_for` (in fact `form_for` calls `fields_for` internally). +The object yielded by `fields_for` is a form builder like the one yielded by `form_with`. ### Relying on Record Identification @@ -319,62 +299,59 @@ The Article model is directly available to users of the application, so - follow resources :articles ``` -TIP: Declaring a resource has a number of side effects. See [Rails Routing From the Outside In](routing.html#resource-routing-the-rails-default) for more information on setting up and using resources. +TIP: Declaring a resource has a number of side effects. See [Rails Routing from the Outside In](routing.html#resource-routing-the-rails-default) guide for more information on setting up and using resources. -When dealing with RESTful resources, calls to `form_for` can get significantly easier if you rely on **record identification**. In short, you can just pass the model instance and have Rails figure out model name and the rest: +When dealing with RESTful resources, calls to `form_with` can get significantly easier if you rely on **record identification**. In short, you can just pass the model instance and have Rails figure out model name and the rest: ```ruby ## Creating a new article # long-style: -form_for(@article, url: articles_path) -# same thing, short-style (record identification gets used): -form_for(@article) +form_with(model: @article, url: articles_path) +short-style: +form_with(model: @article) ## Editing an existing article # long-style: -form_for(@article, url: article_path(@article), html: {method: "patch"}) +form_with(model: @article, url: article_path(@article), method: "patch") # short-style: -form_for(@article) +form_with(model: @article) ``` -Notice how the short-style `form_for` invocation is conveniently the same, regardless of the record being new or existing. Record identification is smart enough to figure out if the record is new by asking `record.new_record?`. It also selects the correct path to submit to and the name based on the class of the object. - -Rails will also automatically set the `class` and `id` of the form appropriately: a form creating an article would have `id` and `class` `new_article`. If you were editing the article with id 23, the `class` would be set to `edit_article` and the id to `edit_article_23`. These attributes will be omitted for brevity in the rest of this guide. +Notice how the short-style `form_with` invocation is conveniently the same, regardless of the record being new or existing. Record identification is smart enough to figure out if the record is new by asking `record.new_record?`. It also selects the correct path to submit to, and the name based on the class of the object. -WARNING: When you're using STI (single-table inheritance) with your models, you can't rely on record identification on a subclass if only their parent class is declared a resource. You will have to specify the model name, `:url`, and `:method` explicitly. +WARNING: When you're using STI (single-table inheritance) with your models, you can't rely on record identification on a subclass if only their parent class is declared a resource. You will have to specify `:url`, and `:scope` (the model name) explicitly. #### Dealing with Namespaces -If you have created namespaced routes, `form_for` has a nifty shorthand for that too. If your application has an admin namespace then +If you have created namespaced routes, `form_with` has a nifty shorthand for that too. If your application has an admin namespace then ```ruby -form_for [:admin, @article] +form_with model: [:admin, @article] ``` will create a form that submits to the `ArticlesController` inside the admin namespace (submitting to `admin_article_path(@article)` in the case of an update). If you have several levels of namespacing then the syntax is similar: ```ruby -form_for [:admin, :management, @article] +form_with model: [:admin, :management, @article] ``` -For more information on Rails' routing system and the associated conventions, please see the [routing guide](routing.html). +For more information on Rails' routing system and the associated conventions, please see [Rails Routing from the Outside In](routing.html) guide. ### How do forms with PATCH, PUT, or DELETE methods work? -The Rails framework encourages RESTful design of your applications, which means you'll be making a lot of "PATCH" and "DELETE" requests (besides "GET" and "POST"). However, most browsers _don't support_ methods other than "GET" and "POST" when it comes to submitting forms. +The Rails framework encourages RESTful design of your applications, which means you'll be making a lot of "PATCH", "PUT", and "DELETE" requests (besides "GET" and "POST"). However, most browsers _don't support_ methods other than "GET" and "POST" when it comes to submitting forms. Rails works around this issue by emulating other methods over POST with a hidden input named `"_method"`, which is set to reflect the desired method: ```ruby -form_tag(search_path, method: "patch") +form_with(url: search_path, method: "patch") ``` -output: +Output: ```html -<form accept-charset="UTF-8" action="/search" method="post"> +<form accept-charset="UTF-8" action="/search" data-remote="true" method="post"> <input name="_method" type="hidden" value="patch" /> - <input name="utf8" type="hidden" value="✓" /> <input name="authenticity_token" type="hidden" value="f755bb0ed134b76c432144748a6d4b7a7ddf2b71" /> ... </form> @@ -382,6 +359,8 @@ output: When parsing POSTed data, Rails will take into account the special `_method` parameter and act as if the HTTP method was the one specified inside it ("PATCH" in this example). +IMPORTANT: All forms using `form_with` implement `remote: true` by default. These forms will submit data using an XHR (Ajax) request. To disable this include `local: true`. To dive deeper see [Working with JavaScript in Rails](working_with_javascript_in_rails.html#remote-elements) guide. + Making Select Boxes with Ease ----------------------------- @@ -393,8 +372,7 @@ Here is what the markup might look like: <select name="city_id" id="city_id"> <option value="1">Lisbon</option> <option value="2">Madrid</option> - ... - <option value="12">Berlin</option> + <option value="3">Berlin</option> </select> ``` @@ -405,19 +383,21 @@ Here you have a list of cities whose names are presented to the user. Internally The most generic helper is `select_tag`, which - as the name implies - simply generates the `SELECT` tag that encapsulates an options string: ```erb -<%= select_tag(:city_id, '<option value="1">Lisbon</option>...') %> +<%= select_tag(:city_id, raw('<option value="1">Lisbon</option><option value="2">Madrid</option><option value="3">Berlin</option>')) %> ``` This is a start, but it doesn't dynamically create the option tags. You can generate option tags with the `options_for_select` helper: ```html+erb -<%= options_for_select([['Lisbon', 1], ['Madrid', 2], ...]) %> +<%= options_for_select([['Lisbon', 1], ['Madrid', 2], ['Berlin', 3]]) %> +``` -output: +Output: +```html <option value="1">Lisbon</option> <option value="2">Madrid</option> -... +<option value="3">Berlin</option> ``` The first argument to `options_for_select` is a nested array where each element has two elements: option text (city name) and option value (city id). The option value is what will be submitted to your controller. Often this will be the id of a corresponding database object but this does not have to be the case. @@ -431,48 +411,61 @@ Knowing this, you can combine `select_tag` and `options_for_select` to achieve t `options_for_select` allows you to pre-select an option by passing its value. ```html+erb -<%= options_for_select([['Lisbon', 1], ['Madrid', 2], ...], 2) %> +<%= options_for_select([['Lisbon', 1], ['Madrid', 2], ['Berlin', 3]], 2) %> +``` -output: +Output: +```html <option value="1">Lisbon</option> <option value="2" selected="selected">Madrid</option> -... +<option value="3">Berlin</option> ``` Whenever Rails sees that the internal value of an option being generated matches this value, it will add the `selected` attribute to that option. -WARNING: When `:include_blank` or `:prompt` are not present, `:include_blank` is forced true if the select attribute `required` is true, display `size` is one, and `multiple` is not true. - You can add arbitrary attributes to the options using hashes: ```html+erb <%= options_for_select( [ ['Lisbon', 1, { 'data-size' => '2.8 million' }], - ['Madrid', 2, { 'data-size' => '3.2 million' }] + ['Madrid', 2, { 'data-size' => '3.2 million' }], + ['Berlin', 3, { 'data-size' => '3.4 million' }] ], 2 ) %> +``` -output: +Output: +```html <option value="1" data-size="2.8 million">Lisbon</option> <option value="2" selected="selected" data-size="3.2 million">Madrid</option> -... +<option value="3" data-size="3.4 million">Berlin</option> ``` -### Select Boxes for Dealing with Models +### Select Boxes for Dealing with Model Objects + +In most cases form controls will be tied to a specific model and as you might expect Rails provides helpers tailored for that purpose. Consistent with other form helpers, when dealing with a model object drop the `_tag` suffix from `select_tag`: -In most cases form controls will be tied to a specific database model and as you might expect Rails provides helpers tailored for that purpose. Consistent with other form helpers, when dealing with models you drop the `_tag` suffix from `select_tag`: +If your controller has defined `@person` and that person's city_id is 2: ```ruby -# controller: @person = Person.new(city_id: 2) ``` ```erb -# view: -<%= select(:person, :city_id, [['Lisbon', 1], ['Madrid', 2], ...]) %> +<%= select(:person, :city_id, [['Lisbon', 1], ['Madrid', 2], ['Berlin', 3]]) %> +``` + +will produce output similar to + +```html +<select name="person[city_id]" id="person_city_id"> + <option value="1">Lisbon</option> + <option value="2" selected="selected">Madrid</option> + <option value="3">Berlin</option> +</select> ``` Notice that the third parameter, the options array, is the same kind of argument you pass to `options_for_select`. One advantage here is that you don't have to worry about pre-selecting the correct city if the user already has one - Rails will do this for you by reading from the `@person.city_id` attribute. @@ -480,21 +473,26 @@ Notice that the third parameter, the options array, is the same kind of argument As with other helpers, if you were to use the `select` helper on a form builder scoped to the `@person` object, the syntax would be: ```erb -# select on a form builder -<%= f.select(:city_id, ...) %> +<%= form_with model: @person do |person_form| %> + <%= person_form.select(:city_id, [['Lisbon', 1], ['Madrid', 2], ['Berlin', 3]]) %> +<% end %> ``` You can also pass a block to `select` helper: ```erb -<%= f.select(:city_id) do %> - <% [['Lisbon', 1], ['Madrid', 2]].each do |c| -%> - <%= content_tag(:option, c.first, value: c.last) %> +<%= form_with model: @person do |person_form| %> + <%= person_form.select(:city_id) do %> + <% [['Lisbon', 1], ['Madrid', 2], ['Berlin', 3]].each do |c| %> + <%= content_tag(:option, c.first, value: c.last) %> + <% end %> <% end %> <% end %> ``` -WARNING: If you are using `select` (or similar helpers such as `collection_select`, `select_tag`) to set a `belongs_to` association you must pass the name of the foreign key (in the example above `city_id`), not the name of association itself. If you specify `city` instead of `city_id` Active Record will raise an error along the lines of `ActiveRecord::AssociationTypeMismatch: City(#17815740) expected, got String(#1138750)` when you pass the `params` hash to `Person.new` or `update`. Another way of looking at this is that form helpers only edit attributes. You should also be aware of the potential security ramifications of allowing users to edit foreign keys directly. +WARNING: If you are using `select` or similar helpers to set a `belongs_to` association you must pass the name of the foreign key (in the example above `city_id`), not the name of association itself. + +WARNING: When `:include_blank` or `:prompt` are not present, `:include_blank` is forced true if the select attribute `required` is true, display `size` is one, and `multiple` is not true. ### Option Tags from a Collection of Arbitrary Objects @@ -511,7 +509,7 @@ This is a perfectly valid solution, but Rails provides a less verbose alternativ <%= options_from_collection_for_select(City.all, :id, :name) %> ``` -As the name implies, this only generates option tags. To generate a working select box you would need to use it in conjunction with `select_tag`, just as you would with `options_for_select`. When working with model objects, just as `select` combines `select_tag` and `options_for_select`, `collection_select` combines `select_tag` with `options_from_collection_for_select`. +As the name implies, this only generates option tags. To generate a working select box you would need to use `collection_select`: ```erb <%= collection_select(:person, :city_id, City.all, :id, :name) %> @@ -520,16 +518,16 @@ As the name implies, this only generates option tags. To generate a working sele As with other helpers, if you were to use the `collection_select` helper on a form builder scoped to the `@person` object, the syntax would be: ```erb -<%= f.collection_select(:city_id, City.all, :id, :name) %> +<%= form_with model: @person do |person_form| %> + <%= person_form.collection_select(:city_id, City.all, :id, :name) %> +<% end %> ``` -To recap, `options_from_collection_for_select` is to `collection_select` what `options_for_select` is to `select`. - -NOTE: Pairs passed to `options_for_select` should have the name first and the id second, however with `options_from_collection_for_select` the first argument is the value method and the second the text method. +NOTE: Pairs passed to `options_for_select` should have the text first and the value second, however with `options_from_collection_for_select` should have the value method first and the text method second. ### Time Zone and Country Select -To leverage time zone support in Rails, you have to ask your users what time zone they are in. Doing so would require generating select options from a list of pre-defined TimeZone objects using `collection_select`, but you can simply use the `time_zone_select` helper that already wraps this: +To leverage time zone support in Rails, you have to ask your users what time zone they are in. Doing so would require generating select options from a list of pre-defined [`ActiveSupport::TimeZone`](http://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html) objects using `collection_select`, but you can simply use the `time_zone_select` helper that already wraps this: ```erb <%= time_zone_select(:person, :time_zone) %> @@ -537,21 +535,21 @@ To leverage time zone support in Rails, you have to ask your users what time zon There is also `time_zone_options_for_select` helper for a more manual (therefore more customizable) way of doing this. Read the [API documentation](http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-time_zone_options_for_select) to learn about the possible arguments for these two methods. -Rails _used_ to have a `country_select` helper for choosing countries, but this has been extracted to the [country_select plugin](https://github.com/stefanpenner/country_select). When using this, be aware that the exclusion or inclusion of certain names from the list can be somewhat controversial (and was the reason this functionality was extracted from Rails). +Rails _used_ to have a `country_select` helper for choosing countries, but this has been extracted to the [country_select plugin](https://github.com/stefanpenner/country_select). Using Date and Time Form Helpers -------------------------------- You can choose not to use the form helpers generating HTML5 date and time input fields and use the alternative date and time helpers. These date and time helpers differ from all the other form helpers in two important respects: -* Dates and times are not representable by a single input element. Instead you have several, one for each component (year, month, day etc.) and so there is no single value in your `params` hash with your date or time. +* Dates and times are not representable by a single input element. Instead, you have several, one for each component (year, month, day etc.) and so there is no single value in your `params` hash with your date or time. * Other helpers use the `_tag` suffix to indicate whether a helper is a barebones helper or one that operates on model objects. With dates and times, `select_date`, `select_time` and `select_datetime` are the barebones helpers, `date_select`, `time_select` and `datetime_select` are the equivalent model object helpers. Both of these families of helpers will create a series of select boxes for the different components (year, month, day etc.). ### Barebones Helpers -The `select_*` family of helpers take as their first argument an instance of `Date`, `Time` or `DateTime` that is used as the currently selected value. You may omit this parameter, in which case the current date is used. For example: +The `select_*` family of helpers take as their first argument an instance of `Date`, `Time`, or `DateTime` that is used as the currently selected value. You may omit this parameter, in which case the current date is used. For example: ```erb <%= select_date Date.today, prefix: :start_date %> @@ -560,12 +558,15 @@ The `select_*` family of helpers take as their first argument an instance of `Da outputs (with actual option values omitted for brevity) ```html -<select id="start_date_year" name="start_date[year]"> ... </select> -<select id="start_date_month" name="start_date[month]"> ... </select> -<select id="start_date_day" name="start_date[day]"> ... </select> +<select id="start_date_year" name="start_date[year]"> +</select> +<select id="start_date_month" name="start_date[month]"> +</select> +<select id="start_date_day" name="start_date[day]"> +</select> ``` -The above inputs would result in `params[:start_date]` being a hash with keys `:year`, `:month`, `:day`. To get an actual `Date`, `Time` or `DateTime` object you would have to extract these values and pass them to the appropriate constructor, for example: +The above inputs would result in `params[:start_date]` being a hash with keys `:year`, `:month`, `:day`. To get an actual `Date`, `Time`, or `DateTime` object you would have to extract these values and pass them to the appropriate constructor, for example: ```ruby Date.civil(params[:start_date][:year].to_i, params[:start_date][:month].to_i, params[:start_date][:day].to_i) @@ -585,9 +586,12 @@ The model object helpers for dates and times submit parameters with special name outputs (with actual option values omitted for brevity) ```html -<select id="person_birth_date_1i" name="person[birth_date(1i)]"> ... </select> -<select id="person_birth_date_2i" name="person[birth_date(2i)]"> ... </select> -<select id="person_birth_date_3i" name="person[birth_date(3i)]"> ... </select> +<select id="person_birth_date_1i" name="person[birth_date(1i)]"> +</select> +<select id="person_birth_date_2i" name="person[birth_date(2i)]"> +</select> +<select id="person_birth_date_3i" name="person[birth_date(3i)]"> +</select> ``` which results in a `params` hash like @@ -604,68 +608,60 @@ Both families of helpers use the same core set of functions to generate the indi As a rule of thumb you should be using `date_select` when working with model objects and `select_date` in other cases, such as a search form which filters results by date. -NOTE: In many cases the built-in date pickers are clumsy as they do not aid the user in working out the relationship between the date and the day of the week. - ### Individual Components Occasionally you need to display just a single date component such as a year or a month. Rails provides a series of helpers for this, one for each component `select_year`, `select_month`, `select_day`, `select_hour`, `select_minute`, `select_second`. These helpers are fairly straightforward. By default they will generate an input field named after the time component (for example, "year" for `select_year`, "month" for `select_month` etc.) although this can be overridden with the `:field_name` option. The `:prefix` option works in the same way that it does for `select_date` and `select_time` and has the same default value. -The first parameter specifies which value should be selected and can either be an instance of a `Date`, `Time` or `DateTime`, in which case the relevant component will be extracted, or a numerical value. For example: +The first parameter specifies which value should be selected and can either be an instance of a `Date`, `Time`, or `DateTime`, in which case the relevant component will be extracted, or a numerical value. For example: ```erb <%= select_year(2009) %> -<%= select_year(Time.now) %> +<%= select_year(Time.new(2009)) %> ``` -will produce the same output if the current year is 2009 and the value chosen by the user can be retrieved by `params[:date][:year]`. +will produce the same output and the value chosen by the user can be retrieved by `params[:date][:year]`. Uploading Files --------------- -A common task is uploading some sort of file, whether it's a picture of a person or a CSV file containing data to process. The most important thing to remember with file uploads is that the rendered form's encoding **MUST** be set to "multipart/form-data". If you use `form_for`, this is done automatically. If you use `form_tag`, you must set it yourself, as per the following example. +A common task is uploading some sort of file, whether it's a picture of a person or a CSV file containing data to process. The most important thing to remember with file uploads is that the rendered form's enctype attribute **must** be set to "multipart/form-data". If you use `form_with` with `:model`, this is done automatically. If you use `form_with` without `:model`, you must set it yourself, as per the following example. The following two forms both upload a file. ```erb -<%= form_tag({action: :upload}, multipart: true) do %> +<%= form_with(url: {action: :upload}, multipart: true) do %> <%= file_field_tag 'picture' %> <% end %> -<%= form_for @person do |f| %> +<%= form_with model: @person do |f| %> <%= f.file_field :picture %> <% end %> ``` -Rails provides the usual pair of helpers: the barebones `file_field_tag` and the model oriented `file_field`. The only difference with other helpers is that you cannot set a default value for file inputs as this would have no meaning. As you would expect in the first case the uploaded file is in `params[:picture]` and in the second case in `params[:person][:picture]`. +Rails provides the usual pair of helpers: the barebones `file_field_tag` and the model oriented `file_field`. As you would expect in the first case the uploaded file is in `params[:picture]` and in the second case in `params[:person][:picture]`. ### What Gets Uploaded -The object in the `params` hash is an instance of a subclass of `IO`. Depending on the size of the uploaded file it may in fact be a `StringIO` or an instance of `File` backed by a temporary file. In both cases the object will have an `original_filename` attribute containing the name the file had on the user's computer and a `content_type` attribute containing the MIME type of the uploaded file. The following snippet saves the uploaded content in `#{Rails.root}/public/uploads` under the same name as the original file (assuming the form was the one in the previous example). +The object in the `params` hash is an instance of [`ActionDispatch::Http::UploadedFile`](http://api.rubyonrails.org/classes/ActionDispatch/Http/UploadedFile.html). The following snippet saves the uploaded file in `#{Rails.root}/public/uploads` under the same name as the original file. ```ruby def upload - uploaded_io = params[:person][:picture] - File.open(Rails.root.join('public', 'uploads', uploaded_io.original_filename), 'wb') do |file| - file.write(uploaded_io.read) + uploaded_file = params[:picture] + File.open(Rails.root.join('public', 'uploads', uploaded_file.original_filename), 'wb') do |file| + file.write(uploaded_file.read) end end ``` -Once a file has been uploaded, there are a multitude of potential tasks, ranging from where to store the files (on disk, Amazon S3, etc) and associating them with models to resizing image files and generating thumbnails. [Active Storage](https://guides.rubyonrails.org/active_storage_overview.html) is designed to assist with these tasks. - -NOTE: If the user has not selected a file the corresponding parameter will be an empty string. - -### Dealing with Ajax - -Unlike other forms, making an asynchronous file upload form is not as simple as providing `form_for` with `remote: true`. With an Ajax form the serialization is done by JavaScript running inside the browser and since JavaScript cannot read files from your hard drive the file cannot be uploaded. The most common workaround is to use an invisible iframe that serves as the target for the form submission. +Once a file has been uploaded, there are a multitude of potential tasks, ranging from where to store the files (on Disk, Amazon S3, etc), associating them with models, resizing image files, and generating thumbnails, etc. [Active Storage](active_storage_overview.html) is designed to assist with these tasks. Customizing Form Builders ------------------------- -As mentioned previously the object yielded by `form_for` and `fields_for` is an instance of `FormBuilder` (or a subclass thereof). Form builders encapsulate the notion of displaying form elements for a single object. While you can of course write helpers for your forms in the usual way, you can also subclass `FormBuilder` and add the helpers there. For example: +The object yielded by `form_with` and `fields_for` is an instance of [`ActionView::Helpers::FormBuilder`](http://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html). Form builders encapsulate the notion of displaying form elements for a single object. While you can write helpers for your forms in the usual way, you can also create subclass `ActionView::Helpers::FormBuilder` and add the helpers there. For example: ```erb -<%= form_for @person do |f| %> +<%= form_with model: @person do |f| %> <%= text_field_with_label f, :first_name %> <% end %> ``` @@ -673,7 +669,7 @@ As mentioned previously the object yielded by `form_for` and `fields_for` is an can be replaced with ```erb -<%= form_for @person, builder: LabellingFormBuilder do |f| %> +<%= form_with model: @person, builder: LabellingFormBuilder do |f| %> <%= f.text_field :first_name %> <% end %> ``` @@ -688,12 +684,12 @@ class LabellingFormBuilder < ActionView::Helpers::FormBuilder end ``` -If you reuse this frequently you could define a `labeled_form_for` helper that automatically applies the `builder: LabellingFormBuilder` option: +If you reuse this frequently you could define a `labeled_form_with` helper that automatically applies the `builder: LabellingFormBuilder` option: ```ruby -def labeled_form_for(record, options = {}, &block) +def labeled_form_with(model: nil, scope: nil, url: nil, format: nil, **options, &block) options.merge! builder: LabellingFormBuilder - form_for record, options, &block + form_with model: model, scope: scope, url: url, format: format, **options, &block end ``` @@ -703,13 +699,12 @@ The form builder used also determines what happens when you do <%= render partial: f %> ``` -If `f` is an instance of `FormBuilder` then this will render the `form` partial, setting the partial's object to the form builder. If the form builder is of class `LabellingFormBuilder` then the `labelling_form` partial would be rendered instead. +If `f` is an instance of `ActionView::Helpers::FormBuilder` then this will render the `form` partial, setting the partial's object to the form builder. If the form builder is of class `LabellingFormBuilder` then the `labelling_form` partial would be rendered instead. Understanding Parameter Naming Conventions ------------------------------------------ -As you've seen in the previous sections, values from forms can be at the top level of the `params` hash or nested in another hash. For example, in a standard `create` -action for a Person model, `params[:person]` would usually be a hash of all the attributes for the person to create. The `params` hash can also contain arrays, arrays of hashes, and so on. +Values from forms can be at the top level of the `params` hash or nested in another hash. For example, in a standard `create` action for a Person model, `params[:person]` would usually be a hash of all the attributes for the person to create. The `params` hash can also contain arrays, arrays of hashes, and so on. Fundamentally HTML forms don't know about any sort of structured data, all they generate is name-value pairs, where pairs are just plain strings. The arrays and hashes you see in your application are the result of some parameter naming conventions that Rails uses. @@ -756,25 +751,28 @@ This would result in `params[:person][:phone_number]` being an array containing We can mix and match these two concepts. One element of a hash might be an array as in the previous example, or you can have an array of hashes. For example, a form might let you create any number of addresses by repeating the following form fragment ```html -<input name="addresses[][line1]" type="text"/> -<input name="addresses[][line2]" type="text"/> -<input name="addresses[][city]" type="text"/> +<input name="person[addresses][][line1]" type="text"/> +<input name="person[addresses][][line2]" type="text"/> +<input name="person[addresses][][city]" type="text"/> +<input name="person[addresses][][line1]" type="text"/> +<input name="person[addresses][][line2]" type="text"/> +<input name="person[addresses][][city]" type="text"/> ``` -This would result in `params[:addresses]` being an array of hashes with keys `line1`, `line2` and `city`. Rails decides to start accumulating values in a new hash whenever it encounters an input name that already exists in the current hash. +This would result in `params[:person][:addresses]` being an array of hashes with keys `line1`, `line2`, and `city`. There's a restriction, however, while hashes can be nested arbitrarily, only one level of "arrayness" is allowed. Arrays can usually be replaced by hashes; for example, instead of having an array of model objects, one can have a hash of model objects keyed by their id, an array index, or some other parameter. -WARNING: Array parameters do not play well with the `check_box` helper. According to the HTML specification unchecked checkboxes submit no value. However it is often convenient for a checkbox to always submit a value. The `check_box` helper fakes this by creating an auxiliary hidden input with the same name. If the checkbox is unchecked only the hidden input is submitted and if it is checked then both are submitted but the value submitted by the checkbox takes precedence. When working with array parameters this duplicate submission will confuse Rails since duplicate input names are how it decides when to start a new array element. It is preferable to either use `check_box_tag` or to use hashes instead of arrays. +WARNING: Array parameters do not play well with the `check_box` helper. According to the HTML specification unchecked checkboxes submit no value. However it is often convenient for a checkbox to always submit a value. The `check_box` helper fakes this by creating an auxiliary hidden input with the same name. If the checkbox is unchecked only the hidden input is submitted and if it is checked then both are submitted but the value submitted by the checkbox takes precedence. ### Using Form Helpers -The previous sections did not use the Rails form helpers at all. While you can craft the input names yourself and pass them directly to helpers such as `text_field_tag` Rails also provides higher level support. The two tools at your disposal here are the name parameter to `form_for` and `fields_for` and the `:index` option that helpers take. +The previous sections did not use the Rails form helpers at all. While you can craft the input names yourself and pass them directly to helpers such as `text_field_tag` Rails also provides higher level support. The two tools at your disposal here are the name parameter to `form_with` and `fields_for` and the `:index` option that helpers take. You might want to render a form with a set of edit fields for each of a person's addresses. For example: ```erb -<%= form_for @person do |person_form| %> +<%= form_with model: @person do |person_form| %> <%= person_form.text_field :name %> <% @person.addresses.each do |address| %> <%= person_form.fields_for address, index: address.id do |address_form|%> @@ -787,7 +785,8 @@ You might want to render a form with a set of edit fields for each of a person's Assuming the person had two addresses, with ids 23 and 45 this would create output similar to this: ```html -<form accept-charset="UTF-8" action="/people/1" class="edit_person" id="edit_person_1" method="post"> +<form accept-charset="UTF-8" action="/people/1" data-remote="true" method="post"> + <input name="_method" type="hidden" value="patch" /> <input id="person_name" name="person[name]" type="text" /> <input id="person_address_23_city" name="person[address][23][city]" type="text" /> <input id="person_address_45_city" name="person[address][45][city]" type="text" /> @@ -812,7 +811,7 @@ To create more intricate nestings, you can specify the first part of the input name (`person[address]` in the previous example) explicitly: ```erb -<%= fields_for 'person[address][primary]', address, index: address do |address_form| %> +<%= fields_for 'person[address][primary]', address, index: address.id do |address_form| %> <%= address_form.text_field :city %> <% end %> ``` @@ -820,12 +819,12 @@ name (`person[address]` in the previous example) explicitly: will create inputs like ```html -<input id="person_address_primary_1_city" name="person[address][primary][1][city]" type="text" value="bologna" /> +<input id="person_address_primary_1_city" name="person[address][primary][1][city]" type="text" value="Bologna" /> ``` -As a general rule the final input name is the concatenation of the name given to `fields_for`/`form_for`, the index value, and the name of the attribute. You can also pass an `:index` option directly to helpers such as `text_field`, but it is usually less repetitive to specify this at the form builder level rather than on individual input controls. +As a general rule the final input name is the concatenation of the name given to `fields_for`/`form_with`, the index value, and the name of the attribute. You can also pass an `:index` option directly to helpers such as `text_field`, but it is usually less repetitive to specify this at the form builder level rather than on individual input controls. -As a shortcut you can append [] to the name and omit the `:index` option. This is the same as specifying `index: address` so +As a shortcut you can append [] to the name and omit the `:index` option. This is the same as specifying `index: address.id` so ```erb <%= fields_for 'person[address][primary][]', address do |address_form| %> @@ -838,10 +837,10 @@ produces exactly the same output as the previous example. Forms to External Resources --------------------------- -Rails' form helpers can also be used to build a form for posting data to an external resource. However, at times it can be necessary to set an `authenticity_token` for the resource; this can be done by passing an `authenticity_token: 'your_external_token'` parameter to the `form_tag` options: +Rails' form helpers can also be used to build a form for posting data to an external resource. However, at times it can be necessary to set an `authenticity_token` for the resource; this can be done by passing an `authenticity_token: 'your_external_token'` parameter to the `form_with` options: ```erb -<%= form_tag 'http://farfar.away/form', authenticity_token: 'external_token' do %> +<%= form_with url: 'http://farfar.away/form', authenticity_token: 'external_token' do %> Form contents <% end %> ``` @@ -849,23 +848,7 @@ Rails' form helpers can also be used to build a form for posting data to an exte Sometimes when submitting data to an external resource, like a payment gateway, the fields that can be used in the form are limited by an external API and it may be undesirable to generate an `authenticity_token`. To not send a token, simply pass `false` to the `:authenticity_token` option: ```erb -<%= form_tag 'http://farfar.away/form', authenticity_token: false do %> - Form contents -<% end %> -``` - -The same technique is also available for `form_for`: - -```erb -<%= form_for @invoice, url: external_url, authenticity_token: 'external_token' do |f| %> - Form contents -<% end %> -``` - -Or if you don't want to render an `authenticity_token` field: - -```erb -<%= form_for @invoice, url: external_url, authenticity_token: false do |f| %> +<%= form_with url: 'http://farfar.away/form', authenticity_token: false do %> Form contents <% end %> ``` @@ -897,7 +880,7 @@ This creates an `addresses_attributes=` method on `Person` that allows you to cr The following form allows a user to create a `Person` and its associated addresses. ```html+erb -<%= form_for @person do |f| %> +<%= form_with model: @person do |f| %> Addresses: <ul> <%= f.fields_for :addresses do |addresses_form| %> @@ -948,12 +931,12 @@ The `fields_for` yields a form builder. The parameters' name will be what The keys of the `:addresses_attributes` hash are unimportant, they need merely be different for each address. -If the associated object is already saved, `fields_for` autogenerates a hidden input with the `id` of the saved record. You can disable this by passing `include_id: false` to `fields_for`. You may wish to do this if the autogenerated input is placed in a location where an input tag is not valid HTML or when using an ORM where children do not have an `id`. +If the associated object is already saved, `fields_for` autogenerates a hidden input with the `id` of the saved record. You can disable this by passing `include_id: false` to `fields_for`. ### The Controller As usual you need to -[whitelist the parameters](action_controller_overview.html#strong-parameters) in +[declare the permitted parameters](action_controller_overview.html#strong-parameters) in the controller before you pass them to the model: ```ruby @@ -979,12 +962,12 @@ class Person < ApplicationRecord end ``` -If the hash of attributes for an object contains the key `_destroy` with a value -of `1` or `true` then the object will be destroyed. This form allows users to -remove addresses: +If the hash of attributes for an object contains the key `_destroy` with a value that +evaluates to `true` (eg. 1, '1', true, or 'true') then the object will be destroyed. +This form allows users to remove addresses: ```erb -<%= form_for @person do |f| %> +<%= form_with model: @person do |f| %> Addresses: <ul> <%= f.fields_for :addresses do |addresses_form| %> @@ -999,7 +982,7 @@ remove addresses: <% end %> ``` -Don't forget to update the whitelisted params in your controller to also include +Don't forget to update the permitted params in your controller to also include the `_destroy` field: ```ruby @@ -1024,4 +1007,9 @@ As a convenience you can instead pass the symbol `:all_blank` which will create ### Adding Fields on the Fly -Rather than rendering multiple sets of fields ahead of time you may wish to add them only when a user clicks on an 'Add new address' button. Rails does not provide any built-in support for this. When generating new sets of fields you must ensure the key of the associated array is unique - the current JavaScript date (milliseconds after the epoch) is a common choice. +Rather than rendering multiple sets of fields ahead of time you may wish to add them only when a user clicks on an 'Add new address' button. Rails does not provide any built-in support for this. When generating new sets of fields you must ensure the key of the associated array is unique - the current JavaScript date (milliseconds since the [epoch](https://en.wikipedia.org/wiki/Unix_time)) is a common choice. + +Using form_for and form_tag +--------------------------- + +Before `form_with` was introduced in Rails 5.1 its functionality used to be split between `form_tag` and `form_for`. Both are now soft-deprecated. Documentation on their usage can be found in [older versions of this guide](https://guides.rubyonrails.org/v5.2/form_helpers.html). diff --git a/guides/source/getting_started.md b/guides/source/getting_started.md index 88a13cdd70..197a198db7 100644 --- a/guides/source/getting_started.md +++ b/guides/source/getting_started.md @@ -779,10 +779,11 @@ extra fields with values that violated your application's integrity? They would be 'mass assigned' into your model and then into the database along with the good stuff - potentially breaking your application or worse. -We have to whitelist our controller parameters to prevent wrongful mass +We have to define our permitted controller parameters to prevent wrongful mass assignment. In this case, we want to both allow and require the `title` and `text` parameters for valid use of `create`. The syntax for this introduces -`require` and `permit`. The change will involve one line in the `create` action: +`require` and `permit`. The change will involve one line in the `create` +action: ```ruby @article = Article.new(params.require(:article).permit(:title, :text)) diff --git a/guides/source/i18n.md b/guides/source/i18n.md index 7843df5b18..78e5f27448 100644 --- a/guides/source/i18n.md +++ b/guides/source/i18n.md @@ -77,8 +77,8 @@ There are also attribute readers and writers for the following attributes: load_path # Announce your custom translation files locale # Get and set the current locale default_locale # Get and set the default locale -available_locales # Whitelist locales available for the application -enforce_available_locales # Enforce locale whitelisting (true or false) +available_locales # Permitted locales available for the application +enforce_available_locales # Enforce locale permission (true or false) exception_handler # Use a different exception_handler backend # Use a different backend ``` @@ -128,7 +128,7 @@ The load path must be specified before any translations are looked up. To change # Where the I18n library should search for translation files I18n.load_path += Dir[Rails.root.join('lib', 'locale', '*.{rb,yml}')] -# Whitelist locales available for the application +# Permitted locales available for the application I18n.available_locales = [:en, :pt] # Set default locale to something other than :en diff --git a/guides/source/layout.html.erb b/guides/source/layout.html.erb index e8a1bd4f3d..dd9175e312 100644 --- a/guides/source/layout.html.erb +++ b/guides/source/layout.html.erb @@ -1,20 +1,19 @@ <!DOCTYPE html> - -<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> +<html lang="en"> <head> -<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> -<meta name="viewport" content="width=device-width, initial-scale=1"/> - -<title><%= yield(:page_title) || 'Ruby on Rails Guides' %></title> -<link rel="stylesheet" type="text/css" href="stylesheets/style.css" /> -<link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print" /> - -<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shCore.css" /> -<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shThemeRailsGuides.css" /> - -<link rel="stylesheet" type="text/css" href="stylesheets/fixes.css" /> - -<link href="images/favicon.ico" rel="shortcut icon" type="image/x-icon" /> + <meta charset="utf-8"> + <meta name="viewport" content="width=device-width, initial-scale=1"> + <title><%= yield(:page_title) || 'Ruby on Rails Guides' %></title> + <link rel="stylesheet" type="text/css" href="stylesheets/style.css" data-turbolinks-track="reload"> + <link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print"> + <link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shCore.css" data-turbolinks-track="reload"> + <link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shThemeRailsGuides.css" data-turbolinks-track="reload"> + <link rel="stylesheet" type="text/css" href="stylesheets/fixes.css" data-turbolinks-track="reload"> + <link href="images/favicon.ico" rel="shortcut icon" type="image/x-icon" /> + <script src="javascripts/syntaxhighlighter.js" data-turbolinks-track="reload"></script> + <script src="javascripts/turbolinks.js" data-turbolinks-track="reload"></script> + <script src="javascripts/guides.js" data-turbolinks-track="reload"></script> + <script src="javascripts/responsive-tables.js" data-turbolinks-track="reload"></script> </head> <body class="guide"> <% if @edge %> @@ -95,12 +94,12 @@ </p> <p> Please contribute if you see any typos or factual errors. - To get started, you can read our <%= link_to 'documentation contributions', 'http://edgeguides.rubyonrails.org/contributing_to_ruby_on_rails.html#contributing-to-the-rails-documentation' %> section. + To get started, you can read our <%= link_to 'documentation contributions', 'https://edgeguides.rubyonrails.org/contributing_to_ruby_on_rails.html#contributing-to-the-rails-documentation' %> section. </p> <p> 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 - <%= link_to 'Edge Guides', 'http://edgeguides.rubyonrails.org' %> first to verify + <%= link_to 'Edge Guides', 'https://edgeguides.rubyonrails.org' %> first to verify if the issues are already fixed or not on the master branch. Check the <%= link_to 'Ruby on Rails Guides Guidelines', 'ruby_on_rails_guides_guidelines.html' %> for style and conventions. @@ -122,9 +121,5 @@ <%= render 'license' %> </div> </div> - - <script type="text/javascript" src="javascripts/syntaxhighlighter.js"></script> - <script type="text/javascript" src="javascripts/guides.js"></script> - <script type="text/javascript" src="javascripts/responsive-tables.js"></script> </body> </html> diff --git a/guides/source/routing.md b/guides/source/routing.md index 8c69e2600b..84de727c11 100644 --- a/guides/source/routing.md +++ b/guides/source/routing.md @@ -719,12 +719,12 @@ NOTE: There is an exception for the `format` constraint: while it's a method on ### Advanced Constraints -If you have a more advanced constraint, you can provide an object that responds to `matches?` that Rails should use. Let's say you wanted to route all users on a blacklist to the `BlacklistController`. You could do: +If you have a more advanced constraint, you can provide an object that responds to `matches?` that Rails should use. Let's say you wanted to route all users on a restricted list to the `RestrictedListController`. You could do: ```ruby -class BlacklistConstraint +class RestrictedListConstraint def initialize - @ips = Blacklist.retrieve_ips + @ips = RestrictedList.retrieve_ips end def matches?(request) @@ -733,8 +733,8 @@ class BlacklistConstraint end Rails.application.routes.draw do - get '*path', to: 'blacklist#index', - constraints: BlacklistConstraint.new + get '*path', to: 'restricted_list#index', + constraints: RestrictedListConstraint.new end ``` @@ -742,8 +742,8 @@ You can also specify constraints as a lambda: ```ruby Rails.application.routes.draw do - get '*path', to: 'blacklist#index', - constraints: lambda { |request| Blacklist.retrieve_ips.include?(request.remote_ip) } + get '*path', to: 'restricted_list#index', + constraints: lambda { |request| RestrictedList.retrieve_ips.include?(request.remote_ip) } end ``` diff --git a/guides/source/security.md b/guides/source/security.md index 9fbd252bb7..bb996cc39c 100644 --- a/guides/source/security.md +++ b/guides/source/security.md @@ -378,7 +378,7 @@ This will redirect the user to the main action if they tried to access a legacy http://www.example.com/site/legacy?param1=xy¶m2=23&host=www.attacker.com ``` -If it is at the end of the URL it will hardly be noticed and redirects the user to the attacker.com host. A simple countermeasure would be to _include only the expected parameters in a legacy action_ (again a whitelist approach, as opposed to removing unexpected parameters). _And if you redirect to a URL, check it with a whitelist or a regular expression_. +If it is at the end of the URL it will hardly be noticed and redirects the user to the attacker.com host. A simple countermeasure would be to _include only the expected parameters in a legacy action_ (again a permitted list approach, as opposed to removing unexpected parameters). _And if you redirect to a URL, check it with a permitted list or a regular expression_. #### Self-contained XSS @@ -394,7 +394,7 @@ NOTE: _Make sure file uploads don't overwrite important files, and process media Many web applications allow users to upload files. _File names, which the user may choose (partly), should always be filtered_ as an attacker could use a malicious file name to overwrite any file on the server. If you store file uploads at /var/www/uploads, and the user enters a file name like "../../../etc/passwd", it may overwrite an important file. Of course, the Ruby interpreter would need the appropriate permissions to do so - one more reason to run web servers, database servers, and other programs as a less privileged Unix user. -When filtering user input file names, _don't try to remove malicious parts_. Think of a situation where the web application removes all "../" in a file name and an attacker uses a string such as "....//" - the result will be "../". It is best to use a whitelist approach, which _checks for the validity of a file name with a set of accepted characters_. This is opposed to a blacklist approach which attempts to remove not allowed characters. In case it isn't a valid file name, reject it (or replace not accepted characters), but don't remove them. Here is the file name sanitizer from the [attachment_fu plugin](https://github.com/technoweenie/attachment_fu/tree/master): +When filtering user input file names, _don't try to remove malicious parts_. Think of a situation where the web application removes all "../" in a file name and an attacker uses a string such as "....//" - the result will be "../". It is best to use a permitted list approach, which _checks for the validity of a file name with a set of accepted characters_. This is opposed to a restricted list approach which attempts to remove not allowed characters. In case it isn't a valid file name, reject it (or replace not accepted characters), but don't remove them. Here is the file name sanitizer from the [attachment_fu plugin](https://github.com/technoweenie/attachment_fu/tree/master): ```ruby def sanitize_filename(filename) @@ -641,19 +641,19 @@ INFO: _Injection is a class of attacks that introduce malicious code or paramete Injection is very tricky, because the same code or parameter can be malicious in one context, but totally harmless in another. A context can be a scripting, query, or programming language, the shell, or a Ruby/Rails method. The following sections will cover all important contexts where injection attacks may happen. The first section, however, covers an architectural decision in connection with Injection. -### Whitelists versus Blacklists +### Permitted lists versus Restricted lists -NOTE: _When sanitizing, protecting, or verifying something, prefer whitelists over blacklists._ +NOTE: _When sanitizing, protecting, or verifying something, prefer permitted lists over restricted lists._ -A blacklist can be a list of bad e-mail addresses, non-public actions or bad HTML tags. This is opposed to a whitelist which lists the good e-mail addresses, public actions, good HTML tags, and so on. Although sometimes it is not possible to create a whitelist (in a SPAM filter, for example), _prefer to use whitelist approaches_: +A restricted list can be a list of bad e-mail addresses, non-public actions or bad HTML tags. This is opposed to a permitted list which lists the good e-mail addresses, public actions, good HTML tags, and so on. Although sometimes it is not possible to create a permitted list (in a SPAM filter, for example), _prefer to use permitted list approaches_: * Use before_action except: [...] instead of only: [...] for security-related actions. This way you don't forget to enable security checks for newly added actions. * Allow <strong> instead of removing <script> against Cross-Site Scripting (XSS). See below for details. -* Don't try to correct user input by blacklists: +* Don't try to correct user input using restricted lists: * This will make the attack work: "<sc<script>ript>".gsub("<script>", "") * But reject malformed input -Whitelists are also a good approach against the human factor of forgetting something in the blacklist. +Permitted lists are also a good approach against the human factor of forgetting something in the restricted list. ### SQL Injection @@ -810,15 +810,15 @@ http://www.cbsnews.com/stories/2002/02/15/weather_local/main501644.shtml?zipcode _It is very important to filter malicious input, but it is also important to escape the output of the web application_. -Especially for XSS, it is important to do _whitelist input filtering instead of blacklist_. Whitelist filtering states the values allowed as opposed to the values not allowed. Blacklists are never complete. +Especially for XSS, it is important to do _permitted input filtering instead of restricted_. Permitted list filtering states the values allowed as opposed to the values not allowed. Restricted lists are never complete. -Imagine a blacklist deletes "script" from the user input. Now the attacker injects "<scrscriptipt>", and after the filter, "<script>" remains. Earlier versions of Rails used a blacklist approach for the strip_tags(), strip_links() and sanitize() method. So this kind of injection was possible: +Imagine a restricted list deletes "script" from the user input. Now the attacker injects "<scrscriptipt>", and after the filter, "<script>" remains. Earlier versions of Rails used a restricted list approach for the strip_tags(), strip_links() and sanitize() method. So this kind of injection was possible: ```ruby strip_tags("some<<b>script>alert('hello')<</b>/script>") ``` -This returned "some<script>alert('hello')</script>", which makes an attack work. That's why a whitelist approach is better, using the updated Rails 2 method sanitize(): +This returned "some<script>alert('hello')</script>", which makes an attack work. That's why a permitted list approach is better, using the updated Rails 2 method sanitize(): ```ruby tags = %w(a acronym b strong i em li ul ol h1 h2 h3 h4 h5 h6 blockquote br cite sub sup ins p) @@ -852,7 +852,7 @@ The following is an excerpt from the [Js.Yamanner@m](http://www.symantec.com/sec var IDList = ''; var CRumb = ''; function makeRequest(url, Func, Method,Param) { ... ``` -The worms exploit a hole in Yahoo's HTML/JavaScript filter, which usually filters all targets and onload attributes from tags (because there can be JavaScript). The filter is applied only once, however, so the onload attribute with the worm code stays in place. This is a good example why blacklist filters are never complete and why it is hard to allow HTML/JavaScript in a web application. +The worms exploit a hole in Yahoo's HTML/JavaScript filter, which usually filters all targets and onload attributes from tags (because there can be JavaScript). The filter is applied only once, however, so the onload attribute with the worm code stays in place. This is a good example why restricted list filters are never complete and why it is hard to allow HTML/JavaScript in a web application. Another proof-of-concept webmail worm is Nduja, a cross-domain worm for four Italian webmail services. Find more details on [Rosario Valotta's paper](http://www.xssed.com/news/37/Nduja_Connection_A_cross_webmail_worm_XWW/). Both webmail worms have the goal to harvest email addresses, something a criminal hacker could make money with. @@ -876,7 +876,7 @@ So the payload is in the style attribute. But there are no quotes allowed in the <div id="mycode" expr="alert('hah!')" style="background:url('javascript:eval(document.all.mycode.expr)')"> ``` -The eval() function is a nightmare for blacklist input filters, as it allows the style attribute to hide the word "innerHTML": +The eval() function is a nightmare for restricted list input filters, as it allows the style attribute to hide the word "innerHTML": ``` alert(eval('document.body.inne' + 'rHTML')); @@ -896,7 +896,7 @@ The [moz-binding](http://www.securiteam.com/securitynews/5LP051FHPE.html) CSS pr #### Countermeasures -This example, again, showed that a blacklist filter is never complete. However, as custom CSS in web applications is a quite rare feature, it may be hard to find a good whitelist CSS filter. _If you want to allow custom colors or images, you can allow the user to choose them and build the CSS in the web application_. Use Rails' `sanitize()` method as a model for a whitelist CSS filter, if you really need one. +This example, again, showed that a restricted list filter is never complete. However, as custom CSS in web applications is a quite rare feature, it may be hard to find a good permitted CSS filter. _If you want to allow custom colors or images, you can allow the user to choose them and build the CSS in the web application_. Use Rails' `sanitize()` method as a model for a permitted CSS filter, if you really need one. ### Textile Injection @@ -925,7 +925,7 @@ RedCloth.new("<a href='javascript:alert(1)'>hello</a>", [:filter_html]).to_html #### Countermeasures -It is recommended to _use RedCloth in combination with a whitelist input filter_, as described in the countermeasures against XSS section. +It is recommended to _use RedCloth in combination with a permitted input filter_, as described in the countermeasures against XSS section. ### Ajax Injection diff --git a/guides/source/testing.md b/guides/source/testing.md index 01cda8e6e4..de93e1c653 100644 --- a/guides/source/testing.md +++ b/guides/source/testing.md @@ -1113,11 +1113,10 @@ end Now you can try running all the tests and they should pass. -NOTE: If you followed the steps in the Basic Authentication section, you'll need to add the following to the `setup` block to get all the tests passing: +NOTE: If you followed the steps in the Basic Authentication section, you'll need to add authorization to every request header to get all the tests passing: ```ruby -request.headers['Authorization'] = ActionController::HttpAuthentication::Basic. - encode_credentials('dhh', 'secret') +post articles_url, params: { article: { body: 'Rails is awesome!', title: 'Hello Rails' } }, headers: { Authorization: ActionController::HttpAuthentication::Basic.encode_credentials('dhh', 'secret') } ``` ### Available Request Types for Functional Tests diff --git a/guides/source/upgrading_ruby_on_rails.md b/guides/source/upgrading_ruby_on_rails.md index 319bc09be3..befd4e08c0 100644 --- a/guides/source/upgrading_ruby_on_rails.md +++ b/guides/source/upgrading_ruby_on_rails.md @@ -66,9 +66,18 @@ Overwrite /myapp/config/application.rb? (enter "h" for help) [Ynaqdh] Don't forget to review the difference, to see if there were any unexpected changes. +### Configure Framework Defaults + +The new Rails version might have different configuration defaults than the previous version. However, after following the steps described above, your application would still run with configuration defaults from the *previous* Rails version. That's because the value for `config.load_defaults` in `config/application.rb` has not been changed yet. + +To allow you to upgrade to new defaults one by one, the update task has created a file `config/initializers/new_framework_defaults.rb`. Once your application is ready to run with new defaults, you can remove this file and flip the `config.load_defaults` value. + + Upgrading from Rails 5.2 to Rails 6.0 ------------------------------------- +For more information on changes made to Rails 6.0 please see the [release notes](6_0_release_notes.html). + ### Force SSL The `force_ssl` method on controllers has been deprecated and will be removed in @@ -76,6 +85,17 @@ Rails 6.1. You are encouraged to enable `config.force_ssl` to enforce HTTPS connections throughout your application. If you need to exempt certain endpoints from redirection, you can use `config.ssl_options` to configure that behavior. +### Purpose in signed or encrypted cookie is now embedded in the cookies values + +To improve security, Rails now embeds the purpose information in encrypted or signed cookies value. +Rails can now thwart attacks that attempt to copy signed/encrypted value +of a cookie and use it as the value of another cookie. + +This new embed information make those cookies incompatible with versions of Rails older than 6.0. + +If you require your cookies to be read by 5.2 and older, or you are still validating your 6.0 deploy and want +to allow you to rollback set +`Rails.application.config.action_dispatch.use_cookies_with_metadata` to `false`. Upgrading from Rails 5.1 to Rails 5.2 ------------------------------------- |