aboutsummaryrefslogtreecommitdiffstats
path: root/guides/source
diff options
context:
space:
mode:
Diffstat (limited to 'guides/source')
-rw-r--r--guides/source/3_0_release_notes.md2
-rw-r--r--guides/source/3_1_release_notes.md2
-rw-r--r--guides/source/3_2_release_notes.md4
-rw-r--r--guides/source/4_0_release_notes.md2
-rw-r--r--guides/source/4_2_release_notes.md11
-rw-r--r--guides/source/_welcome.html.erb10
-rw-r--r--guides/source/action_controller_overview.md16
-rw-r--r--guides/source/action_mailer_basics.md25
-rw-r--r--guides/source/action_view_overview.md57
-rw-r--r--guides/source/active_job_basics.md71
-rw-r--r--guides/source/active_model_basics.md73
-rw-r--r--guides/source/active_record_basics.md4
-rw-r--r--guides/source/active_record_migrations.md84
-rw-r--r--guides/source/active_record_postgresql.md60
-rw-r--r--guides/source/active_record_querying.md51
-rw-r--r--guides/source/active_record_validations.md29
-rw-r--r--guides/source/active_support_core_extensions.md8
-rw-r--r--guides/source/active_support_instrumentation.md51
-rw-r--r--guides/source/api_app.md683
-rw-r--r--guides/source/api_documentation_guidelines.md7
-rw-r--r--guides/source/asset_pipeline.md8
-rw-r--r--guides/source/association_basics.md68
-rw-r--r--guides/source/caching_with_rails.md381
-rw-r--r--guides/source/command_line.md10
-rw-r--r--guides/source/configuring.md38
-rw-r--r--guides/source/contributing_to_ruby_on_rails.md15
-rw-r--r--guides/source/credits.html.erb2
-rw-r--r--guides/source/debugging_rails_applications.md55
-rw-r--r--guides/source/development_dependencies_install.md8
-rw-r--r--guides/source/documents.yaml4
-rw-r--r--guides/source/engines.md24
-rw-r--r--guides/source/form_helpers.md24
-rw-r--r--guides/source/generators.md8
-rw-r--r--guides/source/getting_started.md43
-rw-r--r--guides/source/i18n.md20
-rw-r--r--guides/source/kindle/layout.html.erb4
-rw-r--r--guides/source/kindle/toc.ncx.erb8
-rw-r--r--guides/source/layouts_and_rendering.md11
-rw-r--r--guides/source/plugins.md1
-rw-r--r--guides/source/rails_application_templates.md10
-rw-r--r--guides/source/rails_on_rack.md37
-rw-r--r--guides/source/routing.md30
-rw-r--r--guides/source/security.md86
-rw-r--r--guides/source/testing.md656
-rw-r--r--guides/source/upgrading_ruby_on_rails.md40
-rw-r--r--guides/source/working_with_javascript_in_rails.md4
46 files changed, 1574 insertions, 1271 deletions
diff --git a/guides/source/3_0_release_notes.md b/guides/source/3_0_release_notes.md
index 9ad32e8168..696493a3cf 100644
--- a/guides/source/3_0_release_notes.md
+++ b/guides/source/3_0_release_notes.md
@@ -88,7 +88,7 @@ $ cd myapp
Rails now uses a `Gemfile` in the application root to determine the gems you require for your application to start. This `Gemfile` is processed by the [Bundler](http://github.com/carlhuda/bundler,) which then installs all your dependencies. It can even install all the dependencies locally to your application so that it doesn't depend on the system gems.
-More information: - [bundler homepage](http://gembundler.com)
+More information: - [bundler homepage](http://bundler.io/)
### Living on the Edge
diff --git a/guides/source/3_1_release_notes.md b/guides/source/3_1_release_notes.md
index d753346fa3..327495704a 100644
--- a/guides/source/3_1_release_notes.md
+++ b/guides/source/3_1_release_notes.md
@@ -151,7 +151,7 @@ $ cd myapp
Rails now uses a `Gemfile` in the application root to determine the gems you require for your application to start. This `Gemfile` is processed by the [Bundler](https://github.com/carlhuda/bundler) gem, which then installs all your dependencies. It can even install all the dependencies locally to your application so that it doesn't depend on the system gems.
-More information: - [bundler homepage](http://gembundler.com)
+More information: - [bundler homepage](http://bundler.io/)
### Living on the Edge
diff --git a/guides/source/3_2_release_notes.md b/guides/source/3_2_release_notes.md
index 6ddf77d9c0..f6871c186e 100644
--- a/guides/source/3_2_release_notes.md
+++ b/guides/source/3_2_release_notes.md
@@ -81,7 +81,7 @@ $ cd myapp
Rails now uses a `Gemfile` in the application root to determine the gems you require for your application to start. This `Gemfile` is processed by the [Bundler](https://github.com/carlhuda/bundler) gem, which then installs all your dependencies. It can even install all the dependencies locally to your application so that it doesn't depend on the system gems.
-More information: [Bundler homepage](http://gembundler.com)
+More information: [Bundler homepage](http://bundler.io/)
### Living on the Edge
@@ -327,7 +327,7 @@ Active Record
* Implemented `ActiveRecord::Relation#explain`.
-* Implements `AR::Base.silence_auto_explain` which allows the user to selectively disable automatic EXPLAINs within a block.
+* Implements `ActiveRecord::Base.silence_auto_explain` which allows the user to selectively disable automatic EXPLAINs within a block.
* Implements automatic EXPLAIN logging for slow queries. A new configuration parameter `config.active_record.auto_explain_threshold_in_seconds` determines what's to be considered a slow query. Setting that to nil disables this feature. Defaults are 0.5 in development mode, and nil in test and production modes. Rails 3.2 supports this feature in SQLite, MySQL (mysql2 adapter), and PostgreSQL.
diff --git a/guides/source/4_0_release_notes.md b/guides/source/4_0_release_notes.md
index 9feaff098a..b9444510ea 100644
--- a/guides/source/4_0_release_notes.md
+++ b/guides/source/4_0_release_notes.md
@@ -36,7 +36,7 @@ $ cd myapp
Rails now uses a `Gemfile` in the application root to determine the gems you require for your application to start. This `Gemfile` is processed by the [Bundler](https://github.com/carlhuda/bundler) gem, which then installs all your dependencies. It can even install all the dependencies locally to your application so that it doesn't depend on the system gems.
-More information: [Bundler homepage](http://gembundler.com)
+More information: [Bundler homepage](http://bundler.io)
### Living on the Edge
diff --git a/guides/source/4_2_release_notes.md b/guides/source/4_2_release_notes.md
index 684bd286bc..8a59007420 100644
--- a/guides/source/4_2_release_notes.md
+++ b/guides/source/4_2_release_notes.md
@@ -227,6 +227,17 @@ restore the old behavior.
If you do this, be sure to configure your firewall properly such that only
trusted machines on your network can access your development server.
+### Changed status option symbols for `render`
+
+Due to a [change in Rack](https://github.com/rack/rack/commit/be28c6a2ac152fe4adfbef71f3db9f4200df89e8), the symbols that the `render` method accepts for the `:status` option have changed:
+
+- 306: `:reserved` has been removed.
+- 413: `:request_entity_too_large` has been renamed to `:payload_too_large`.
+- 414: `:request_uri_too_long` has been renamed to `:uri_too_long`.
+- 416: `:requested_range_not_satisfiable` has been renamed to `:range_not_satisfiable`.
+
+Keep in mind that if calling `render` with an unknown symbol, the response status will default to 500.
+
### HTML Sanitizer
The HTML sanitizer has been replaced with a new, more robust, implementation
diff --git a/guides/source/_welcome.html.erb b/guides/source/_welcome.html.erb
index 67f5f1cdd5..f50bcddbe7 100644
--- a/guides/source/_welcome.html.erb
+++ b/guides/source/_welcome.html.erb
@@ -16,9 +16,9 @@
<% end %>
<p>
The guides for earlier releases:
-<a href="http://guides.rubyonrails.org/v4.2.0/">Rails 4.2.0</a>,
-<a href="http://guides.rubyonrails.org/v4.1.8/">Rails 4.1.8</a>,
-<a href="http://guides.rubyonrails.org/v4.0.12/">Rails 4.0.12</a>,
-<a href="http://guides.rubyonrails.org/v3.2.21/">Rails 3.2.21</a> and
-<a href="http://guides.rubyonrails.org/v2.3.11/">Rails 2.3.11</a>.
+<a href="http://guides.rubyonrails.org/v4.2/">Rails 4.2</a>,
+<a href="http://guides.rubyonrails.org/v4.1/">Rails 4.1</a>,
+<a href="http://guides.rubyonrails.org/v4.0/">Rails 4.0</a>,
+<a href="http://guides.rubyonrails.org/v3.2/">Rails 3.2</a>, and
+<a href="http://guides.rubyonrails.org/v2.3/">Rails 2.3</a>.
</p>
diff --git a/guides/source/action_controller_overview.md b/guides/source/action_controller_overview.md
index 7d95d4792e..7e43ba375a 100644
--- a/guides/source/action_controller_overview.md
+++ b/guides/source/action_controller_overview.md
@@ -185,7 +185,9 @@ end
These options will be used as a starting point when generating URLs, so it's possible they'll be overridden by the options passed to `url_for` calls.
-If you define `default_url_options` in `ApplicationController`, as in the example above, it will be used for all URL generation. The method can also be defined in a specific controller, in which case it only affects URLs generated there.
+If you define `default_url_options` in `ApplicationController`, as in the example above, these defaults will be used for all URL generation. The method can also be defined in a specific controller, in which case it only affects URLs generated there.
+
+In a given request, the method is not actually called for every single generated URL; for performance reasons, the returned hash is cached, there is at most one invocation per request.
### Strong Parameters
@@ -736,7 +738,7 @@ You can choose not to yield and build the response yourself, in which case the a
While the most common way to use filters is by creating private methods and using *_action to add them, there are two other ways to do the same thing.
-The first is to use a block directly with the *\_action methods. The block receives the controller as an argument, and the `require_login` filter from above could be rewritten to use a block:
+The first is to use a block directly with the *\_action methods. The block receives the controller as an argument. The `require_login` filter from above could be rewritten to use a block:
```ruby
class ApplicationController < ActionController::Base
@@ -808,7 +810,7 @@ The [Security Guide](security.html) has more about this and a lot of other secur
The Request and Response Objects
--------------------------------
-In every controller there are two accessor methods pointing to the request and the response objects associated with the request cycle that is currently in execution. The `request` method contains an instance of `AbstractRequest` and the `response` method returns a response object representing what is going to be sent back to the client.
+In every controller there are two accessor methods pointing to the request and the response objects associated with the request cycle that is currently in execution. The `request` method contains an instance of `ActionDispatch::Request` and the `response` method returns a response object representing what is going to be sent back to the client.
### The `request` Object
@@ -1027,7 +1029,7 @@ There are a couple of things to notice in the above example. We need to make
sure to close the response stream. Forgetting to close the stream will leave
the socket open forever. We also have to set the content type to `text/event-stream`
before we write to the response stream. This is because headers cannot be written
-after the response has been committed (when `response.committed` returns a truthy
+after the response has been committed (when `response.committed?` returns a truthy
value), which occurs when you `write` or `commit` the response stream.
#### Example Usage
@@ -1112,11 +1114,11 @@ Rescue
Most likely your application is going to contain bugs or otherwise throw an exception that needs to be handled. For example, if the user follows a link to a resource that no longer exists in the database, Active Record will throw the `ActiveRecord::RecordNotFound` exception.
-Rails' default exception handling displays a "500 Server Error" message for all exceptions. If the request was made locally, a nice traceback and some added information gets displayed so you can figure out what went wrong and deal with it. If the request was remote Rails will just display a simple "500 Server Error" message to the user, or a "404 Not Found" if there was a routing error or a record could not be found. Sometimes you might want to customize how these errors are caught and how they're displayed to the user. There are several levels of exception handling available in a Rails application:
+Rails default exception handling displays a "500 Server Error" message for all exceptions. If the request was made locally, a nice traceback and some added information gets displayed so you can figure out what went wrong and deal with it. If the request was remote Rails will just display a simple "500 Server Error" message to the user, or a "404 Not Found" if there was a routing error or a record could not be found. Sometimes you might want to customize how these errors are caught and how they're displayed to the user. There are several levels of exception handling available in a Rails application:
### The Default 500 and 404 Templates
-By default a production application will render either a 404 or a 500 error message. These messages are contained in static HTML files in the `public` folder, in `404.html` and `500.html` respectively. You can customize these files to add some extra information and layout, but remember that they are static; i.e. you can't use RHTML or layouts in them, just plain HTML.
+By default a production application will render either a 404 or a 500 error message. These messages are contained in static HTML files in the `public` folder, in `404.html` and `500.html` respectively. You can customize these files to add some extra information and style, but remember that they are static HTML; i.e. you can't use ERB, SCSS, CoffeeScript, or layouts for them.
### `rescue_from`
@@ -1172,7 +1174,7 @@ end
WARNING: You shouldn't do `rescue_from Exception` or `rescue_from StandardError` unless you have a particular reason as it will cause serious side-effects (e.g. you won't be able to see exception details and tracebacks during development).
-NOTE: Certain exceptions are only rescuable from the `ApplicationController` class, as they are raised before the controller gets initialized and the action gets executed. See Pratik Naik's [article](http://m.onkey.org/2008/7/20/rescue-from-dispatching) on the subject for more information.
+NOTE: Certain exceptions are only rescuable from the `ApplicationController` class, as they are raised before the controller gets initialized and the action gets executed.
Force HTTPS protocol
--------------------
diff --git a/guides/source/action_mailer_basics.md b/guides/source/action_mailer_basics.md
index bf3bf5d19e..4800cece82 100644
--- a/guides/source/action_mailer_basics.md
+++ b/guides/source/action_mailer_basics.md
@@ -326,7 +326,7 @@ key. The list of emails can be an array of email addresses or a single string
with the addresses separated by commas.
```ruby
-class AdminMailer < ActionMailer::Base
+class AdminMailer < ApplicationMailer
default to: Proc.new { Admin.pluck(:email) },
from: 'notification@example.com'
@@ -533,6 +533,24 @@ url helper.
NOTE: non-`GET` links require [jQuery UJS](https://github.com/rails/jquery-ujs)
and won't work in mailer templates. They will result in normal `GET` requests.
+### Adding images in Action Mailer Views
+
+Unlike controllers, the mailer instance doesn't have any context about the
+incoming request so you'll need to provide the `:asset_host` parameter yourself.
+
+As the `:asset_host` usually is consistent across the application you can
+configure it globally in config/application.rb:
+
+```ruby
+config.action_mailer.asset_host = 'http://example.com'
+```
+
+Now you can display an image inside your email.
+
+```ruby
+<%= image_tag 'image.jpg' %>
+```
+
### Sending Multipart Emails
Action Mailer will automatically send multipart emails if you have different
@@ -696,7 +714,7 @@ files (environment.rb, production.rb, etc...)
| Configuration | Description |
|---------------|-------------|
|`logger`|Generates information on the mailing run if available. Can be set to `nil` for no logging. Compatible with both Ruby's own `Logger` and `Log4r` loggers.|
-|`smtp_settings`|Allows detailed configuration for `:smtp` delivery method:<ul><li>`:address` - Allows you to use a remote mail server. Just change it from its default `"localhost"` setting.</li><li>`:port` - On the off chance that your mail server doesn't run on port 25, you can change it.</li><li>`:domain` - If you need to specify a HELO domain, you can do it here.</li><li>`:user_name` - If your mail server requires authentication, set the username in this setting.</li><li>`:password` - If your mail server requires authentication, set the password in this setting.</li><li>`:authentication` - If your mail server requires authentication, you need to specify the authentication type here. This is a symbol and one of `:plain`, `:login`, `:cram_md5`.</li><li>`:enable_starttls_auto` - Set this to `false` if there is a problem with your server certificate that you cannot resolve.</li></ul>|
+|`smtp_settings`|Allows detailed configuration for `:smtp` delivery method:<ul><li>`:address` - Allows you to use a remote mail server. Just change it from its default `"localhost"` setting.</li><li>`:port` - On the off chance that your mail server doesn't run on port 25, you can change it.</li><li>`:domain` - If you need to specify a HELO domain, you can do it here.</li><li>`:user_name` - If your mail server requires authentication, set the username in this setting.</li><li>`:password` - If your mail server requires authentication, set the password in this setting.</li><li>`:authentication` - If your mail server requires authentication, you need to specify the authentication type here. This is a symbol and one of `:plain` (will send the password in the clear), `:login` (will send password Base64 encoded) or `:cram_md5` (combines a Challenge/Response mechanism to exchange information and a cryptographic Message Digest 5 algorithm to hash important information)</li><li>`:enable_starttls_auto` - Detects if STARTTLS is enabled in your SMTP server and starts to use it. Defaults to `true`.</li><li>`:openssl_verify_mode` - When using TLS, you can set how OpenSSL checks the certificate. This is really useful if you need to validate a self-signed and/or a wildcard certificate. You can use the name of an OpenSSL verify constant ('none', 'peer', 'client_once', 'fail_if_no_peer_cert') or directly the constant (`OpenSSL::SSL::VERIFY_NONE`, `OpenSSL::SSL::VERIFY_PEER`, ...).</li></ul>|
|`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 -t`.</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.|
@@ -741,6 +759,9 @@ config.action_mailer.smtp_settings = {
authentication: 'plain',
enable_starttls_auto: true }
```
+Note: As of July 15, 2014, Google increased [its security measures](https://support.google.com/accounts/answer/6010255) and now blocks attempts from apps it deems less secure.
+You can change your gmail settings [here](https://www.google.com/settings/security/lesssecureapps) to allow the attempts or
+use another ESP to send email by replacing 'smtp.gmail.com' above with the address of your provider.
Mailer Testing
--------------
diff --git a/guides/source/action_view_overview.md b/guides/source/action_view_overview.md
index 09fac41491..4b0e9bff7c 100644
--- a/guides/source/action_view_overview.md
+++ b/guides/source/action_view_overview.md
@@ -15,7 +15,7 @@ After reading this guide, you will know:
What is Action View?
--------------------
-Action View and Action Controller are the two major components of Action Pack. In Rails, web requests are handled by Action Pack, which splits the work into a controller part (performing the logic) and a view part (rendering a template). Typically, Action Controller will be concerned with communicating with the database and performing CRUD actions where necessary. Action View is then responsible for compiling the response.
+In Rails, web requests are handled by [Action Controller](action_controller_overview.html) and Action View. Typically, Action Controller will be concerned with communicating with the database and performing CRUD actions where necessary. Action View is then responsible for compiling the response.
Action View templates are written using embedded Ruby in tags mingled with HTML. To avoid cluttering the templates with boilerplate code, a number of helper classes provide common behavior for forms, dates, and strings. It's also easy to add new helpers to your application as it evolves.
@@ -147,6 +147,39 @@ xml.rss("version" => "2.0", "xmlns:dc" => "http://purl.org/dc/elements/1.1/") do
end
```
+#### Jbuilder
+[Jbuilder](https://github.com/rails/jbuilder) is a gem that's
+maintained by the Rails team and included in the default Rails Gemfile.
+It's similar to Builder, but is used to generate JSON, instead of XML.
+
+If you don't have it, you can add the following to your Gemfile:
+
+```ruby
+gem 'jbuilder'
+```
+
+A Jbuilder object named `json` is automatically made available to templates with
+a `.jbuilder` extension.
+
+Here is a basic example:
+
+```ruby
+json.name("Alex")
+json.email("alex@example.com")
+```
+
+would produce:
+
+```json
+{
+ "name": "Alex",
+ "email: "alex@example.com"
+}
+```
+
+See the [Jbuilder documention](https://github.com/rails/jbuilder#jbuilder) for
+more examples and information.
+
#### Template Caching
By default, Rails will compile each template to a method in order to render it. When you alter a template, Rails will check the file's modification time and recompile it in development mode.
@@ -725,7 +758,7 @@ Returns a select tag with options for each of the seconds 0 through 59 with the
```ruby
# Generates a select field for seconds that defaults to the seconds for the time provided
-select_second(Time.now + 16.minutes)
+select_second(Time.now + 16.seconds)
```
#### select_time
@@ -1059,14 +1092,6 @@ If `@article.author_ids` is [1], this would return:
<input name="article[author_ids][]" type="hidden" value="" />
```
-#### country_options_for_select
-
-Returns a string of option tags for pretty much any country in the world.
-
-#### country_select
-
-Returns select and option tags for the given object and method, using country_options_for_select to generate the list of option tags.
-
#### option_groups_from_collection_for_select
Returns a string of `option` tags, like `options_from_collection_for_select`, but groups them by `optgroup` tags based on the object relationships of the arguments.
@@ -1153,8 +1178,8 @@ If `@article.person_id` is 1, this would become:
<select name="article[person_id]">
<option value=""></option>
<option value="1" selected="selected">David</option>
- <option value="2">Sam</option>
- <option value="3">Tobias</option>
+ <option value="2">Eileen</option>
+ <option value="3">Rafael</option>
</select>
```
@@ -1222,7 +1247,7 @@ file_field_tag 'attachment'
#### form_tag
-Starts a form tag that points the action to an url configured with `url_for_options` just like `ActionController::Base#url_for`.
+Starts a form tag that points the action to a url configured with `url_for_options` just like `ActionController::Base#url_for`.
```html+erb
<%= form_tag '/articles' do %>
@@ -1429,7 +1454,7 @@ This sanitize helper will HTML encode all tags and strip all attributes that are
sanitize @article.body
```
-If either the `:attributes` or `:tags` options are passed, only the mentioned tags and attributes are allowed and nothing else.
+If either the `:attributes` or `:tags` options are passed, only the mentioned attributes and tags are allowed and nothing else.
```ruby
sanitize @article.body, tags: %w(table tr td), attributes: %w(id class style)
@@ -1451,12 +1476,12 @@ Sanitizes a block of CSS code.
Strips all link tags from text leaving just the link text.
```ruby
-strip_links("<a href="http://rubyonrails.org">Ruby on Rails</a>")
+strip_links('<a href="http://rubyonrails.org">Ruby on Rails</a>')
# => Ruby on Rails
```
```ruby
-strip_links("emails to <a href="mailto:me@email.com">me@email.com</a>.")
+strip_links('emails to <a href="mailto:me@email.com">me@email.com</a>.')
# => emails to me@email.com.
```
diff --git a/guides/source/active_job_basics.md b/guides/source/active_job_basics.md
index 29d0c32b09..17087d187a 100644
--- a/guides/source/active_job_basics.md
+++ b/guides/source/active_job_basics.md
@@ -4,7 +4,7 @@ Active Job Basics
=================
This guide provides you with all you need to get started in creating,
-enqueueing and executing background jobs.
+enqueuing and executing background jobs.
After reading this guide, you will know:
@@ -20,7 +20,7 @@ Introduction
------------
Active Job is a framework for declaring jobs and making them run on a variety
-of queueing backends. These jobs can be everything from regularly scheduled
+of queuing backends. These jobs can be everything from regularly scheduled
clean-ups, to billing charges, to mailings. Anything that can be chopped up
into small units of work and run in parallel, really.
@@ -28,11 +28,14 @@ into small units of work and run in parallel, really.
The Purpose of Active Job
-----------------------------
The main point is to ensure that all Rails apps will have a job infrastructure
-in place, even if it's in the form of an "immediate runner". We can then have
-framework features and other gems build on top of that, without having to
-worry about API differences between various job runners such as Delayed Job
-and Resque. Picking your queuing backend becomes more of an operational concern,
-then. And you'll be able to switch between them without having to rewrite your jobs.
+in place. We can then have framework features and other gems build on top of that,
+without having to worry about API differences between various job runners such as
+Delayed Job and Resque. Picking your queuing backend becomes more of an operational
+concern, then. And you'll be able to switch between them without having to rewrite
+your jobs.
+
+NOTE: Rails by default comes with an "immediate runner" queuing implementation.
+That means that each job that has been enqueued will run immediately.
Creating a Job
@@ -67,49 +70,59 @@ Here's what a job looks like:
class GuestsCleanupJob < ActiveJob::Base
queue_as :default
- def perform(*args)
+ def perform(*guests)
# Do something later
end
end
```
+Note that you can define `perform` with as many arguments as you want.
+
### Enqueue the Job
Enqueue a job like so:
```ruby
-# Enqueue a job to be performed as soon the queueing system is
+# Enqueue a job to be performed as soon the queuing system is
# free.
-MyJob.perform_later record
+GuestsCleanupJob.perform_later guest
```
```ruby
# Enqueue a job to be performed tomorrow at noon.
-MyJob.set(wait_until: Date.tomorrow.noon).perform_later(record)
+GuestsCleanupJob.set(wait_until: Date.tomorrow.noon).perform_later(guest)
```
```ruby
# Enqueue a job to be performed 1 week from now.
-MyJob.set(wait: 1.week).perform_later(record)
+GuestsCleanupJob.set(wait: 1.week).perform_later(guest)
```
-That's it!
+```ruby
+# `perform_now` and `perform_later` will call `perform` under the hood so
+# you can pass as many arguments as defined in the latter.
+GuestsCleanupJob.perform_later(guest1, guest2, filter: 'some_filter')
+```
+That's it!
Job Execution
-------------
-If no adapter is set, the job is immediately executed.
+For enqueuing and executing jobs you need to set up a queuing backend, that is to
+say you need to decide for a 3rd-party queuing library that Rails should use.
+Rails itself does not provide a sophisticated queuing system and just executes the
+job immediately if no adapter is set.
### Backends
-Active Job has built-in adapters for multiple queueing backends (Sidekiq,
+Active Job has built-in adapters for multiple queuing backends (Sidekiq,
Resque, Delayed Job and others). To get an up-to-date list of the adapters
see the API Documentation for [ActiveJob::QueueAdapters](http://api.rubyonrails.org/classes/ActiveJob/QueueAdapters.html).
### Setting the Backend
-You can easily set your queueing backend:
+You can easily set your queuing backend:
```ruby
# config/application.rb
@@ -123,6 +136,10 @@ module YourApp
end
```
+NOTE: Since jobs run in parallel to your Rails application, most queuing libraries
+require that you start a library-specific queuing service (in addition to
+starting your Rails app) for the job processing to work. For information on
+how to do that refer to the documentation of your respective library.
Queues
------
@@ -212,7 +229,7 @@ end
ProcessVideoJob.perform_later(Video.last)
```
-NOTE: Make sure your queueing backend "listens" on your queue name. For some
+NOTE: Make sure your queuing backend "listens" on your queue name. For some
backends you need to specify the queues to listen to.
@@ -270,6 +287,19 @@ UserMailer.welcome(@user).deliver_later
```
+Internationalization
+--------------------
+
+Each job uses the `I18n.locale` set when the job was created. Useful if you send
+emails asynchronously:
+
+```ruby
+I18n.locale = :eo
+
+UserMailer.welcome(@user).deliver_later # Email will be localized to Esperanto.
+```
+
+
GlobalID
--------
@@ -320,6 +350,13 @@ class GuestsCleanupJob < ActiveJob::Base
end
```
+### Deserialization
+
+GlobalID allows serializing full Active Record objects passed to `#perform`.
+
+If a passed record is deleted after the job is enqueued but before the `#perform`
+method is called Active Job will raise an `ActiveJob::DeserializationError`
+exception.
Job Testing
--------------
diff --git a/guides/source/active_model_basics.md b/guides/source/active_model_basics.md
index 4b2bfaee2f..2bdbd792a8 100644
--- a/guides/source/active_model_basics.md
+++ b/guides/source/active_model_basics.md
@@ -8,12 +8,12 @@ classes. Active Model allows for Action Pack helpers to interact with
plain Ruby objects. Active Model also helps build custom ORMs for use
outside of the Rails framework.
-After reading this guide, you will be able to add to plain Ruby objects:
+After reading this guide, you will know:
-* The ability to behave like an Active Record model.
-* Callbacks and validations like Active Record.
-* Serializers.
-* Integration with the Rails internationalization (i18n) framework.
+* How an Active Record model behaves.
+* How Callbacks and validations work.
+* How serializers work.
+* The Rails internationalization (i18n) framework.
--------------------------------------------------------------------------------
@@ -156,7 +156,7 @@ person.changed? # => false
person.first_name = "First Name"
person.first_name # => "First Name"
-# returns if any attribute has changed.
+# returns true if any of the attributes have unsaved changes, false otherwise.
person.changed? # => true
# returns a list of attributes that have changed before saving.
@@ -319,9 +319,8 @@ person.serializable_hash # => {"name"=>"Bob"}
#### ActiveModel::Serializers
-Rails provides two serializers `ActiveModel::Serializers::JSON` and
-`ActiveModel::Serializers::Xml`. Both of these modules automatically include
-the `ActiveModel::Serialization`.
+Rails provides a `ActiveModel::Serializers::JSON` serializer.
+This module automatically include the `ActiveModel::Serialization`.
##### ActiveModel::Serializers::JSON
@@ -379,62 +378,6 @@ person.from_json(json) # => #<Person:0x00000100c773f0 @name="Bob">
person.name # => "Bob"
```
-##### ActiveModel::Serializers::Xml
-
-To use the `ActiveModel::Serializers::Xml` you only need to change from
-`ActiveModel::Serialization` to `ActiveModel::Serializers::Xml`.
-
-```ruby
-class Person
- include ActiveModel::Serializers::Xml
-
- attr_accessor :name
-
- def attributes
- {'name' => nil}
- end
-end
-```
-
-With the `to_xml` you have an XML representing the model.
-
-```ruby
-person = Person.new
-person.to_xml # => "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<person>\n <name nil=\"true\"/>\n</person>\n"
-person.name = "Bob"
-person.to_xml # => "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<person>\n <name>Bob</name>\n</person>\n"
-```
-
-From an XML string you define the attributes of the model.
-You need to have the `attributes=` method defined on your class:
-
-```ruby
-class Person
- include ActiveModel::Serializers::Xml
-
- attr_accessor :name
-
- def attributes=(hash)
- hash.each do |key, value|
- send("#{key}=", value)
- end
- end
-
- def attributes
- {'name' => nil}
- end
-end
-```
-
-Now it is possible to create an instance of person and set the attributes using `from_xml`.
-
-```ruby
-xml = { name: 'Bob' }.to_xml
-person = Person.new
-person.from_xml(xml) # => #<Person:0x00000100c773f0 @name="Bob">
-person.name # => "Bob"
-```
-
### Translation
`ActiveModel::Translation` provides integration between your object and the Rails
diff --git a/guides/source/active_record_basics.md b/guides/source/active_record_basics.md
index a227b54040..dafbe17bbd 100644
--- a/guides/source/active_record_basics.md
+++ b/guides/source/active_record_basics.md
@@ -142,7 +142,7 @@ end
This will create a `Product` model, mapped to a `products` table at the
database. By doing this you'll also have the ability to map the columns of each
row in that table with the attributes of the instances of your model. Suppose
-that the `products` table was created using an SQL sentence like:
+that the `products` table was created using an SQL statement like:
```sql
CREATE TABLE products (
@@ -260,7 +260,7 @@ david = User.find_by(name: 'David')
```ruby
# find all users named David who are Code Artists and sort by created_at in reverse chronological order
-users = User.where(name: 'David', occupation: 'Code Artist').order('created_at DESC')
+users = User.where(name: 'David', occupation: 'Code Artist').order(created_at: :desc)
```
You can learn more about querying an Active Record model in the [Active Record
diff --git a/guides/source/active_record_migrations.md b/guides/source/active_record_migrations.md
index ad069a112e..c5ac70143d 100644
--- a/guides/source/active_record_migrations.md
+++ b/guides/source/active_record_migrations.md
@@ -357,8 +357,8 @@ will append `ENGINE=BLACKHOLE` to the SQL statement used to create the table
### Creating a Join Table
-Migration method `create_join_table` creates an HABTM join table. A typical use
-would be:
+The migration method `create_join_table` creates an HABTM (has and belongs to
+many) join table. A typical use would be:
```ruby
create_join_table :products, :categories
@@ -367,23 +367,21 @@ create_join_table :products, :categories
which creates a `categories_products` table with two columns called
`category_id` and `product_id`. These columns have the option `:null` set to
`false` by default. This can be overridden by specifying the `:column_options`
-option.
+option:
```ruby
-create_join_table :products, :categories, column_options: {null: true}
+create_join_table :products, :categories, column_options: { null: true }
```
-will create the `product_id` and `category_id` with the `:null` option as
-`true`.
-
-You can pass the option `:table_name` when you want to customize the table
-name. For example:
+By default, the name of the join table comes from the union of the first two
+arguments provided to create_join_table, in alphabetical order.
+To customize the name of the table, provide a `:table_name` option:
```ruby
create_join_table :products, :categories, table_name: :categorization
```
-will create a `categorization` table.
+creates a `categorization` table.
`create_join_table` also accepts a block, which you can use to add indices
(which are not created by default) or additional columns:
@@ -423,21 +421,23 @@ change_column :products, :part_number, :text
```
This changes the column `part_number` on products table to be a `:text` field.
+Note that `change_column` command is irreversible.
Besides `change_column`, the `change_column_null` and `change_column_default`
-methods are used specifically to change a not null constraint and default values of a
-column.
+methods are used specifically to change a not null constraint and default
+values of a column.
```ruby
change_column_null :products, :name, false
-change_column_default :products, :approved, false
+change_column_default :products, :approved, from: true, to: false
```
This sets `:name` field on products to a `NOT NULL` column and the default
-value of the `:approved` field to false.
+value of the `:approved` field from true to false.
-TIP: Unlike `change_column` (and `change_column_default`), `change_column_null`
-is reversible.
+Note: You could also write the above `change_column_default` migration as
+`change_column_default :products, :approved, false`, but unlike the previous
+example, this would make your migration irreversible.
### Column Modifiers
@@ -475,7 +475,7 @@ column names can not be derived from the table names, you can use the
`:column` and `:primary_key` options.
Rails will generate a name for every foreign key starting with
-`fk_rails_` followed by 10 character which is deterministically
+`fk_rails_` followed by 10 characters which are deterministically
generated from the `from_table` and `column`.
There is a `:name` option to specify a different name if needed.
@@ -522,20 +522,27 @@ majority of cases, where Active Record knows how to reverse the migration
automatically. Currently, the `change` method supports only these migration
definitions:
-* `add_column`
-* `add_index`
-* `add_reference`
-* `add_timestamps`
-* `add_foreign_key`
-* `create_table`
-* `create_join_table`
-* `drop_table` (must supply a block)
-* `drop_join_table` (must supply a block)
-* `remove_timestamps`
-* `rename_column`
-* `rename_index`
-* `remove_reference`
-* `rename_table`
+* add_column
+* add_foreign_key
+* add_index
+* add_reference
+* add_timestamps
+* change_column_default (must supply a :from and :to option)
+* change_column_null
+* create_join_table
+* create_table
+* disable_extension
+* drop_join_table
+* drop_table (must supply a block)
+* enable_extension
+* remove_column (must supply a type)
+* remove_foreign_key (must supply a second table)
+* remove_index
+* remove_reference
+* remove_timestamps
+* rename_column
+* rename_index
+* rename_table
`change_table` is also reversible, as long as the block does not call `change`,
`change_default` or `remove`.
@@ -652,7 +659,7 @@ can't be done.
You can use Active Record's ability to rollback migrations using the `revert` method:
```ruby
-require_relative '2012121212_example_migration'
+require_relative '20121212123456_example_migration'
class FixupExampleMigration < ActiveRecord::Migration
def change
@@ -1004,7 +1011,10 @@ such features, the `execute` method can be used to execute arbitrary SQL.
Migrations and Seed Data
------------------------
-Some people use migrations to add data to the database:
+The main purpose of Rails' migration feature is to issue commands that modify the
+schema using a consistent process. Migrations can also be used
+to add or modify data. This is useful in an existing database that can't be destroyed
+and recreated, such as a production database.
```ruby
class AddInitialProducts < ActiveRecord::Migration
@@ -1020,9 +1030,11 @@ class AddInitialProducts < ActiveRecord::Migration
end
```
-However, Rails has a 'seeds' feature that should be used for seeding a database
-with initial data. It's a really simple feature: just fill up `db/seeds.rb`
-with some Ruby code, and run `rake db:seed`:
+To add initial data after a database is created, Rails has a built-in
+'seeds' feature that makes the process quick and easy. This is especially
+useful when reloading the database frequently in development and test environments.
+It's easy to get started with this feature: just fill up `db/seeds.rb` with some
+Ruby code, and run `rake db:seed`:
```ruby
5.times do |i|
diff --git a/guides/source/active_record_postgresql.md b/guides/source/active_record_postgresql.md
index dcc523eb0f..f71e6ccd57 100644
--- a/guides/source/active_record_postgresql.md
+++ b/guides/source/active_record_postgresql.md
@@ -220,11 +220,22 @@ normal text columns:
```ruby
# db/migrate/20131220144913_create_articles.rb
-execute <<-SQL
- CREATE TYPE article_status AS ENUM ('draft', 'published');
-SQL
-create_table :articles do |t|
- t.column :status, :article_status
+def up
+ execute <<-SQL
+ CREATE TYPE article_status AS ENUM ('draft', 'published');
+ SQL
+ create_table :articles do |t|
+ t.column :status, :article_status
+ end
+end
+
+# NOTE: It's important to drop table before dropping enum.
+def down
+ drop_table :articles
+
+ execute <<-SQL
+ DROP TYPE article_status;
+ SQL
end
# app/models/article.rb
@@ -240,6 +251,31 @@ article.status = "published"
article.save!
```
+To add a new value before/after existing one you should use [ALTER TYPE](http://www.postgresql.org/docs/current/static/sql-altertype.html):
+```ruby
+# db/migrate/20150720144913_add_new_state_to_articles.rb
+# NOTE: ALTER TYPE ... ADD VALUE cannot be executed inside of a transaction block so here we are using disable_ddl_transaction!
+disable_ddl_transaction!
+
+def up
+ execute <<-SQL
+ ALTER TYPE article_status ADD VALUE IF NOT EXISTS 'archived' AFTER 'published';
+ SQL
+end
+```
+
+NOTE: by now we can't drop ENUM values. You can read why [here](http://www.postgresql.org/message-id/29F36C7C98AB09499B1A209D48EAA615B7653DBC8A@mail2a.alliedtesting.com).
+
+Hint: to show all the values of the all enums you have, you should call this query in `bin/rails db` or `psql` console:
+```sql
+SELECT n.nspname AS enum_schema,
+ t.typname AS enum_name,
+ e.enumlabel AS enum_value
+ FROM pg_type t
+ JOIN pg_enum e ON t.oid = e.enumtypid
+ JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace
+```
+
### UUID
* [type definition](http://www.postgresql.org/docs/current/static/datatype-uuid.html)
@@ -252,7 +288,7 @@ extension to use uuid.
```ruby
# db/migrate/20131220144913_create_revisions.rb
create_table :revisions do |t|
- t.column :identifier, :uuid
+ t.uuid :identifier
end
# app/models/revision.rb
@@ -266,13 +302,14 @@ revision = Revision.first
revision.identifier # => "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11"
```
-You can use `uuid` type to define references in migrations
+You can use `uuid` type to define references in migrations:
```ruby
# db/migrate/20150418012400_create_blog.rb
-create_table :posts, id: :uuid
+enable_extension 'pgcrypto' unless extension_enabled?('pgcrypto')
+create_table :posts, id: :uuid, default: 'gen_random_uuid()'
-create_table :comments, id: :uuid do |t|
+create_table :comments, id: :uuid, default: 'gen_random_uuid()' do |t|
# t.belongs_to :post, type: :uuid
t.references :post, type: :uuid
end
@@ -288,6 +325,8 @@ class Comment < ActiveRecord::Base
end
```
+See [this section](#uuid-primary-keys) for more details on using UUIDs as primary key.
+
### Bit String Types
* [type definition](http://www.postgresql.org/docs/current/static/datatype-bit.html)
@@ -377,6 +416,9 @@ device = Device.create
device.id # => "814865cd-5a1d-4771-9306-4268f188fe9e"
```
+NOTE: `uuid_generate_v4()` (from `uuid-ossp`) is assumed if no `:default` option was
+passed to `create_table`.
+
Full Text Search
----------------
diff --git a/guides/source/active_record_querying.md b/guides/source/active_record_querying.md
index e3cfabb327..8ea0f383c0 100644
--- a/guides/source/active_record_querying.md
+++ b/guides/source/active_record_querying.md
@@ -10,7 +10,7 @@ After reading this guide, you will know:
* How to find records using a variety of methods and conditions.
* How to specify the order, retrieved attributes, grouping, and other properties of the found records.
* How to use eager loading to reduce the number of database queries needed for data retrieval.
-* How to use dynamic finders methods.
+* How to use dynamic finder methods.
* How to use method chaining to use multiple ActiveRecord methods together.
* How to check for the existence of particular records.
* How to perform various calculations on Active Record models.
@@ -341,8 +341,6 @@ User.find_each(begin_at: 2000, batch_size: 5000) do |user|
end
```
-Another example would be if you wanted multiple workers handling the same processing queue. You could have each worker handle 10000 records by setting the appropriate `:begin_at` option on each worker.
-
**`:end_at`**
Similar to the `:begin_at` option, `:end_at` allows you to configure the last ID of the sequence whenever the highest ID is not the one you need.
@@ -356,6 +354,10 @@ User.find_each(begin_at: 2000, end_at: 10000, batch_size: 5000) do |user|
end
```
+Another example would be if you wanted multiple workers handling the same
+processing queue. You could have each worker handle 10000 records by setting the
+appropriate `:begin_at` and `:end_at` options on each worker.
+
#### `find_in_batches`
The `find_in_batches` method is similar to `find_each`, since both retrieve batches of records. The difference is that `find_in_batches` yields _batches_ to the block as an array of models, instead of individually. The following example will yield to the supplied block an array of up to 1000 invoices at a time, with the final block containing any remaining invoices:
@@ -390,7 +392,7 @@ Now what if that number could vary, say as an argument from somewhere? The find
Client.where("orders_count = ?", params[:orders])
```
-Active Record will go through the first element in the conditions value and any additional elements will replace the question marks `(?)` in the first element.
+Active Record will take the first argument as the conditions string and any additional arguments will replace the question marks `(?)` in it.
If you want to specify multiple conditions:
@@ -418,7 +420,7 @@ TIP: For more information on the dangers of SQL injection, see the [Ruby on Rail
#### Placeholder Conditions
-Similar to the `(?)` replacement style of params, you can also specify keys/values hash in your array conditions:
+Similar to the `(?)` replacement style of params, you can also specify keys in your conditions string along with a corresponding keys/values hash:
```ruby
Client.where("created_at >= :start_date AND created_at <= :end_date",
@@ -429,7 +431,7 @@ This makes for clearer readability if you have a large number of variable condit
### Hash Conditions
-Active Record also allows you to pass in hash conditions which can increase the readability of your conditions syntax. With hash conditions, you pass in a hash with keys of the fields you want conditionalised and the values of how you want to conditionalise them:
+Active Record also allows you to pass in hash conditions which can increase the readability of your conditions syntax. With hash conditions, you pass in a hash with keys of the fields you want qualified and the values of how you want to qualify them:
NOTE: Only equality, range and subset checking are possible with Hash conditions.
@@ -529,7 +531,7 @@ Client.order("orders_count ASC, created_at DESC")
Client.order("orders_count ASC", "created_at DESC")
```
-If you want to call `order` multiple times e.g. in different context, new order will append previous one:
+If you want to call `order` multiple times, subsequent orders will be appended to the first:
```ruby
Client.order("orders_count ASC").order("created_at DESC")
@@ -617,9 +619,9 @@ SELECT * FROM clients LIMIT 5 OFFSET 30
Group
-----
-To apply a `GROUP BY` clause to the SQL fired by the finder, you can specify the `group` method on the find.
+To apply a `GROUP BY` clause to the SQL fired by the finder, you can use the `group` method.
-For example, if you want to find a collection of the dates orders were created on:
+For example, if you want to find a collection of the dates on which orders were created:
```ruby
Order.select("date(created_at) as ordered_date, sum(price) as total_price").group("date(created_at)")
@@ -637,7 +639,7 @@ GROUP BY date(created_at)
### Total of grouped items
-To get the total of grouped items on a single query call `count` after the `group`.
+To get the total of grouped items on a single query, call `count` after the `group`.
```ruby
Order.group(:status).count
@@ -673,7 +675,7 @@ GROUP BY date(created_at)
HAVING sum(price) > 100
```
-This will return single order objects for each day, but only those that are ordered more than $100 in a day.
+This returns the date and total price for each order object, grouped by the day they were ordered and where the price is more than $100.
Overriding Conditions
---------------------
@@ -703,8 +705,7 @@ Article.where(id: 10, trashed: false).unscope(where: :id)
# SELECT "articles".* FROM "articles" WHERE trashed = 0
```
-A relation which has used `unscope` will affect any relation it is
-merged in to:
+A relation which has used `unscope` will affect any relation into which it is merged:
```ruby
Article.order('id asc').merge(Article.unscope(:order))
@@ -748,7 +749,7 @@ SELECT * FROM articles WHERE id = 10
SELECT * FROM comments WHERE article_id = 10 ORDER BY name
```
-In case the `reorder` clause is not used, the SQL executed would be:
+In the case where the `reorder` clause is not used, the SQL executed would be:
```sql
SELECT * FROM articles WHERE id = 10
@@ -837,7 +838,7 @@ end
Readonly Objects
----------------
-Active Record provides `readonly` method on a relation to explicitly disallow modification of any of the returned objects. Any attempt to alter a readonly record will not succeed, raising an `ActiveRecord::ReadOnlyRecord` exception.
+Active Record provides the `readonly` method on a relation to explicitly disallow modification of any of the returned objects. Any attempt to alter a readonly record will not succeed, raising an `ActiveRecord::ReadOnlyRecord` exception.
```ruby
client = Client.readonly.first
@@ -1050,7 +1051,7 @@ SELECT categories.* FROM categories
### Specifying Conditions on the Joined Tables
-You can specify conditions on the joined tables using the regular [Array](#array-conditions) and [String](#pure-string-conditions) conditions. [Hash conditions](#hash-conditions) provides a special syntax for specifying conditions for the joined tables:
+You can specify conditions on the joined tables using the regular [Array](#array-conditions) and [String](#pure-string-conditions) conditions. [Hash conditions](#hash-conditions) provide a special syntax for specifying conditions for the joined tables:
```ruby
time_range = (Time.now.midnight - 1.day)..Time.now.midnight
@@ -1089,7 +1090,7 @@ This code looks fine at the first sight. But the problem lies within the total n
Active Record lets you specify in advance all the associations that are going to be loaded. This is possible by specifying the `includes` method of the `Model.find` call. With `includes`, Active Record ensures that all of the specified associations are loaded using the minimum possible number of queries.
-Revisiting the above case, we could rewrite `Client.limit(10)` to use eager load addresses:
+Revisiting the above case, we could rewrite `Client.limit(10)` to eager load addresses:
```ruby
clients = Client.includes(:address).limit(10)
@@ -1266,6 +1267,18 @@ class Client < ActiveRecord::Base
end
```
+NOTE: The `default_scope` is also applied while creating/building a record.
+It is not applied while updating a record. E.g.:
+
+```ruby
+class Client < ActiveRecord::Base
+ default_scope { where(active: true) }
+end
+
+Client.new # => #<Client id: nil, active: true>
+Client.unscoped.new # => #<Client id: nil, active: nil>
+```
+
### Merging of scopes
Just like `where` clauses scopes are merged using `AND` conditions.
@@ -1414,7 +1427,7 @@ It's common that you need to find a record or create it if it doesn't exist. You
### `find_or_create_by`
-The `find_or_create_by` method checks whether a record with the attributes exists. If it doesn't, then `create` is called. Let's see an example.
+The `find_or_create_by` method checks whether a record with the specified attributes exists. If it doesn't, then `create` is called. Let's see an example.
Suppose you want to find a client named 'Andy', and if there's none, create one. You can do so by running:
@@ -1854,6 +1867,6 @@ following pointers may be helpful:
* SQLite3: [EXPLAIN QUERY PLAN](http://www.sqlite.org/eqp.html)
-* MySQL: [EXPLAIN Output Format](http://dev.mysql.com/doc/refman/5.6/en/explain-output.html)
+* MySQL: [EXPLAIN Output Format](http://dev.mysql.com/doc/refman/5.7/en/explain-output.html)
* PostgreSQL: [Using EXPLAIN](http://www.postgresql.org/docs/current/static/using-explain.html)
diff --git a/guides/source/active_record_validations.md b/guides/source/active_record_validations.md
index 7932853c11..7f88c13dc0 100644
--- a/guides/source/active_record_validations.md
+++ b/guides/source/active_record_validations.md
@@ -242,7 +242,7 @@ end
>> person = Person.new
>> person.valid?
->> person.errors.details[:name] #=> [{error: :blank}]
+>> person.errors.details[:name] # => [{error: :blank}]
```
Using `details` with custom validators is covered in the [Working with
@@ -273,9 +273,13 @@ available helpers.
This method validates that a checkbox on the user interface was checked when a
form was submitted. This is typically used when the user needs to agree to your
application's terms of service, confirm that some text is read, or any similar
-concept. This validation is very specific to web applications and this
-'acceptance' does not need to be recorded anywhere in your database (if you
-don't have a field for it, the helper will just create a virtual attribute).
+concept.
+
+This validation is very specific to web applications and this
+'acceptance' does not need to be recorded anywhere in your database. If you
+don't have a field for it, the helper will just create a virtual attribute. If
+the field does exist in your database, the `accept` option must be set to
+`true` or else the validation will not run.
```ruby
class Person < ActiveRecord::Base
@@ -348,6 +352,16 @@ class Person < ActiveRecord::Base
end
```
+There is also a `:case_sensitive` option that you can use to define whether the
+confirmation constraint will be case sensitive or not. This option defaults to
+true.
+
+```ruby
+class Person < ActiveRecord::Base
+ validates :email, confirmation: { case_sensitive: false }
+end
+```
+
The default error message for this helper is _"doesn't match confirmation"_.
### `exclusion`
@@ -626,7 +640,7 @@ class Holiday < ActiveRecord::Base
message: "should happen once per year" }
end
```
-Should you wish to create a database constraint to prevent possible violations of a uniqueness validation using the `:scope` option, you must create a unique index on both columns in your database. See [the MySQL manual](http://dev.mysql.com/doc/refman/5.6/en/multiple-column-indexes.html) for more details about multiple column indexes or [the PostgreSQL manual](http://www.postgresql.org/docs/current/static/ddl-constraints.html) for examples of unique constraints that refer to a group of columns.
+Should you wish to create a database constraint to prevent possible violations of a uniqueness validation using the `:scope` option, you must create a unique index on both columns in your database. See [the MySQL manual](http://dev.mysql.com/doc/refman/5.7/en/multiple-column-indexes.html) for more details about multiple column indexes or [the PostgreSQL manual](http://www.postgresql.org/docs/current/static/ddl-constraints.html) for examples of unique constraints that refer to a group of columns.
There is also a `:case_sensitive` option that you can use to define whether the
uniqueness constraint will be case sensitive or not. This option defaults to
@@ -965,8 +979,9 @@ own custom validators.
You can also create methods that verify the state of your models and add
messages to the `errors` collection when they are invalid. You must then
-register these methods by using the `validate` class method, passing in the
-symbols for the validation methods' names.
+register these methods by using the `validate`
+([API](http://api.rubyonrails.org/classes/ActiveModel/Validations/ClassMethods.html#method-i-validate))
+class method, passing in the symbols for the validation methods' names.
You can pass more than one symbol for each class method and the respective
validations will be run in the same order as they were registered.
diff --git a/guides/source/active_support_core_extensions.md b/guides/source/active_support_core_extensions.md
index 01bf928407..5a68f6c869 100644
--- a/guides/source/active_support_core_extensions.md
+++ b/guides/source/active_support_core_extensions.md
@@ -172,7 +172,7 @@ NOTE: Defined in `active_support/core_ext/object/duplicable.rb`.
### `deep_dup`
-The `deep_dup` method returns deep copy of a given object. Normally, when you `dup` an object that contains other objects, Ruby does not `dup` them, so it creates a shallow copy of the object. If you have an array with a string, for example, it will look like this:
+The `deep_dup` method returns a deep copy of a given object. Normally, when you `dup` an object that contains other objects, Ruby does not `dup` them, so it creates a shallow copy of the object. If you have an array with a string, for example, it will look like this:
```ruby
array = ['string']
@@ -1865,15 +1865,15 @@ The methods `to_date`, `to_time`, and `to_datetime` are basically convenience wr
```ruby
"2010-07-27".to_date # => Tue, 27 Jul 2010
-"2010-07-27 23:37:00".to_time # => Tue Jul 27 23:37:00 UTC 2010
+"2010-07-27 23:37:00".to_time # => 2010-07-27 23:37:00 +0200
"2010-07-27 23:37:00".to_datetime # => Tue, 27 Jul 2010 23:37:00 +0000
```
`to_time` receives an optional argument `:utc` or `:local`, to indicate which time zone you want the time in:
```ruby
-"2010-07-27 23:42:00".to_time(:utc) # => Tue Jul 27 23:42:00 UTC 2010
-"2010-07-27 23:42:00".to_time(:local) # => Tue Jul 27 23:42:00 +0200 2010
+"2010-07-27 23:42:00".to_time(:utc) # => 2010-07-27 23:42:00 UTC
+"2010-07-27 23:42:00".to_time(:local) # => 2010-07-27 23:42:00 +0200
```
Default is `:utc`.
diff --git a/guides/source/active_support_instrumentation.md b/guides/source/active_support_instrumentation.md
index 373dbbb9aa..e5a560edd0 100644
--- a/guides/source/active_support_instrumentation.md
+++ b/guides/source/active_support_instrumentation.md
@@ -244,14 +244,6 @@ INFO. The adapters will add their own data as well.
}
```
-### identity.active_record
-
-| Key | Value |
-| ---------------- | ----------------------------------------- |
-| `:line` | Primary Key of object in the identity map |
-| `:name` | Record's class |
-| `:connection_id` | `self.object_id` |
-
### instantiation.active_record
| Key | Value |
@@ -321,17 +313,6 @@ Action Mailer
}
```
-Active Resource
---------------
-
-### request.active_resource
-
-| Key | Value |
-| -------------- | -------------------- |
-| `:method` | HTTP method |
-| `:request_uri` | Complete URI |
-| `:result` | HTTP response object |
-
Active Support
--------------
@@ -414,6 +395,38 @@ INFO. Cache stores may add their own keys
}
```
+Active Job
+--------
+
+### enqueue_at.active_job
+
+| Key | Value |
+| ------------ | -------------------------------------- |
+| `:adapter` | QueueAdapter object processing the job |
+| `:job` | Job object |
+
+### enqueue.active_job
+
+| Key | Value |
+| ------------ | -------------------------------------- |
+| `:adapter` | QueueAdapter object processing the job |
+| `:job` | Job object |
+
+### perform_start.active_job
+
+| Key | Value |
+| ------------ | -------------------------------------- |
+| `:adapter` | QueueAdapter object processing the job |
+| `:job` | Job object |
+
+### perform.active_job
+
+| Key | Value |
+| ------------ | -------------------------------------- |
+| `:adapter` | QueueAdapter object processing the job |
+| `:job` | Job object |
+
+
Railties
--------
diff --git a/guides/source/api_app.md b/guides/source/api_app.md
index 0a6335ed88..feaaff166a 100644
--- a/guides/source/api_app.md
+++ b/guides/source/api_app.md
@@ -1,435 +1,404 @@
-Using Rails for API-only Apps
-=============================
+**DO NOT READ THIS FILE ON GITHUB, GUIDES ARE PUBLISHED ON http://guides.rubyonrails.org.**
+
+
+Using Rails for API-only Applications
+=====================================
In this guide you will learn:
-- What Rails provides for API-only applications
-- How to configure Rails to start without any browser features
-- How to decide which middlewares you will want to include
-- How to decide which modules to use in your controller
+* What Rails provides for API-only applications
+* How to configure Rails to start without any browser features
+* How to decide which middlewares you will want to include
+* How to decide which modules to use in your controller
-endprologue.
+--------------------------------------------------------------------------------
-### What is an API app?
+What is an API app?
+-------------------
-Traditionally, when people said that they used Rails as an “API”, they
-meant providing a programmatically accessible API alongside their web
-application.\
-For example, GitHub provides [an API](http://developer.github.com) that
-you can use from your own custom clients.
+Traditionally, when people said that they used Rails as an "API", they meant
+providing a programmatically accessible API alongside their web application.
+For example, GitHub provides [an API](http://developer.github.com) that you
+can use from your own custom clients.
-With the advent of client-side frameworks, more developers are using
-Rails to build a backend that is shared between their web application
-and other native applications.
+With the advent of client-side frameworks, more developers are using Rails to
+build a back-end that is shared between their web application and other native
+applications.
-For example, Twitter uses its [public API](https://dev.twitter.com) in
-its web application, which is built as a static site that consumes JSON
-resources.
+For example, Twitter uses its [public API](https://dev.twitter.com) in its web
+application, which is built as a static site that consumes JSON resources.
-Instead of using Rails to generate dynamic HTML that will communicate
-with the server through forms and links, many developers are treating
-their web application as just another client, delivered as static HTML,
-CSS and JavaScript, and consuming a simple JSON API
+Instead of using Rails to generate dynamic HTML that will communicate with the
+server through forms and links, many developers are treating their web application
+as just another client, delivered as static HTML, CSS and JavaScript consuming
+a simple JSON API.
-This guide covers building a Rails application that serves JSON
-resources to an API client **or** client-side framework.
+This guide covers building a Rails application that serves JSON resources to an
+API client **or** a client-side framework.
-### Why use Rails for JSON APIs?
+Why use Rails for JSON APIs?
+----------------------------
-The first question a lot of people have when thinking about building a
-JSON API using Rails is: “isn’t using Rails to spit out some JSON
-overkill? Shouldn’t I just use something like Sinatra?”
+The first question a lot of people have when thinking about building a JSON API
+using Rails is: "isn't using Rails to spit out some JSON overkill? Shouldn't I
+just use something like Sinatra?".
For very simple APIs, this may be true. However, even in very HTML-heavy
-applications, most of an application’s logic is actually outside of the
-view layer.
+applications, most of an application's logic is actually outside of the view
+layer.
-The reason most people use Rails is that it provides a set of defaults
-that allows us to get up and running quickly without having to make a
-lot of trivial decisions.
+The reason most people use Rails is that it provides a set of defaults that
+allows us to get up and running quickly without having to make a lot of trivial
+decisions.
-Let’s take a look at some of the things that Rails provides out of the
-box that are still applicable to API applications.
+Let's take a look at some of the things that Rails provides out of the box that are
+still applicable to API applications.
Handled at the middleware layer:
-- Reloading: Rails applications support transparent reloading. This
- works even if your application gets big and restarting the server
- for every request becomes non-viable.
-- Development Mode: Rails application come with smart defaults for
- development, making development pleasant without compromising
- production-time performance.
-- Test Mode: Ditto test mode.
-- Logging: Rails applications log every request, with a level of
- verbosity appropriate for the current mode. Rails logs in
- development include information about the request environment,
- database queries, and basic performance information.
-- Security: Rails detects and thwarts [IP spoofing
- attacks](http://en.wikipedia.org/wiki/IP_address_spoofing) and
- handles cryptographic signatures in a [timing
- attack](http://en.wikipedia.org/wiki/Timing_attack) aware way. Don’t
- know what an IP spoofing attack or a timing attack is? Exactly.
-- Parameter Parsing: Want to specify your parameters as JSON instead
- of as a URL-encoded String? No problem. Rails will decode the JSON
- for you and make it available in *params*. Want to use nested
- URL-encoded params? That works too.
-- Conditional GETs: Rails handles conditional *GET*, (*ETag* and
- *Last-Modified*), processing request headers and returning the
- correct response headers and status code. All you need to do is use
- the
- [stale?](http://api.rubyonrails.org/classes/ActionController/ConditionalGet.html#method-i-stale-3F)
- check in your controller, and Rails will handle all of the HTTP
- details for you.
-- Caching: If you use *dirty?* with public cache control, Rails will
- automatically cache your responses. You can easily configure the
- cache store.
-- HEAD requests: Rails will transparently convert *HEAD* requests into
- *GET* requests, and return just the headers on the way out. This
- makes *HEAD* work reliably in all Rails APIs.
-
-While you could obviously build these up in terms of existing Rack
-middlewares, I think this list demonstrates that the default Rails
-middleware stack provides a lot of value, even if you’re “just
-generating JSON”.
-
-Handled at the ActionPack layer:
-
-- Resourceful Routing: If you’re building a RESTful JSON API, you want
- to be using the Rails router. Clean and conventional mapping from
- HTTP to controllers means not having to spend time thinking about
- how to model your API in terms of HTTP.
-- URL Generation: The flip side of routing is URL generation. A good
- API based on HTTP includes URLs (see [the GitHub gist
- API](http://developer.github.com/v3/gists/) for an example).
-- Header and Redirection Responses: *head :no\_content* and
- *redirect\_to user\_url(current\_user)* come in handy. Sure, you
- could manually add the response headers, but why?
-- Caching: Rails provides page, action and fragment caching. Fragment
- caching is especially helpful when building up a nested JSON object.
-- Basic, Digest and Token Authentication: Rails comes with
- out-of-the-box support for three kinds of HTTP authentication.
-- Instrumentation: Rails 3.0 added an instrumentation API that will
- trigger registered handlers for a variety of events, such as action
- processing, sending a file or data, redirection, and database
- queries. The payload of each event comes with relevant information
- (for the action processing event, the payload includes the
- controller, action, params, request format, request method and the
- request’s full path).
-- Generators: This may be passé for advanced Rails users, but it can
- be nice to generate a resource and get your model, controller, test
- stubs, and routes created for you in a single command.
-- Plugins: Many third-party libraries come with support for Rails that
- reduces or eliminates the cost of setting up and gluing together the
- library and the web framework. This includes things like overriding
- default generators, adding rake tasks, and honoring Rails choices
- (like the logger and cache backend).
-
-Of course, the Rails boot process also glues together all registered
-components. For example, the Rails boot process is what uses your
-*config/database.yml* file when configuring ActiveRecord.
-
-**The short version is**: you may not have thought about which parts of
-Rails are still applicable even if you remove the view layer, but the
-answer turns out to be “most of it”.
-
-### The Basic Configuration
-
-If you’re building a Rails application that will be an API server first
-and foremost, you can start with a more limited subset of Rails and add
-in features as needed.
+- Reloading: Rails applications support transparent reloading. This works even if
+ your application gets big and restarting the server for every request becomes
+ non-viable.
+- Development Mode: Rails applications come with smart defaults for development,
+ making development pleasant without compromising production-time performance.
+- Test Mode: Ditto development mode.
+- Logging: Rails applications log every request, with a level of verbosity
+ appropriate for the current mode. Rails logs in development include information
+ about the request environment, database queries, and basic performance
+ information.
+- Security: Rails detects and thwarts [IP spoofing
+ attacks](http://en.wikipedia.org/wiki/IP_address_spoofing) and handles
+ cryptographic signatures in a [timing
+ attack](http://en.wikipedia.org/wiki/Timing_attack) aware way. Don't know what
+ an IP spoofing attack or a timing attack is? Exactly.
+- Parameter Parsing: Want to specify your parameters as JSON instead of as a
+ URL-encoded String? No problem. Rails will decode the JSON for you and make
+ it available in `params`. Want to use nested URL-encoded parameters? That
+ works too.
+- Conditional GETs: Rails handles conditional `GET`, (`ETag` and `Last-Modified`),
+ processing request headers and returning the correct response headers and status
+ code. All you need to do is use the
+ [`stale?`](http://api.rubyonrails.org/classes/ActionController/ConditionalGet.html#method-i-stale-3F)
+ check in your controller, and Rails will handle all of the HTTP details for you.
+- Caching: If you use `dirty?` with public cache control, Rails will automatically
+ cache your responses. You can easily configure the cache store.
+- HEAD requests: Rails will transparently convert `HEAD` requests into `GET` ones,
+ and return just the headers on the way out. This makes `HEAD` work reliably in
+ all Rails APIs.
+
+While you could obviously build these up in terms of existing Rack middlewares,
+this list demonstrates that the default Rails middleware stack provides a lot
+of value, even if you're "just generating JSON".
+
+Handled at the Action Pack layer:
+
+- Resourceful Routing: If you're building a RESTful JSON API, you want to be
+ using the Rails router. Clean and conventional mapping from HTTP to controllers
+ means not having to spend time thinking about how to model your API in terms
+ of HTTP.
+- URL Generation: The flip side of routing is URL generation. A good API based
+ on HTTP includes URLs (see [the GitHub gist API](http://developer.github.com/v3/gists/)
+ for an example).
+- Header and Redirection Responses: `head :no_content` and
+ `redirect_to user_url(current_user)` come in handy. Sure, you could manually
+ add the response headers, but why?
+- Caching: Rails provides page, action and fragment caching. Fragment caching
+ is especially helpful when building up a nested JSON object.
+- Basic, Digest and Token Authentication: Rails comes with out-of-the-box support
+ for three kinds of HTTP authentication.
+- Instrumentation: Rails has an instrumentation API that will trigger registered
+ handlers for a variety of events, such as action processing, sending a file or
+ data, redirection, and database queries. The payload of each event comes with
+ relevant information (for the action processing event, the payload includes
+ the controller, action, parameters, request format, request method and the
+ request's full path).
+- Generators: This may be passé for advanced Rails users, but it can be nice to
+ generate a resource and get your model, controller, test stubs, and routes
+ created for you in a single command.
+- Plugins: Many third-party libraries come with support for Rails that reduce
+ or eliminate the cost of setting up and gluing together the library and the
+ web framework. This includes things like overriding default generators, adding
+ rake tasks, and honoring Rails choices (like the logger and cache back-end).
+
+Of course, the Rails boot process also glues together all registered components.
+For example, the Rails boot process is what uses your `config/database.yml` file
+when configuring Active Record.
+
+**The short version is**: you may not have thought about which parts of Rails
+are still applicable even if you remove the view layer, but the answer turns out
+to be "most of it".
+
+The Basic Configuration
+-----------------------
+
+If you're building a Rails application that will be an API server first and
+foremost, you can start with a more limited subset of Rails and add in features
+as needed.
You can generate a new api Rails app:
-<shell>\
-\$ rails new my\_api --api\
-</shell>
+```bash
+$ rails new my_api --api
+```
This will do three main things for you:
-- Configure your application to start with a more limited set of
- middleware than normal. Specifically, it will not include any
- middleware primarily useful for browser applications (like cookie
- support) by default.
-- Make *ApplicationController* inherit from *ActionController::API*
- instead of *ActionController::Base*. As with middleware, this will
- leave out any *ActionController* modules that provide functionality
- primarily used by browser applications.
-- Configure the generators to skip generating views, helpers and
- assets when you generate a new resource.
-
-If you want to take an existing app and make it an API app, follow the
+- Configure your application to start with a more limited set of middlewares
+ than normal. Specifically, it will not include any middleware primarily useful
+ for browser applications (like cookies support) by default.
+- Make `ApplicationController` inherit from `ActionController::API` instead of
+ `ActionController::Base`. As with middlewares, this will leave out any Action
+ Controller modules that provide functionalities primarily used by browser
+ applications.
+- Configure the generators to skip generating views, helpers and assets when
+ you generate a new resource.
+
+If you want to take an existing application and make it an API one, read the
following steps.
-In *config/application.rb* add the following line at the top of the
-*Application* class:
-
-<ruby>\
-config.api\_only!\
-</ruby>
-
-Change *app/controllers/application\_controller.rb*:
-
-<ruby>
-
-1. instead of\
- class ApplicationController \< ActionController::Base\
- end
-
-<!-- -->
-
-1. do\
- class ApplicationController \< ActionController::API\
- end\
- </ruby>
-
-### Choosing Middlewares
-
-An API application comes with the following middlewares by default.
-
-- *Rack::Cache*: Caches responses with public *Cache-Control* headers
- using HTTP caching semantics. See below for more information.
-- *Rack::Sendfile*: Uses a front-end server’s file serving support
- from your Rails application.
-- *Rack::Lock*: If your application is not marked as threadsafe
- (*config.threadsafe!*), this middleware will add a mutex around your
- requests.
-- *ActionDispatch::RequestId*:
-- *Rails::Rack::Logger*:
-- *Rack::Runtime*: Adds a header to the response listing the total
- runtime of the request.
-- *ActionDispatch::ShowExceptions*: Rescue exceptions and re-dispatch
- them to an exception handling application
-- *ActionDispatch::DebugExceptions*: Log exceptions
-- *ActionDispatch::RemoteIp*: Protect against IP spoofing attacks
-- *ActionDispatch::Reloader*: In development mode, support code
- reloading.
-- *ActionDispatch::ParamsParser*: Parse XML, YAML and JSON parameters
- when the request’s *Content-Type* is one of those.
-- *ActionDispatch::Head*: Dispatch *HEAD* requests as *GET* requests,
- and return only the status code and headers.
-- *Rack::ConditionalGet*: Supports the *stale?* feature in Rails
- controllers.
-- *Rack::ETag*: Automatically set an *ETag* on all string responses.
- This means that if the same response is returned from a controller
- for the same URL, the server will return a *304 Not Modified*, even
- if no additional caching steps are taken. This is primarily a
- client-side optimization; it reduces bandwidth costs but not server
- processing time.
-
-Other plugins, including *ActiveRecord*, may add additional middlewares.
-In general, these middlewares are agnostic to the type of app you are
+In `config/application.rb` add the following line at the top of the `Application`
+class definition:
+
+```ruby
+config.api_only = true
+```
+
+Finally, inside `app/controllers/application_controller.rb`, instead of:
+
+```ruby
+class ApplicationController < ActionController::Base
+end
+```
+
+do:
+
+```ruby
+class ApplicationController < ActionController::API
+end
+```
+
+Choosing Middlewares
+--------------------
+
+An API application comes with the following middlewares by default:
+
+- `Rack::Sendfile`
+- `ActionDispatch::Static`
+- `Rack::Lock`
+- `ActiveSupport::Cache::Strategy::LocalCache::Middleware`
+- `ActionDispatch::RequestId`
+- `Rails::Rack::Logger`
+- `Rack::Runtime`
+- `ActionDispatch::ShowExceptions`
+- `ActionDispatch::DebugExceptions`
+- `ActionDispatch::RemoteIp`
+- `ActionDispatch::Reloader`
+- `ActionDispatch::Callbacks`
+- `Rack::Head`
+- `Rack::ConditionalGet`
+- `Rack::ETag`
+
+See the [internal middlewares](rails_on_rack.html#internal-middleware-stack)
+section of the Rack guide for further information on them.
+
+Other plugins, including Active Record, may add additional middlewares. In
+general, these middlewares are agnostic to the type of application you are
building, and make sense in an API-only Rails application.
You can get a list of all middlewares in your application via:
-<shell>\
-\$ rake middleware\
-</shell>
+```bash
+$ rake middleware
+```
-#### Using Rack::Cache
+### Using the Cache Middleware
-When used with Rails, *Rack::Cache* uses the Rails cache store for its
-entity and meta stores. This means that if you use memcache, for your
-Rails app, for instance, the built-in HTTP cache will use memcache.
+By default, Rails will add a middleware that provides a cache store based on
+the configuration of your application (memcache by default). This means that
+the built-in HTTP cache will rely on it.
-To make use of *Rack::Cache*, you will want to use *stale?* in your
-controller. Here’s an example of *stale?* in use.
+For instance, using the `stale?` method:
-<ruby>\
-def show\
+```ruby
+def show
@post = Post.find(params[:id])
-if stale?(:last\_modified =\> `post.updated_at)
- render json: `post\
- end\
-end\
-</ruby>
+ if stale?(last_modified: @post.updated_at)
+ render json: @post
+ end
+end
+```
-The call to *stale?* will compare the *If-Modified-Since* header in the
-request with *@post.updated\_at*. If the header is newer than the last
-modified, this action will return a *304 Not Modified* response.
-Otherwise, it will render the response and include a *Last-Modified*
-header with the response.
+The call to `stale?` will compare the `If-Modified-Since` header in the request
+with `@post.updated_at`. If the header is newer than the last modified, this
+action will return a "304 Not Modified" response. Otherwise, it will render the
+response and include a `Last-Modified` header in it.
-Normally, this mechanism is used on a per-client basis. *Rack::Cache*
+Normally, this mechanism is used on a per-client basis. The cache middleware
allows us to share this caching mechanism across clients. We can enable
-cross-client caching in the call to *stale?*
+cross-client caching in the call to `stale?`:
-<ruby>\
-def show\
+```ruby
+def show
@post = Post.find(params[:id])
-if stale?(:last\_modified =\> `post.updated_at, :public => true)
- render json: `post\
- end\
-end\
-</ruby>
+ if stale?(last_modified: @post.updated_at, public: true)
+ render json: @post
+ end
+end
+```
-This means that *Rack::Cache* will store off *Last-Modified* value for a
-URL in the Rails cache, and add an *If-Modified-Since* header to any
+This means that the cache middleware will store off the `Last-Modified` value
+for a URL in the Rails cache, and add an `If-Modified-Since` header to any
subsequent inbound requests for the same URL.
Think of it as page caching using HTTP semantics.
-NOTE: The *Rack::Cache* middleware is always outside of the *Rack::Lock*
-mutex, even in single-threaded apps.
+NOTE: This middleware is always outside of the `Rack::Lock` mutex, even in
+single-threaded applications.
-#### Using Rack::Sendfile
+### Using Rack::Sendfile
-When you use the *send\_file* method in a Rails controller, it sets the
-*X-Sendfile* header. *Rack::Sendfile* is responsible for actually
-sending the file.
+When you use the `send_file` method inside a Rails controller, it sets the
+`X-Sendfile` header. `Rack::Sendfile` is responsible for actually sending the
+file.
-If your front-end server supports accelerated file sending,
-*Rack::Sendfile* will offload the actual file sending work to the
-front-end server.
+If your front-end server supports accelerated file sending, `Rack::Sendfile`
+will offload the actual file sending work to the front-end server.
-You can configure the name of the header that your front-end server uses
-for this purposes using *config.action\_dispatch.x\_sendfile\_header* in
-the appropriate environment config file.
+You can configure the name of the header that your front-end server uses for
+this purpose using `config.action_dispatch.x_sendfile_header` in the appropriate
+environment's configuration file.
-You can learn more about how to use *Rack::Sendfile* with popular
+You can learn more about how to use `Rack::Sendfile` with popular
front-ends in [the Rack::Sendfile
-documentation](http://rubydoc.info/github/rack/rack/master/Rack/Sendfile)
+documentation](http://rubydoc.info/github/rack/rack/master/Rack/Sendfile).
-The values for popular servers once they are configured to support
+Here are some values for popular servers, once they are configured, to support
accelerated file sending:
-<ruby>
+```ruby
+# Apache and lighttpd
+config.action_dispatch.x_sendfile_header = "X-Sendfile"
+
+# Nginx
+config.action_dispatch.x_sendfile_header = "X-Accel-Redirect"
+```
+
+Make sure to configure your server to support these options following the
+instructions in the `Rack::Sendfile` documentation.
+
+NOTE: The `Rack::Sendfile` middleware is always outside of the `Rack::Lock`
+mutex, even in single-threaded applications.
+
+### Using ActionDispatch::Request
+
+`ActionDispatch::Request#params` will take parameters from the client in the JSON
+format and make them available in your controller inside `params`.
+
+To use this, your client will need to make a request with JSON-encoded parameters
+and specify the `Content-Type` as `application/json`.
+
+Here's an example in jQuery:
-1. Apache and lighttpd\
- config.action\_dispatch.x\_sendfile\_header = “X-Sendfile”
-
-<!-- -->
-
-1. nginx\
- config.action\_dispatch.x\_sendfile\_header = “X-Accel-Redirect”\
- </ruby>
-
-Make sure to configure your server to support these options following
-the instructions in the *Rack::Sendfile* documentation.
-
-NOTE: The *Rack::Sendfile* middleware is always outside of the
-*Rack::Lock* mutex, even in single-threaded apps.
-
-#### Using ActionDispatch::ParamsParser
-
-*ActionDispatch::ParamsParser* will take parameters from the client in
-JSON and make them available in your controller as *params*.
+```javascript
+jQuery.ajax({
+ type: 'POST',
+ url: '/people',
+ dataType: 'json',
+ contentType: 'application/json',
+ data: JSON.stringify({ person: { firstName: "Yehuda", lastName: "Katz" } }),
+ success: function(json) { }
+});
+```
-To use this, your client will need to make a request with JSON-encoded
-parameters and specify the *Content-Type* as *application/json*.
+`ActionDispatch::Request` will see the `Content-Type` and your parameters
+will be:
-Here’s an example in jQuery:
+```ruby
+{ :person => { :firstName => "Yehuda", :lastName => "Katz" } }
+```
-<plain>\
-jQuery.ajax({\
- type: ‘POST’,\
- url: ‘/people’\
- dataType: ‘json’,\
- contentType: ‘application/json’,\
- data: JSON.stringify({ person: { firstName: “Yehuda”, lastName: “Katz”
-} }),
+### Other Middlewares
-success: function(json) { }\
-});\
-</plain>
+Rails ships with a number of other middlewares that you might want to use in an
+API application, especially if one of your API clients is the browser:
-*ActionDispatch::ParamsParser* will see the *Content-Type* and your
-params will be *{ :person =\> { :firstName =\> “Yehuda”, :lastName =\>
-“Katz” } }*.
+- `Rack::MethodOverride`
+- `ActionDispatch::Cookies`
+- `ActionDispatch::Flash`
+- For sessions management
+ * `ActionDispatch::Session::CacheStore`
+ * `ActionDispatch::Session::CookieStore`
+ * `ActionDispatch::Session::MemCacheStore`
-#### Other Middlewares
+Any of these middlewares can be added via:
-Rails ships with a number of other middlewares that you might want to
-use in an API app, especially if one of your API clients is the browser:
+```ruby
+config.middleware.use Rack::MethodOverride
+```
-- *Rack::MethodOverride*: Allows the use of the *\_method* hack to
- route POST requests to other verbs.
-- *ActionDispatch::Cookies*: Supports the *cookie* method in
- *ActionController*, including support for signed and encrypted
- cookies.
-- *ActionDispatch::Flash*: Supports the *flash* mechanism in
- *ActionController*.
-- *ActionDispatch::BestStandards*: Tells Internet Explorer to use the
- most standards-compliant available renderer. In production mode, if
- ChromeFrame is available, use ChromeFrame.
-- Session Management: If a *config.session\_store* is supplied, this
- middleware makes the session available as the *session* method in
- *ActionController*.
+### Removing Middlewares
-Any of these middlewares can be adding via:
+If you don't want to use a middleware that is included by default in the API-only
+middleware set, you can remove it with:
-<ruby>\
-config.middleware.use Rack::MethodOverride\
-</ruby>
+```ruby
+config.middleware.delete ::Rack::Sendfile
+```
-#### Removing Middlewares
+Keep in mind that removing these middlewares will remove support for certain
+features in Action Controller.
-If you don’t want to use a middleware that is included by default in the
-API-only middleware set, you can remove it using
-*config.middleware.delete*:
+Choosing Controller Modules
+---------------------------
-<ruby>\
-config.middleware.delete ::Rack::Sendfile\
-</ruby>
+An API application (using `ActionController::API`) comes with the following
+controller modules by default:
-Keep in mind that removing these features may remove support for certain
-features in *ActionController*.
+- `ActionController::UrlFor`: Makes `url_for` and friends available.
+- `ActionController::Redirecting`: Support for `redirect_to`.
+- `ActionController::Rendering`: Basic support for rendering.
+- `ActionController::Renderers::All`: Support for `render :json` and friends.
+- `ActionController::ConditionalGet`: Support for `stale?`.
+- `ActionController::ForceSSL`: Support for `force_ssl`.
+- `ActionController::DataStreaming`: Support for `send_file` and `send_data`.
+- `AbstractController::Callbacks`: Support for `before_action` and friends.
+- `ActionController::Instrumentation`: Support for the instrumentation
+ hooks defined by Action Controller (see [the instrumentation
+ guide](active_support_instrumentation.html#action-controller)).
+- `ActionController::Rescue`: Support for `rescue_from`.
+- `ActionController::BasicImplicitRender`: Makes sure to return an empty response
+ if there's not an explicit one.
+- `ActionController::StrongParameters`: Support for parameters white-listing in
+ combination with Active Model mass assignment.
+- `ActionController::ParamsWrapper`: Wraps the parameters hash into a nested hash
+ so you don't have to specify root elements sending POST requests for instance.
-### Choosing Controller Modules
+Other plugins may add additional modules. You can get a list of all modules
+included into `ActionController::API` in the rails console:
+
+```bash
+$ bin/rails c
+>> ActionController::API.ancestors - ActionController::Metal.ancestors
+```
-An API application (using *ActionController::API*) comes with the
-following controller modules by default:
+### Adding Other Modules
-- *ActionController::UrlFor*: Makes *url\_for* and friends available
-- *ActionController::Redirecting*: Support for *redirect\_to*
-- *ActionController::Rendering*: Basic support for rendering
-- *ActionController::Renderers::All*: Support for *render :json* and
- friends
-- *ActionController::ConditionalGet*: Support for *stale?*
-- *ActionController::ForceSSL*: Support for *force\_ssl*
-- *ActionController::RackDelegation*: Support for the *request* and
- *response* methods returning *ActionDispatch::Request* and
- *ActionDispatch::Response* objects.
-- *ActionController::DataStreaming*: Support for *send\_file* and
- *send\_data*
-- *AbstractController::Callbacks*: Support for *before\_filter* and
- friends
-- *ActionController::Instrumentation*: Support for the instrumentation
- hooks defined by *ActionController* (see [the
- source](https://github.com/rails/rails/blob/master/actionpack/lib/action_controller/metal/instrumentation.rb)
- for more).
-- *ActionController::Rescue*: Support for *rescue\_from*.
-
-Other plugins may add additional modules. You can get a list of all
-modules included into *ActionController::API* in the rails console:
-
-<shell>\
-\$ irb\
-\>\> ActionController::API.ancestors -
-ActionController::Metal.ancestors\
-</shell>
-
-#### Adding Other Modules
-
-All ActionController modules know about their dependent modules, so you
-can feel free to include any modules into your controllers, and all
-dependencies will be included and set up as well.
+All Action Controller modules know about their dependent modules, so you can feel
+free to include any modules into your controllers, and all dependencies will be
+included and set up as well.
Some common modules you might want to add:
-- *AbstractController::Translation*: Support for the *l* and *t*
- localization and translation methods. These delegate to
- *I18n.translate* and *I18n.localize*.
-- *ActionController::HTTPAuthentication::Basic* (or *Digest*
- or +Token): Support for basic, digest or token HTTP authentication.
-- *AbstractController::Layouts*: Support for layouts when rendering.
-- *ActionController::MimeResponds*: Support for content negotiation
- (*respond\_to*, *respond\_with*).
-- *ActionController::Cookies*: Support for *cookies*, which includes
- support for signed and encrypted cookies. This requires the cookie
- middleware.
-
-The best place to add a module is in your *ApplicationController*. You
-can also add modules to individual controllers.
+- `AbstractController::Translation`: Support for the `l` and `t` localization
+ and translation methods.
+- `ActionController::HttpAuthentication::Basic` (or `Digest` or `Token`): Support
+ for basic, digest or token HTTP authentication.
+- `AbstractController::Layouts`: Support for layouts when rendering.
+- `ActionController::MimeResponds`: Support for `respond_to`.
+- `ActionController::Cookies`: Support for `cookies`, which includes
+ support for signed and encrypted cookies. This requires the cookies middleware.
+
+The best place to add a module is in your `ApplicationController` but you can
+also add modules to individual controllers.
diff --git a/guides/source/api_documentation_guidelines.md b/guides/source/api_documentation_guidelines.md
index 46c9013087..526bf768cc 100644
--- a/guides/source/api_documentation_guidelines.md
+++ b/guides/source/api_documentation_guidelines.md
@@ -84,6 +84,11 @@ English
Please use American English (*color*, *center*, *modularize*, etc). See [a list of American and British English spelling differences here](http://en.wikipedia.org/wiki/American_and_British_English_spelling_differences).
+Comma
+-------
+
+Please use the Oxford comma (*red, white, and blue* style). See [the detail of Oxford comma](http://en.wikipedia.org/wiki/Serial_comma).
+
Example Code
------------
@@ -234,7 +239,7 @@ You can quickly test the RDoc output with the following command:
```
$ echo "+:to_param+" | rdoc --pipe
-#=> <p><code>:to_param</code></p>
+# => <p><code>:to_param</code></p>
```
### Regular Font
diff --git a/guides/source/asset_pipeline.md b/guides/source/asset_pipeline.md
index 4a610e8458..7b8d2d3aef 100644
--- a/guides/source/asset_pipeline.md
+++ b/guides/source/asset_pipeline.md
@@ -403,13 +403,13 @@ When using the asset pipeline, paths to assets must be re-written and
underscored in Ruby) for the following asset classes: image, font, video, audio,
JavaScript and stylesheet.
-* `image-url("rails.png")` becomes `url(/assets/rails.png)`
-* `image-path("rails.png")` becomes `"/assets/rails.png"`.
+* `image-url("rails.png")` returns `url(/assets/rails.png)`
+* `image-path("rails.png")` returns `"/assets/rails.png"`
The more generic form can also be used:
-* `asset-url("rails.png")` becomes `url(/assets/rails.png)`
-* `asset-path("rails.png")` becomes `"/assets/rails.png"`
+* `asset-url("rails.png")` returns `url(/assets/rails.png)`
+* `asset-path("rails.png")` returns `"/assets/rails.png"`
#### JavaScript/CoffeeScript and ERB
diff --git a/guides/source/association_basics.md b/guides/source/association_basics.md
index 05dd0d2a04..999c533fb3 100644
--- a/guides/source/association_basics.md
+++ b/guides/source/association_basics.md
@@ -622,6 +622,19 @@ end
We pass `id: false` to `create_table` because that table does not represent a model. That's required for the association to work properly. If you observe any strange behavior in a `has_and_belongs_to_many` association like mangled model IDs, or exceptions about conflicting IDs, chances are you forgot that bit.
+You can also use the method `create_join_table`
+
+```ruby
+class CreateAssembliesPartsJoinTable < ActiveRecord::Migration
+ def change
+ create_join_table :assemblies, :parts do |t|
+ t.index :assembly_id
+ t.index :part_id
+ end
+ end
+end
+```
+
### Controlling Association Scope
By default, associations look for objects only within the current module's scope. This can be important when you declare Active Record models within a module. For example:
@@ -755,7 +768,7 @@ The `belongs_to` association creates a one-to-one match with another model. In d
When you declare a `belongs_to` association, the declaring class automatically gains five methods related to the association:
-* `association(force_reload = false)`
+* `association`
* `association=(associate)`
* `build_association(attributes = {})`
* `create_association(attributes = {})`
@@ -781,7 +794,7 @@ create_customer!
NOTE: When initializing a new `has_one` or `belongs_to` association you must use the `build_` prefix to build the association, rather than the `association.build` method that would be used for `has_many` or `has_and_belongs_to_many` associations. To create one, use the `create_` prefix.
-##### `association(force_reload = false)`
+##### `association`
The `association` method returns the associated object, if any. If no associated object is found, it returns `nil`.
@@ -789,7 +802,11 @@ The `association` method returns the associated object, if any. If no associated
@customer = @order.customer
```
-If the associated object has already been retrieved from the database for this object, the cached version will be returned. To override this behavior (and force a database read), pass `true` as the `force_reload` argument.
+If the associated object has already been retrieved from the database for this object, the cached version will be returned. To override this behavior (and force a database read), call `#reload` on the parent object.
+
+```ruby
+@customer = @order.reload.customer
+```
##### `association=(associate)`
@@ -915,8 +932,11 @@ If you set the `:dependent` option to:
* `:destroy`, when the object is destroyed, `destroy` will be called on its
associated objects.
-* `:delete`, when the object is destroyed, all its associated objects will be
+* `:delete_all`, when the object is destroyed, all its associated objects will be
deleted directly from the database without calling their `destroy` method.
+* `:nullify`, causes the foreign key to be set to `NULL`. Callbacks are not executed.
+* `:restrict_with_exception`, causes an exception to be raised if there is an associated record
+* `:restrict_with_error`, causes an error to be added to the owner if there is an associated object
WARNING: You should not specify this option on a `belongs_to` association that is connected with a `has_many` association on the other class. Doing so can lead to orphaned records in your database.
@@ -1100,7 +1120,7 @@ The `has_one` association creates a one-to-one match with another model. In data
When you declare a `has_one` association, the declaring class automatically gains five methods related to the association:
-* `association(force_reload = false)`
+* `association`
* `association=(associate)`
* `build_association(attributes = {})`
* `create_association(attributes = {})`
@@ -1126,7 +1146,7 @@ create_account!
NOTE: When initializing a new `has_one` or `belongs_to` association you must use the `build_` prefix to build the association, rather than the `association.build` method that would be used for `has_many` or `has_and_belongs_to_many` associations. To create one, use the `create_` prefix.
-##### `association(force_reload = false)`
+##### `association`
The `association` method returns the associated object, if any. If no associated object is found, it returns `nil`.
@@ -1134,7 +1154,11 @@ The `association` method returns the associated object, if any. If no associated
@account = @supplier.account
```
-If the associated object has already been retrieved from the database for this object, the cached version will be returned. To override this behavior (and force a database read), pass `true` as the `force_reload` argument.
+If the associated object has already been retrieved from the database for this object, the cached version will be returned. To override this behavior (and force a database read), call `#reload` on the parent object.
+
+```ruby
+@account = @supplier.reload.account
+```
##### `association=(associate)`
@@ -1367,7 +1391,7 @@ The `has_many` association creates a one-to-many relationship with another model
When you declare a `has_many` association, the declaring class automatically gains 16 methods related to the association:
-* `collection(force_reload = false)`
+* `collection`
* `collection<<(object, ...)`
* `collection.delete(object, ...)`
* `collection.destroy(object, ...)`
@@ -1395,7 +1419,7 @@ end
Each instance of the `Customer` model will have these methods:
```ruby
-orders(force_reload = false)
+orders
orders<<(object, ...)
orders.delete(object, ...)
orders.destroy(object, ...)
@@ -1413,7 +1437,7 @@ orders.create(attributes = {})
orders.create!(attributes = {})
```
-##### `collection(force_reload = false)`
+##### `collection`
The `collection` method returns an array of all of the associated objects. If there are no associated objects, it returns an empty array.
@@ -1519,20 +1543,30 @@ conditions exists in the collection. It uses the same syntax and options as
##### `collection.build(attributes = {}, ...)`
-The `collection.build` method returns one or more new objects of the associated type. These objects will be instantiated from the passed attributes, and the link through their foreign key will be created, but the associated objects will _not_ yet be saved.
+The `collection.build` method returns a single or array of new objects of the associated type. The object(s) will be instantiated from the passed attributes, and the link through their foreign key will be created, but the associated objects will _not_ yet be saved.
```ruby
@order = @customer.orders.build(order_date: Time.now,
order_number: "A12345")
+
+@orders = @customer.orders.build([
+ { order_date: Time.now, order_number: "A12346" },
+ { order_date: Time.now, order_number: "A12347" }
+])
```
##### `collection.create(attributes = {})`
-The `collection.create` method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through its foreign key will be created, and, once it passes all of the validations specified on the associated model, the associated object _will_ be saved.
+The `collection.create` method returns a single or array of new objects of the associated type. The object(s) will be instantiated from the passed attributes, the link through its foreign key will be created, and, once it passes all of the validations specified on the associated model, the associated object _will_ be saved.
```ruby
@order = @customer.orders.create(order_date: Time.now,
order_number: "A12345")
+
+@orders = @customer.orders.create([
+ { order_date: Time.now, order_number: "A12346" },
+ { order_date: Time.now, order_number: "A12347" }
+])
```
##### `collection.create!(attributes = {})`
@@ -1869,7 +1903,7 @@ The `has_and_belongs_to_many` association creates a many-to-many relationship wi
When you declare a `has_and_belongs_to_many` association, the declaring class automatically gains 16 methods related to the association:
-* `collection(force_reload = false)`
+* `collection`
* `collection<<(object, ...)`
* `collection.delete(object, ...)`
* `collection.destroy(object, ...)`
@@ -1897,7 +1931,7 @@ end
Each instance of the `Part` model will have these methods:
```ruby
-assemblies(force_reload = false)
+assemblies
assemblies<<(object, ...)
assemblies.delete(object, ...)
assemblies.destroy(object, ...)
@@ -1922,7 +1956,7 @@ If the join table for a `has_and_belongs_to_many` association has additional col
WARNING: The use of extra attributes on the join table in a `has_and_belongs_to_many` association is deprecated. If you require this sort of complex behavior on the table that joins two models in a many-to-many relationship, you should use a `has_many :through` association instead of `has_and_belongs_to_many`.
-##### `collection(force_reload = false)`
+##### `collection`
The `collection` method returns an array of all of the associated objects. If there are no associated objects, it returns an empty array.
@@ -2344,13 +2378,13 @@ associations, public methods, etc.
Creating a car will save it in the `vehicles` table with "Car" as the `type` field:
```ruby
-Car.create color: 'Red', price: 10000
+Car.create(color: 'Red', price: 10000)
```
will generate the following SQL:
```sql
-INSERT INTO "vehicles" ("type", "color", "price") VALUES ("Car", "Red", 10000)
+INSERT INTO "vehicles" ("type", "color", "price") VALUES ('Car', 'Red', 10000)
```
Querying car records will just search for vehicles that are cars:
diff --git a/guides/source/caching_with_rails.md b/guides/source/caching_with_rails.md
index 782406659d..9a56233e4a 100644
--- a/guides/source/caching_with_rails.md
+++ b/guides/source/caching_with_rails.md
@@ -1,14 +1,26 @@
**DO NOT READ THIS FILE ON GITHUB, GUIDES ARE PUBLISHED ON http://guides.rubyonrails.org.**
-Caching with Rails: An overview
+Caching with Rails: An Overview
===============================
-This guide will teach you what you need to know about avoiding that expensive round-trip to your database and returning what you need to return to the web clients in the shortest time possible.
+This guide is an introduction to speeding up your Rails application with caching.
+
+Caching means to store content generated during the request-response cycle and
+to reuse it when responding to similar requests.
+
+Caching is often the most effective way to boost an application's performance.
+Through caching, web sites running on a single server with a single database
+can sustain a load of thousands of concurrent users.
+
+Rails provides a set of caching features out of the box. This guide will teach
+you the scope and purpose of each one of them. Master these techniques and your
+Rails applications can serve millions of views without exorbitant response times
+or server bills.
After reading this guide, you will know:
-* Page and action caching (moved to separate gems as of Rails 4).
-* Fragment caching.
+* Fragment and Russian doll caching.
+* How to manage the caching dependencies.
* Alternative cache stores.
* Conditional GET support.
@@ -18,19 +30,32 @@ Basic Caching
-------------
This is an introduction to three types of caching techniques: page, action and
-fragment caching. Rails provides by default fragment caching. In order to use
-page and action caching, you will need to add `actionpack-page_caching` and
+fragment caching. By default Rails provides fragment caching. In order to use
+page and action caching you will need to add `actionpack-page_caching` and
`actionpack-action_caching` to your Gemfile.
-To start playing with caching you'll want to ensure that `config.action_controller.perform_caching` is set to `true` if you're running in development mode. This flag is normally set in the corresponding `config/environments/*.rb` and caching is disabled by default for development and test, and enabled for production.
+By default, caching is only enabled in your production environment. To play
+around with caching locally you'll want to enable caching in your local
+environment by setting `config.action_controller.perform_caching` to `true` in
+the relevant `config/environments/*.rb` file:
```ruby
config.action_controller.perform_caching = true
```
+NOTE: Changing the value of `config.action_controller.perform_caching` will
+only have an effect on the caching provided by the Action Controller component.
+For instance, it will not impact low-level caching, that we address
+[below](#low-level-caching).
+
### Page Caching
-Page caching is a Rails mechanism which allows the request for a generated page to be fulfilled by the webserver (i.e. Apache or NGINX), without ever having to go through the Rails stack at all. Obviously, this is super-fast. Unfortunately, it can't be applied to every situation (such as pages that need authentication) and since the webserver is literally just serving a file from the filesystem, cache expiration is an issue that needs to be dealt with.
+Page caching is a Rails mechanism which allows the request for a generated page
+to be fulfilled by the webserver (i.e. Apache or NGINX) without having to go
+through the entire Rails stack. While this is super fast it can't be applied to
+every situation (such as pages that need authentication). Also, because the
+webserver is serving a file directly from the filesystem you will need to
+implement cache expiration.
INFO: Page Caching has been removed from Rails 4. See the [actionpack-page_caching gem](https://github.com/rails/actionpack-page_caching).
@@ -42,105 +67,213 @@ INFO: Action Caching has been removed from Rails 4. See the [actionpack-action_c
### Fragment Caching
-Life would be perfect if we could get away with caching the entire contents of a page or action and serving it out to the world. Unfortunately, dynamic web applications usually build pages with a variety of components not all of which have the same caching characteristics. In order to address such a dynamically created page where different parts of the page need to be cached and expired differently, Rails provides a mechanism called Fragment Caching.
+Dynamic web applications usually build pages with a variety of components not
+all of which have the same caching characteristics. When different parts of the
+page need to be cached and expired separately you can use Fragment Caching.
Fragment Caching allows a fragment of view logic to be wrapped in a cache block and served out of the cache store when the next request comes in.
-As an example, if you wanted to show all the orders placed on your website in real time and didn't want to cache that part of the page, but did want to cache the part of the page which lists all products available, you could use this piece of code:
+For example, if you wanted to cache each product on a page, you could use this
+code:
```html+erb
-<% Order.find_recent.each do |o| %>
- <%= o.buyer.name %> bought <%= o.product.name %>
-<% end %>
-
-<% cache do %>
- All available products:
- <% Product.all.each do |p| %>
- <%= link_to p.name, product_url(p) %>
+<% @products.each do |product| %>
+ <% cache product do %>
+ <%= render product %>
<% end %>
<% end %>
```
-The cache block in our example will bind to the action that called it and is written out to the same place as the Action Cache, which means that if you want to cache multiple fragments per action, you should provide an `action_suffix` to the cache call:
+When your application receives its first request to this page, Rails will write
+a new cache entry with a unique key. A key looks something like this:
-```html+erb
-<% cache(action: 'recent', action_suffix: 'all_products') do %>
- All available products:
+```
+views/products/1-201505056193031061005000/bea67108094918eeba42cd4a6e786901
```
-and you can expire it using the `expire_fragment` method, like so:
+The number in the middle is the `product_id` followed by the timestamp value in
+the `updated_at` attribute of the product record. Rails uses the timestamp value
+to make sure it is not serving stale data. If the value of `updated_at` has
+changed, a new key will be generated. Then Rails will write a new cache to that
+key, and the old cache written to the old key will never be used again. This is
+called key-based expiration.
-```ruby
-expire_fragment(controller: 'products', action: 'recent', action_suffix: 'all_products')
-```
+Cache fragments will also be expired when the view fragment changes (e.g., the
+HTML in the view changes). The string of characters at the end of the key is a
+template tree digest. It is an md5 hash computed based on the contents of the
+view fragment you are caching. If you change the view fragment, the md5 hash
+will change, expiring the existing file.
-If you don't want the cache block to bind to the action that called it, you can also use globally keyed fragments by calling the `cache` method with a key:
+TIP: Cache stores like Memcached will automatically delete old cache files.
+
+If you want to cache a fragment under certain conditions, you can use
+`cache_if` or `cache_unless`:
```erb
-<% cache('all_available_products') do %>
- All available products:
+<% cache_if admin?, product do %>
+ <%= render product %>
<% end %>
```
-This fragment is then available to all actions in the `ProductsController` using the key and can be expired the same way:
+#### Collection caching
-```ruby
-expire_fragment('all_available_products')
-```
-If you want to avoid expiring the fragment manually, whenever an action updates a product, you can define a helper method:
+The `render` helper can also cache individual templates rendered for a collection.
+It can even one up the previous example with `each` by reading all cache
+templates at once instead of one by one. This is done automatically if the template
+rendered by the collection includes a `cache` call. Take a collection that renders
+a `products/_product.html.erb` partial for each element:
```ruby
-module ProductsHelper
- def cache_key_for_products
- count = Product.count
- max_updated_at = Product.maximum(:updated_at).try(:utc).try(:to_s, :number)
- "products/all-#{count}-#{max_updated_at}"
- end
-end
+render products
```
-This method generates a cache key that depends on all products and can be used in the view:
+If `products/_product.html.erb` starts with a `cache` call like so:
-```erb
-<% cache(cache_key_for_products) do %>
- All available products:
+```html+erb
+<% cache product do %>
+ <%= product.name %>
<% end %>
```
-If you want to cache a fragment under certain conditions, you can use `cache_if` or `cache_unless`
+All the cached templates from previous renders will be fetched at once with much
+greater speed. There's more info on how to make your templates [eligible for
+collection caching](http://api.rubyonrails.org/classes/ActionView/Template/Handlers/ERB.html#method-i-resource_cache_call_pattern).
+
+### Russian Doll Caching
+
+You may want to nest cached fragments inside other cached fragments. This is
+called Russian doll caching.
+
+The advantage of Russian doll caching is that if a single product is updated,
+all the other inner fragments can be reused when regenerating the outer
+fragment.
+
+As explained in the previous section, a cached file will expire if the value of
+`updated_at` changes for a record on which the cached file directly depends.
+However, this will not expire any cache the fragment is nested within.
+
+For example, take the following view:
```erb
-<% cache_if (condition, cache_key_for_products) do %>
- All available products:
+<% cache product do %>
+ <%= render product.games %>
<% end %>
```
-You can also use an Active Record model as the cache key:
+Which in turn renders this view:
```erb
-<% Product.all.each do |p| %>
- <% cache(p) do %>
- <%= link_to p.name, product_url(p) %>
- <% end %>
+<% cache game do %>
+ <%= render game %>
<% end %>
```
-Behind the scenes, a method called `cache_key` will be invoked on the model and it returns a string like `products/23-20130109142513`. The cache key includes the model name, the id and finally the updated_at timestamp. Thus it will automatically generate a new fragment when the product is updated because the key changes.
+If any attribute of game is changed, the `updated_at` value will be set to the
+current time, thereby expiring the cache. However, because `updated_at`
+will not be changed for the product object, that cache will not be expired and
+your app will serve stale data. To fix this, we tie the models together with
+the `touch` method:
+
+```ruby
+class Product < ActiveRecord::Base
+ has_many :games
+end
+
+class Game < ActiveRecord::Base
+ belongs_to :product, touch: true
+end
+```
+
+With `touch` set to true, any action which changes `updated_at` for a game
+record will also change it for the associated product, thereby expiring the
+cache.
-You can also combine the two schemes which is called "Russian Doll Caching":
+### Managing dependencies
-```erb
-<% cache(cache_key_for_products) do %>
- All available products:
- <% Product.all.each do |p| %>
- <% cache(p) do %>
- <%= link_to p.name, product_url(p) %>
- <% end %>
- <% end %>
+In order to correctly invalidate the cache, you need to properly define the
+caching dependencies. Rails is clever enough to handle common cases so you don't
+have to specify anything. However, sometimes, when you're dealing with custom
+helpers for instance, you need to explicitly define them.
+
+#### Implicit dependencies
+
+Most template dependencies can be derived from calls to `render` in the template
+itself. Here are some examples of render calls that `ActionView::Digestor` knows
+how to decode:
+
+```ruby
+render partial: "comments/comment", collection: commentable.comments
+render "comments/comments"
+render 'comments/comments'
+render('comments/comments')
+
+render "header" => render("comments/header")
+
+render(@topic) => render("topics/topic")
+render(topics) => render("topics/topic")
+render(message.topics) => render("topics/topic")
+```
+
+On the other hand, some calls need to be changed to make caching work properly.
+For instance, if you're passing a custom collection, you'll need to change:
+
+```ruby
+render @project.documents.where(published: true)
+```
+
+to:
+
+```ruby
+render partial: "documents/document", collection: @project.documents.where(published: true)
+```
+
+#### Explicit dependencies
+
+Sometimes you'll have template dependencies that can't be derived at all. This
+is typically the case when rendering happens in helpers. Here's an example:
+
+```html+erb
+<%= render_sortable_todolists @project.todolists %>
+```
+
+You'll need to use a special comment format to call those out:
+
+```html+erb
+<%# Template Dependency: todolists/todolist %>
+<%= render_sortable_todolists @project.todolists %>
+```
+
+In some cases, like a single table inheritance setup, you might have a bunch of
+explicit dependencies. Instead of writing every template out, you can use a
+wildcard to match any template in a directory:
+
+```html+erb
+<%# Template Dependency: events/* %>
+<%= render_categorizable_events @person.events %>
+```
+
+As for collection caching, if the partial template doesn't start with a clean
+cache call, you can still benefit from collection caching by adding a special
+comment format anywhere in the template, like:
+
+```html+erb
+<%# Template Collection: notification %>
+<% my_helper_that_calls_cache(some_arg, notification) do %>
+ <%= notification.name %>
<% end %>
```
-It's called "Russian Doll Caching" because it nests multiple fragments. The advantage is that if a single product is updated, all the other inner fragments can be reused when regenerating the outer fragment.
+#### External dependencies
+
+If you use a helper method, for example, inside a cached block and you then update
+that helper, you'll have to bump the cache as well. It doesn't really matter how
+you do it, but the md5 of the template file must change. One recommendation is to
+simply be explicit in a comment, like:
+
+```html+erb
+<%# Helper Dependency Updated: Jul 28, 2015 at 7pm %>
+<%= some_helper_method(person) %>
+```
### Low-Level Caching
@@ -164,7 +297,10 @@ NOTE: Notice that in this example we used the `cache_key` method, so the resulti
### SQL Caching
-Query caching is a Rails feature that caches the result set returned by each query so that if Rails encounters the same query again for that request, it will use the cached result set as opposed to running the query against the database again.
+Query caching is a Rails feature that caches the result set returned by each
+query. If Rails encounters the same query again for that request, it will use
+the cached result set as opposed to running the query against the database
+again.
For example:
@@ -186,21 +322,25 @@ end
The second time the same query is run against the database, it's not actually going to hit the database. The first time the result is returned from the query it is stored in the query cache (in memory) and the second time it's pulled from memory.
-However, it's important to note that query caches are created at the start of an action and destroyed at the end of that action and thus persist only for the duration of the action. If you'd like to store query results in a more persistent fashion, you can in Rails by using low level caching.
+However, it's important to note that query caches are created at the start of
+an action and destroyed at the end of that action and thus persist only for the
+duration of the action. If you'd like to store query results in a more
+persistent fashion, you can with low level caching.
Cache Stores
------------
-Rails provides different stores for the cached data created by **action** and **fragment** caches.
-
-TIP: Page caches are always stored on disk.
+Rails provides different stores for the cached data (apart from SQL and page
+caching).
### Configuration
-You can set up your application's default cache store by calling `config.cache_store=` in the Application definition inside your `config/application.rb` file or in an Application.configure block in an environment specific configuration file (i.e. `config/environments/*.rb`). The first argument will be the cache store to use and the rest of the argument will be passed as arguments to the cache store constructor.
+You can set up your application's default cache store by setting the
+`config.cache_store` configuration option. Other parameters can be passed as
+arguments to the cache store's constructor:
```ruby
-config.cache_store = :memory_store
+config.cache_store = :memory_store, { size: 64.megabytes }
```
NOTE: Alternatively, you can call `ActionController::Base.cache_store` outside of a configuration block.
@@ -225,15 +365,36 @@ There are some common options used by all cache implementations. These can be pa
* `:race_condition_ttl` - This option is used in conjunction with the `:expires_in` option. It will prevent race conditions when cache entries expire by preventing multiple processes from simultaneously regenerating the same entry (also known as the dog pile effect). This option sets the number of seconds that an expired entry can be reused while a new value is being regenerated. It's a good practice to set this value if you use the `:expires_in` option.
+#### Custom Cache Stores
+
+You can create your own custom cache store by simply extending
+`ActiveSupport::Cache::Store` and implementing the appropriate methods. This way,
+you can swap in any number of caching technologies into your Rails application.
+
+To use a custom cache store, simply set the cache store to a new instance of your
+custom class.
+
+```ruby
+config.cache_store = MyCacheStore.new
+```
+
### ActiveSupport::Cache::MemoryStore
-This cache store keeps entries in memory in the same Ruby process. The cache store has a bounded size specified by the `:size` option to the initializer (default is 32Mb). When the cache exceeds the allotted size, a cleanup will occur and the least recently used entries will be removed.
+This cache store keeps entries in memory in the same Ruby process. The cache
+store has a bounded size specified by sending the `:size` option to the
+initializer (default is 32Mb). When the cache exceeds the allotted size, a
+cleanup will occur and the least recently used entries will be removed.
```ruby
config.cache_store = :memory_store, { size: 64.megabytes }
```
-If you're running multiple Ruby on Rails server processes (which is the case if you're using mongrel_cluster or Phusion Passenger), then your Rails server process instances won't be able to share cache data with each other. This cache store is not appropriate for large application deployments, but can work well for small, low traffic sites with only a couple of server processes or for development and test environments.
+If you're running multiple Ruby on Rails server processes (which is the case
+if you're using mongrel_cluster or Phusion Passenger), then your Rails server
+process instances won't be able to share cache data with each other. This cache
+store is not appropriate for large application deployments. However, it can
+work well for small, low traffic sites with only a couple of server processes,
+as well as development and test environments.
### ActiveSupport::Cache::FileStore
@@ -243,9 +404,13 @@ This cache store uses the file system to store entries. The path to the director
config.cache_store = :file_store, "/path/to/cache/directory"
```
-With this cache store, multiple server processes on the same host can share a cache. Server processes running on different hosts could share a cache by using a shared file system, but that set up would not be ideal and is not recommended. The cache store is appropriate for low to medium traffic sites that are served off one or two hosts.
+With this cache store, multiple server processes on the same host can share a
+cache. The cache store is appropriate for low to medium traffic sites that are
+served off one or two hosts. Server processes running on different hosts could
+share a cache by using a shared file system, but that setup is not recommended.
-Note that the cache will grow until the disk is full unless you periodically clear out old entries.
+As the cache will grow until the disk is full, it is recommended to
+periodically clear out old entries.
This is the default cache store implementation.
@@ -253,7 +418,10 @@ This is the default cache store implementation.
This cache store uses Danga's `memcached` server to provide a centralized cache for your application. Rails uses the bundled `dalli` gem by default. This is currently the most popular cache store for production websites. It can be used to provide a single, shared cache cluster with very high performance and redundancy.
-When initializing the cache, you need to specify the addresses for all memcached servers in your cluster. If none is specified, it will assume memcached is running on the local host on the default port, but this is not an ideal set up for larger sites.
+When initializing the cache, you need to specify the addresses for all
+memcached servers in your cluster. If none are specified, it will assume
+memcached is running on localhost on the default port, but this is not an ideal
+setup for larger sites.
The `write` and `fetch` methods on this cache accept two additional options that take advantage of features specific to memcached. You can specify `:raw` to send a value directly to the server with no serialization. The value must be a string or number. You can use memcached direct operations like `increment` and `decrement` only on raw values. You can also specify `:unless_exist` if you don't want memcached to overwrite an existing entry.
@@ -261,36 +429,6 @@ The `write` and `fetch` methods on this cache accept two additional options that
config.cache_store = :mem_cache_store, "cache-1.example.com", "cache-2.example.com"
```
-### ActiveSupport::Cache::EhcacheStore
-
-If you are using JRuby you can use Terracotta's Ehcache as the cache store for your application. Ehcache is an open source Java cache that also offers an enterprise version with increased scalability, management, and commercial support. You must first install the jruby-ehcache-rails3 gem (version 1.1.0 or later) to use this cache store.
-
-```ruby
-config.cache_store = :ehcache_store
-```
-
-When initializing the cache, you may use the `:ehcache_config` option to specify the Ehcache config file to use (where the default is "ehcache.xml" in your Rails config directory), and the :cache_name option to provide a custom name for your cache (the default is rails_cache).
-
-In addition to the standard `:expires_in` option, the `write` method on this cache can also accept the additional `:unless_exist` option, which will cause the cache store to use Ehcache's `putIfAbsent` method instead of `put`, and therefore will not overwrite an existing entry. Additionally, the `write` method supports all of the properties exposed by the [Ehcache Element class](http://ehcache.org/apidocs/net/sf/ehcache/Element.html) , including:
-
-| Property | Argument Type | Description |
-| --------------------------- | ------------------- | ----------------------------------------------------------- |
-| elementEvictionData | ElementEvictionData | Sets this element's eviction data instance. |
-| eternal | boolean | Sets whether the element is eternal. |
-| timeToIdle, tti | int | Sets time to idle |
-| timeToLive, ttl, expires_in | int | Sets time to Live |
-| version | long | Sets the version attribute of the ElementAttributes object. |
-
-These options are passed to the `write` method as Hash options using either camelCase or underscore notation, as in the following examples:
-
-```ruby
-Rails.cache.write('key', 'value', time_to_idle: 60.seconds, timeToLive: 600.seconds)
-caches_action :index, expires_in: 60.seconds, unless_exist: true
-```
-
-For more information about Ehcache, see [http://ehcache.org/](http://ehcache.org/) .
-For more information about Ehcache for JRuby and Rails, see [http://ehcache.org/documentation/jruby.html](http://ehcache.org/documentation/jruby.html)
-
### ActiveSupport::Cache::NullStore
This cache store implementation is meant to be used only in development or test environments and it never stores anything. This can be very useful in development when you have code that interacts directly with `Rails.cache` but caching may interfere with being able to see the results of code changes. With this cache store, all `fetch` and `read` operations will result in a miss.
@@ -299,19 +437,13 @@ This cache store implementation is meant to be used only in development or test
config.cache_store = :null_store
```
-### Custom Cache Stores
-
-You can create your own custom cache store by simply extending `ActiveSupport::Cache::Store` and implementing the appropriate methods. In this way, you can swap in any number of caching technologies into your Rails application.
-
-To use a custom cache store, simply set the cache store to a new instance of the class.
-
-```ruby
-config.cache_store = MyCacheStore.new
-```
-
-### Cache Keys
+Cache Keys
+----------
-The keys used in a cache can be any object that responds to either `:cache_key` or `:to_param`. You can implement the `:cache_key` method on your classes if you need to generate custom keys. Active Record will generate keys based on the class name and record id.
+The keys used in a cache can be any object that responds to either `cache_key` or
+`to_param`. You can implement the `cache_key` method on your classes if you need
+to generate custom keys. Active Record will generate keys based on the class name
+and record id.
You can use Hashes and Arrays of values as cache keys.
@@ -320,7 +452,12 @@ You can use Hashes and Arrays of values as cache keys.
Rails.cache.read(site: "mysite", owners: [owner_1, owner_2])
```
-The keys you use on `Rails.cache` will not be the same as those actually used with the storage engine. They may be modified with a namespace or altered to fit technology backend constraints. This means, for instance, that you can't save values with `Rails.cache` and then try to pull them out with the `memcache-client` gem. However, you also don't need to worry about exceeding the memcached size limit or violating syntax rules.
+The keys you use on `Rails.cache` will not be the same as those actually used with
+the storage engine. They may be modified with a namespace or altered to fit
+technology backend constraints. This means, for instance, that you can't save
+values with `Rails.cache` and then try to pull them out with the `dalli` gem.
+However, you also don't need to worry about exceeding the memcached size limit or
+violating syntax rules.
Conditional GET support
-----------------------
@@ -383,3 +520,9 @@ class ProductsController < ApplicationController
end
end
```
+
+References
+----------
+
+* [DHH's article on key-based expiration](https://signalvnoise.com/posts/3113-how-key-based-cache-expiration-works)
+* [Ryan Bates' Railscast on cache digests](http://railscasts.com/episodes/387-cache-digests)
diff --git a/guides/source/command_line.md b/guides/source/command_line.md
index 0f5a9e4e39..e85f9fc9c6 100644
--- a/guides/source/command_line.md
+++ b/guides/source/command_line.md
@@ -260,7 +260,13 @@ $ bin/rake db:migrate
== CreateHighScores: migrated (0.0019s) ======================================
```
-INFO: Let's talk about unit tests. Unit tests are code that tests and makes assertions about code. In unit testing, we take a little part of code, say a method of a model, and test its inputs and outputs. Unit tests are your friend. The sooner you make peace with the fact that your quality of life will drastically increase when you unit test your code, the better. Seriously. We'll make one in a moment.
+INFO: Let's talk about unit tests. Unit tests are code that tests and makes assertions
+about code. In unit testing, we take a little part of code, say a method of a model,
+and test its inputs and outputs. Unit tests are your friend. The sooner you make
+peace with the fact that your quality of life will drastically increase when you unit
+test your code, the better. Seriously. Please visit
+[the testing guide](http://guides.rubyonrails.org/testing.html) for an in-depth
+look at unit testing.
Let's see the interface Rails created for us.
@@ -406,7 +412,7 @@ Ruby version 2.2.2 (x86_64-linux)
RubyGems version 2.4.6
Rack version 1.6
JavaScript Runtime Node.js (V8)
-Middleware Rack::Sendfile, ActionDispatch::Static, Rack::Lock, #<ActiveSupport::Cache::Strategy::LocalCache::Middleware:0x007ffd131a7c88>, Rack::Runtime, Rack::MethodOverride, ActionDispatch::RequestId, Rails::Rack::Logger, ActionDispatch::ShowExceptions, ActionDispatch::DebugExceptions, ActionDispatch::RemoteIp, ActionDispatch::Reloader, ActionDispatch::Callbacks, ActiveRecord::Migration::CheckPending, ActiveRecord::ConnectionAdapters::ConnectionManagement, ActiveRecord::QueryCache, ActionDispatch::Cookies, ActionDispatch::Session::CookieStore, ActionDispatch::Flash, ActionDispatch::ParamsParser, Rack::Head, Rack::ConditionalGet, Rack::ETag
+Middleware Rack::Sendfile, ActionDispatch::Static, Rack::Lock, #<ActiveSupport::Cache::Strategy::LocalCache::Middleware:0x007ffd131a7c88>, Rack::Runtime, Rack::MethodOverride, ActionDispatch::RequestId, Rails::Rack::Logger, ActionDispatch::ShowExceptions, ActionDispatch::DebugExceptions, ActionDispatch::RemoteIp, ActionDispatch::Reloader, ActionDispatch::Callbacks, ActiveRecord::Migration::CheckPending, ActiveRecord::ConnectionAdapters::ConnectionManagement, ActiveRecord::QueryCache, ActionDispatch::Cookies, ActionDispatch::Session::CookieStore, ActionDispatch::Flash, Rack::Head, Rack::ConditionalGet, Rack::ETag
Application root /home/foobar/commandsapp
Environment development
Database adapter sqlite3
diff --git a/guides/source/configuring.md b/guides/source/configuring.md
index bb6c395c96..87114c4ef0 100644
--- a/guides/source/configuring.md
+++ b/guides/source/configuring.md
@@ -181,7 +181,7 @@ The full set of methods that can be used in this block are as follows:
* `assets` allows to create assets on generating a scaffold. Defaults to `true`.
* `force_plural` allows pluralized model names. Defaults to `false`.
* `helper` defines whether or not to generate helpers. Defaults to `true`.
-* `integration_tool` defines which integration tool to use. Defaults to `nil`.
+* `integration_tool` defines which integration tool to use to generate integration tests. Defaults to `:test_unit`.
* `javascripts` turns on the hook for JavaScript files in generators. Used in Rails for when the `scaffold` generator is run. Defaults to `true`.
* `javascript_engine` configures the engine to be used (for eg. coffee) when generating assets. Defaults to `:js`.
* `orm` defines which orm to use. Defaults to `false` and will use Active Record by default.
@@ -214,7 +214,6 @@ Every Rails application comes with a standard set of middleware which it uses in
* `ActionDispatch::Cookies` sets cookies for the request.
* `ActionDispatch::Session::CookieStore` is responsible for storing the session in cookies. An alternate middleware can be used for this by changing the `config.action_controller.session_store` to an alternate value. Additionally, options passed to this can be configured by using `config.action_controller.session_options`.
* `ActionDispatch::Flash` sets up the `flash` keys. Only available if `config.action_controller.session_store` is set to a value.
-* `ActionDispatch::ParamsParser` parses out parameters from the request into `params`.
* `Rack::MethodOverride` allows the method to be overridden if `params[:_method]` is set. This is the middleware which supports the PATCH, PUT, and DELETE HTTP method types.
* `Rack::Head` converts HEAD requests to GET requests and serves them as so.
@@ -245,7 +244,7 @@ config.middleware.swap ActionController::Failsafe, Lifo::Failsafe
They can also be removed from the stack completely:
```ruby
-config.middleware.delete "Rack::MethodOverride"
+config.middleware.delete Rack::MethodOverride
```
### Configuring i18n
@@ -267,8 +266,8 @@ All these configuration options are delegated to the `I18n` library.
* `config.active_record.logger` accepts a logger conforming to the interface of Log4r or the default Ruby Logger class, which is then passed on to any new database connections made. You can retrieve this logger by calling `logger` on either an Active Record model class or an Active Record model instance. Set to `nil` to disable logging.
* `config.active_record.primary_key_prefix_type` lets you adjust the naming for primary key columns. By default, Rails assumes that primary key columns are named `id` (and this configuration option doesn't need to be set.) There are two other choices:
-** `:table_name` would make the primary key for the Customer class `customerid`
-** `:table_name_with_underscore` would make the primary key for the Customer class `customer_id`
+ * `:table_name` would make the primary key for the Customer class `customerid`
+ * `:table_name_with_underscore` would make the primary key for the Customer class `customer_id`
* `config.active_record.table_name_prefix` lets you set a global string to be prepended to table names. If you set this to `northwest_`, then the Customer class will look for `northwest_customers` as its table. The default is an empty string.
@@ -326,7 +325,7 @@ The schema dumper adds one additional configuration option:
* `config.action_controller.asset_host` sets the host for the assets. Useful when CDNs are used for hosting assets rather than the application server itself.
-* `config.action_controller.perform_caching` configures whether the application should perform caching or not. Set to false in development mode, true in production.
+* `config.action_controller.perform_caching` configures whether the application should perform the caching features provided by the Action Controller component or not. Set to false in development mode, true in production.
* `config.action_controller.default_static_extension` configures the extension used for cached pages. Defaults to `.html`.
@@ -414,7 +413,7 @@ encrypted cookies salt value. Defaults to `'signed encrypted cookie'`.
`config.action_view` includes a small number of configuration settings:
-* `config.action_view.field_error_proc` provides an HTML generator for displaying errors that come from Active Record. The default is
+* `config.action_view.field_error_proc` provides an HTML generator for displaying errors that come from Active Model. The default is
```ruby
Proc.new do |html_tag, instance|
@@ -451,6 +450,9 @@ encrypted cookies salt value. Defaults to `'signed encrypted cookie'`.
* `config.action_view.raise_on_missing_translations` determines whether an
error should be raised for missing translations.
+* `config.action_view.automatically_disable_submit_tag` determines whether
+ submit_tag should automatically disable on click, this defaults to true.
+
### Configuring Action Mailer
There are a number of settings available on `config.action_mailer`:
@@ -533,7 +535,7 @@ There are a few configuration options available in Active Support:
* `config.active_support.time_precision` sets the precision of JSON encoded time values. Defaults to `3`.
-* `config.active_support.halt_callback_chains_on_return_false` specifies whether ActiveRecord, ActiveModel and ActiveModel::Validations callback chains can be halted by returning `false` in a 'before' callback. Defaults to `true`.
+* `ActiveSupport.halt_callback_chains_on_return_false` specifies whether Active Record and Active Model callback chains can be halted by returning `false` in a 'before' callback. Defaults to `true`.
* `ActiveSupport::Logger.silencer` is set to `false` to disable the ability to silence logging in a block. The default is `true`.
@@ -639,7 +641,7 @@ TIP: You don't have to update the database configurations manually. If you look
### Connection Preference
-Since there are two ways to set your connection, via environment variable it is important to understand how the two can interact.
+Since there are two ways to configure your connection (using `config/database.yml` or using an environment variable) it is important to understand how they can interact.
If you have an empty `config/database.yml` file but your `ENV['DATABASE_URL']` is present, then Rails will connect to the database via your environment variable:
@@ -1084,28 +1086,28 @@ development:
timeout: 5000
```
-Since the connection pooling is handled inside of Active Record by default, all application servers (Thin, mongrel, Unicorn etc.) should behave the same. Initially, the database connection pool is empty and it will create additional connections as the demand for them increases, until it reaches the connection pool limit.
+Since the connection pooling is handled inside of Active Record by default, all application servers (Thin, mongrel, Unicorn etc.) should behave the same. The database connection pool is initially empty. As demand for connections increases it will create them until it reaches the connection pool limit.
-Any one request will check out a connection the first time it requires access to the database, after which it will check the connection back in, at the end of the request, meaning that the additional connection slot will be available again for the next request in the queue.
+Any one request will check out a connection the first time it requires access to the database. At the end of the request it will check the connection back in. This means that the additional connection slot will be available again for the next request in the queue.
If you try to use more connections than are available, Active Record will block
-and wait for a connection from the pool. When it cannot get connection, a timeout
-error similar to given below will be thrown.
+you and wait for a connection from the pool. If it cannot get a connection, a
+timeout error similar to that given below will be thrown.
```ruby
-ActiveRecord::ConnectionTimeoutError - could not obtain a database connection within 5 seconds. The max pool size is currently 5; consider increasing it:
+ActiveRecord::ConnectionTimeoutError - could not obtain a database connection within 5.000 seconds (waited 5.000 seconds)
```
-If you get the above error, you might want to increase the size of connection
-pool by incrementing the `pool` option in `database.yml`
+If you get the above error, you might want to increase the size of the
+connection pool by incrementing the `pool` option in `database.yml`
-NOTE. If you are running in a multi-threaded environment, there could be a chance that several threads may be accessing multiple connections simultaneously. So depending on your current request load, you could very well have multiple threads contending for a limited amount of connections.
+NOTE. If you are running in a multi-threaded environment, there could be a chance that several threads may be accessing multiple connections simultaneously. So depending on your current request load, you could very well have multiple threads contending for a limited number of connections.
Custom configuration
--------------------
-You can configure your own code through the Rails configuration object with custom configuration. It works like this:
+You can configure your own code through the Rails configuration object with custom configuration under the `config.x` property. It works like this:
```ruby
config.x.payment_processing.schedule = :daily
diff --git a/guides/source/contributing_to_ruby_on_rails.md b/guides/source/contributing_to_ruby_on_rails.md
index 3279c99c42..6d689804a8 100644
--- a/guides/source/contributing_to_ruby_on_rails.md
+++ b/guides/source/contributing_to_ruby_on_rails.md
@@ -15,6 +15,9 @@ After reading this guide, you will know:
Ruby on Rails is not "someone else's framework." Over the years, hundreds of people have contributed to Ruby on Rails ranging from a single character to massive architectural changes or significant documentation - all with the goal of making Ruby on Rails better for everyone. Even if you don't feel up to writing code or documentation yet, there are a variety of other ways that you can contribute, from reporting issues to testing patches.
+As mentioned in [Rails
+README](https://github.com/rails/rails/blob/master/README.md), everyone interacting in Rails and its sub-projects' codebases, issue trackers, chat rooms, and mailing lists is expected to follow the Rails [code of conduct](https://github.com/rails/rails/blob/master/CODE_OF_CONDUCT.md).
+
--------------------------------------------------------------------------------
Reporting an Issue
@@ -28,7 +31,7 @@ NOTE: Bugs in the most recent released version of Ruby on Rails are likely to ge
If you've found a problem in Ruby on Rails which is not a security risk, do a search on GitHub under [Issues](https://github.com/rails/rails/issues) in case it has already been reported. If you are unable to find any open GitHub issues addressing the problem you found, your next step will be to [open a new one](https://github.com/rails/rails/issues/new). (See the next section for reporting security issues.)
-Your issue report should contain a title and a clear description of the issue at the bare minimum. You should include as much relevant information as possible and should at least post a code sample that demonstrates the issue. It would be even better if you could include a unit test that shows how the expected behavior is not occurring. Your goal should be to make it easy for yourself - and others - to replicate the bug and figure out a fix.
+Your issue report should contain a title and a clear description of the issue at the bare minimum. You should include as much relevant information as possible and should at least post a code sample that demonstrates the issue. It would be even better if you could include a unit test that shows how the expected behavior is not occurring. Your goal should be to make it easy for yourself - and others - to reproduce the bug and figure out a fix.
Then, don't get your hopes up! Unless you have a "Code Red, Mission Critical, the World is Coming to an End" kind of bug, you're creating this issue report in the hope that others with the same problem will be able to collaborate with you on solving it. Do not expect that the issue report will automatically see any activity or that others will jump to fix it. Creating an issue like this is mostly to help yourself start on the path of fixing the problem and for others to confirm it with an "I'm having this problem too" comment.
@@ -61,7 +64,7 @@ can expect it to be marked "invalid" as soon as it's reviewed.
Sometimes, the line between 'bug' and 'feature' is a hard one to draw.
Generally, a feature is anything that adds new behavior, while a bug is
-anything that fixes already existing behavior that is misbehaving. Sometimes,
+anything that causes incorrect behavior. Sometimes,
the core team will have to make a judgement call. That said, the distinction
generally just affects which release your patch will get in to; we love feature
submissions! They just won't get backported to maintenance branches.
@@ -125,7 +128,7 @@ Contributing to the Rails Documentation
Ruby on Rails has two main sets of documentation: the guides, which help you
learn about Ruby on Rails, and the API, which serves as a reference.
-You can help improve the Rails guides by making them more coherent, consistent or readable, adding missing information, correcting factual errors, fixing typos, or bringing it up to date with the latest edge Rails. To get involved in the translation of Rails guides, please see [Translating Rails Guides](https://wiki.github.com/rails/docrails/translating-rails-guides).
+You can help improve the Rails guides by making them more coherent, consistent or readable, adding missing information, correcting factual errors, fixing typos, or bringing them up to date with the latest edge Rails. To get involved in the translation of Rails guides, please see [Translating Rails Guides](https://wiki.github.com/rails/docrails/translating-rails-guides).
You can either open a pull request to [Rails](http://github.com/rails/rails) or
ask the [Rails core team](http://rubyonrails.org/core) for commit access on
@@ -295,7 +298,7 @@ You can run a single test through ruby. For instance:
```bash
$ cd actionmailer
-$ ruby -w -Itest test/mail_layout_test.rb -n test_explicit_class_layout
+$ bundle exec ruby -w -Itest test/mail_layout_test.rb -n test_explicit_class_layout
```
The `-n` option allows you to run a single method instead of the whole
@@ -315,7 +318,7 @@ $ cd activerecord
$ bundle exec rake test:sqlite3
```
-You can now run the tests as you did for `sqlite3`. The tasks are respectively
+You can now run the tests as you did for `sqlite3`. The tasks are respectively:
```bash
test:mysql
@@ -334,7 +337,7 @@ will now run the four of them in turn.
You can also run any single test separately:
```bash
-$ ARCONN=sqlite3 ruby -Itest test/cases/associations/has_many_associations_test.rb
+$ ARCONN=sqlite3 bundle exec ruby -Itest test/cases/associations/has_many_associations_test.rb
```
To run a single test against all adapters, use:
diff --git a/guides/source/credits.html.erb b/guides/source/credits.html.erb
index 61ea0b44ef..1d995581fa 100644
--- a/guides/source/credits.html.erb
+++ b/guides/source/credits.html.erb
@@ -28,7 +28,7 @@ Ruby on Rails Guides: Credits
<h3 class="section">Rails Guides Authors</h3>
<%= author('Ryan Bigg', 'radar', 'radar.png') do %>
- Ryan Bigg works as the Community Manager at <a href="http://spreecommerce.com">Spree Commerce</a> and has been working with Rails since 2006. He's the author of <a href="https://leanpub.com/multi-tenancy-rails">Multi Tenancy With Rails</a> and co-author of <a href="http://manning.com/bigg2">Rails 4 in Action</a>. He's written many gems which can be seen on <a href="https://github.com/radar">his GitHub page</a> and he also tweets prolifically as <a href="http://twitter.com/ryanbigg">@ryanbigg</a>.
+ Ryan Bigg works as a Rails developer at <a href="http://marketplacer.com">Marketplacer</a> and has been working with Rails since 2006. He's the author of <a href="https://leanpub.com/multi-tenancy-rails">Multi Tenancy With Rails</a> and co-author of <a href="http://manning.com/bigg2">Rails 4 in Action</a>. He's written many gems which can be seen on <a href="https://github.com/radar">his GitHub page</a> and he also tweets prolifically as <a href="http://twitter.com/ryanbigg">@ryanbigg</a>.
<% end %>
<%= author('Oscar Del Ben', 'oscardelben', 'oscardelben.jpg') do %>
diff --git a/guides/source/debugging_rails_applications.md b/guides/source/debugging_rails_applications.md
index dc1df8f229..a05abb61d6 100644
--- a/guides/source/debugging_rails_applications.md
+++ b/guides/source/debugging_rails_applications.md
@@ -346,23 +346,13 @@ by asking the debugger for help. Type: `help`
```
(byebug) help
-byebug 2.7.0
+ h[elp][ <cmd>[ <subcmd>]]
-Type 'help <command-name>' for help on a specific command
-
-Available commands:
-backtrace delete enable help list pry next restart source up
-break disable eval info method ps save step var
-catch display exit interrupt next putl set thread
-condition down finish irb p quit show trace
-continue edit frame kill pp reload skip undisplay
+ help -- prints this help.
+ help <cmd> -- prints help on command <cmd>.
+ help <cmd> <subcmd> -- prints help on <cmd>'s subcommand <subcmd>.
```
-TIP: To view the help menu for any command use `help <command-name>` at the
-debugger prompt. For example: _`help list`_. You can abbreviate any debugging
-command by supplying just enough letters to distinguish them from other
-commands. For example, you can use `l` for the `list` command.
-
To see the previous ten lines you should type `list-` (or `l-`).
```
@@ -469,12 +459,12 @@ The debugger can list, stop, resume and switch between running threads by using
the `thread` command (or the abbreviated `th`). This command has a handful of
options:
-* `thread` shows the current thread.
-* `thread list` is used to list all threads and their statuses. The plus +
+* `thread`: shows the current thread.
+* `thread list`: is used to list all threads and their statuses. The plus +
character and the number indicates the current thread of execution.
-* `thread stop _n_` stop thread _n_.
-* `thread resume _n_` resumes thread _n_.
-* `thread switch _n_` switches the current thread context to _n_.
+* `thread stop _n_`: stop thread _n_.
+* `thread resume _n_`: resumes thread _n_.
+* `thread switch _n_`: switches the current thread context to _n_.
This command is very helpful when you are debugging concurrent threads and need
to verify that there are no race conditions in your code.
@@ -502,7 +492,7 @@ current context:
(byebug) instance_variables
[:@_action_has_layout, :@_routes, :@_headers, :@_status, :@_request,
- :@_response, :@_env, :@_prefixes, :@_lookup_context, :@_action_name,
+ :@_response, :@_prefixes, :@_lookup_context, :@_action_name,
:@_response_body, :@marked_for_same_origin_verification, :@_config]
```
@@ -533,7 +523,7 @@ And then ask again for the instance_variables:
```
(byebug) instance_variables
[:@_action_has_layout, :@_routes, :@_headers, :@_status, :@_request,
- :@_response, :@_env, :@_prefixes, :@_lookup_context, :@_action_name,
+ :@_response, :@_prefixes, :@_lookup_context, :@_action_name,
:@_response_body, :@marked_for_same_origin_verification, :@_config,
:@articles]
```
@@ -630,13 +620,16 @@ Processing by ArticlesController#index as HTML
(byebug)
```
-If we use `next`, we want go deep inside method calls. Instead, byebug will go
-to the next line within the same context. In this case, this is the last line of
-the method, so `byebug` will jump to next next line of the previous frame.
+If we use `next`, we won't go deep inside method calls. Instead, `byebug` will
+go to the next line within the same context. In this case, it is the last line
+of the current method, so `byebug` will return to the next line of the caller
+method.
```
(byebug) next
-Next went up a frame because previous frame finished
+
+Next advances to the next line (line 6: `end`), which returns to the next line
+of the caller method:
[4, 13] in /PathTo/project/test_app/app/controllers/articles_controller.rb
4: # GET /articles
@@ -653,8 +646,8 @@ Next went up a frame because previous frame finished
(byebug)
```
-If we use `step` in the same situation, we will literally go to the next Ruby
-instruction to be executed. In this case, Active Support's `week` method.
+If we use `step` in the same situation, `byebug` will literally go to the next
+Ruby instruction to be executed -- in this case, Active Support's `week` method.
```
(byebug) step
@@ -752,12 +745,12 @@ To list all active catchpoints use `catch`.
There are two ways to resume execution of an application that is stopped in the
debugger:
-* `continue` [line-specification] \(or `c`): resume program execution, at the
+* `continue [line-specification]` \(or `c`): resume program execution, at the
address where your script last stopped; any breakpoints set at that address are
bypassed. The optional argument line-specification allows you to specify a line
number to set a one-time breakpoint which is deleted when that breakpoint is
reached.
-* `finish` [frame-number] \(or `fin`): execute until the selected stack frame
+* `finish [frame-number]` \(or `fin`): execute until the selected stack frame
returns. If no frame number is given, the application will run until the
currently selected frame returns. The currently selected frame starts out the
most-recent frame or 0 if no frame positioning (e.g up, down or frame) has been
@@ -773,8 +766,8 @@ environment variable. A specific _line_ can also be given.
### Quitting
-To exit the debugger, use the `quit` command (abbreviated `q`), or its alias
-`exit`.
+To exit the debugger, use the `quit` command (abbreviated to `q`). Or, type `q!`
+to bypass the `Really quit? (y/n)` prompt and exit unconditionally.
A simple quit tries to terminate all threads in effect. Therefore your server
will be stopped and you will have to start it again.
diff --git a/guides/source/development_dependencies_install.md b/guides/source/development_dependencies_install.md
index 295e48f493..4322f03d05 100644
--- a/guides/source/development_dependencies_install.md
+++ b/guides/source/development_dependencies_install.md
@@ -9,7 +9,7 @@ After reading this guide, you will know:
* How to set up your machine for Rails development
* How to run specific groups of unit tests from the Rails test suite
-* How the ActiveRecord portion of the Rails test suite operates
+* How the Active Record portion of the Rails test suite operates
--------------------------------------------------------------------------------
@@ -60,7 +60,7 @@ In Ubuntu you're done with just:
$ sudo apt-get install sqlite3 libsqlite3-dev
```
-And if you are on Fedora or CentOS, you're done with
+If you are on Fedora or CentOS, you're done with
```bash
$ sudo yum install sqlite3 sqlite3-devel
@@ -190,7 +190,7 @@ Follow the instructions given by Homebrew to start these.
In Ubuntu just run:
```bash
-$ sudo apt-get install mysql-server libmysqlclient15-dev
+$ sudo apt-get install mysql-server libmysqlclient-dev
$ sudo apt-get install postgresql postgresql-client postgresql-contrib libpq-dev
```
@@ -213,7 +213,7 @@ FreeBSD users will have to run the following:
```bash
# pkg install mysql56-client mysql56-server
-# pkg install postgresql93-client postgresql93-server
+# pkg install postgresql94-client postgresql94-server
```
Or install them through ports (they are located under the `databases` folder).
diff --git a/guides/source/documents.yaml b/guides/source/documents.yaml
index 9145aee009..4473eba478 100644
--- a/guides/source/documents.yaml
+++ b/guides/source/documents.yaml
@@ -122,6 +122,10 @@
url: autoloading_and_reloading_constants.html
description: This guide documents how autoloading and reloading constants work.
-
+ name: "Caching with Rails: An Overview"
+ url: caching_with_rails.html
+ description: This guide is an introduction to speeding up your Rails application with caching.
+ -
name: Active Support Instrumentation
work_in_progress: true
url: active_support_instrumentation.html
diff --git a/guides/source/engines.md b/guides/source/engines.md
index 3b1588b75a..71844b7990 100644
--- a/guides/source/engines.md
+++ b/guides/source/engines.md
@@ -150,7 +150,7 @@ When you include the engine into an application later on, you will do so with
this line in the Rails application's `Gemfile`:
```ruby
-gem 'blorgh', path: "vendor/engines/blorgh"
+gem 'blorgh', path: 'engines/blorgh'
```
Don't forget to run `bundle install` as usual. By specifying it as a gem within
@@ -639,7 +639,7 @@ However, because you are developing the `blorgh` engine on your local machine,
you will need to specify the `:path` option in your `Gemfile`:
```ruby
-gem 'blorgh', path: "/path/to/blorgh"
+gem 'blorgh', path: 'engines/blorgh'
```
Then run `bundle` to install the gem.
@@ -843,28 +843,10 @@ above the "Title" output inside `app/views/blorgh/articles/show.html.erb`:
```html+erb
<p>
<b>Author:</b>
- <%= @article.author %>
+ <%= @article.author.name %>
</p>
```
-By outputting `@article.author` using the `<%=` tag, the `to_s` method will be
-called on the object. By default, this will look quite ugly:
-
-```
-#<User:0x00000100ccb3b0>
-```
-
-This is undesirable. It would be much better to have the user's name there. To
-do this, add a `to_s` method to the `User` class within the application:
-
-```ruby
-def to_s
- name
-end
-```
-
-Now instead of the ugly Ruby object output, the author's name will be displayed.
-
#### Using a Controller Provided by the Application
Because Rails controllers generally share code for things like authentication
diff --git a/guides/source/form_helpers.md b/guides/source/form_helpers.md
index 8f7d97844e..0a6e2e5dba 100644
--- a/guides/source/form_helpers.md
+++ b/guides/source/form_helpers.md
@@ -40,7 +40,9 @@ When called without arguments like this, it creates a `<form>` tag which, when s
</form>
```
-You'll notice that the HTML contains `input` element with type `hidden`. This `input` is important, because the form cannot be successfully submitted without it. The hidden input element has name attribute of `utf8` enforces browsers to properly respect your form's character encoding and is generated for all forms whether their actions are "GET" or "POST". The second input element with 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 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).
### A Generic Search Form
@@ -103,9 +105,9 @@ checkboxes, text fields, and radio buttons. These basic helpers, with names
ending in `_tag` (such as `text_field_tag` and `check_box_tag`), generate just a
single `<input>` element. The first parameter to these is always the name of the
input. When the form is submitted, the name will be passed along with the form
-data, and will make its way to the `params` hash in the controller with the
-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
+data, and will make its way to the `params` in the controller with the
+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).
@@ -211,9 +213,8 @@ IMPORTANT: The search, telephone, date, time, color, datetime, datetime-local,
month, week, URL, email, number and range inputs are HTML5 controls.
If you require your app to have a consistent experience in older browsers,
you will need an HTML5 polyfill (provided by CSS and/or JavaScript).
-There is definitely [no shortage of solutions for this](https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills), although a couple of popular tools at the moment are
-[Modernizr](http://www.modernizr.com/) and [yepnope](http://yepnopejs.com/),
-which provide a simple way to add functionality based on the presence of
+There is definitely [no shortage of solutions for this](https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills), although a popular tool at the moment is
+[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).
@@ -377,7 +378,7 @@ output:
</form>
```
-When parsing POSTed data, Rails will take into account the special `_method` parameter and acts as if the HTTP method was the one specified inside it ("PATCH" in this example).
+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).
Making Select Boxes with Ease
-----------------------------
@@ -712,13 +713,6 @@ action for a Person model, `params[:person]` would usually be a hash of all the
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.
-TIP: You may find you can try out examples in this section faster by using the console to directly invoke Rack's parameter parser. For example,
-
-```ruby
-Rack::Utils.parse_query "name=fred&phone=0123456789"
-# => {"name"=>"fred", "phone"=>"0123456789"}
-```
-
### Basic Structures
The two basic structures are arrays and hashes. Hashes mirror the syntax used for accessing the value in `params`. For example, if a form contains:
diff --git a/guides/source/generators.md b/guides/source/generators.md
index 14f451cbc9..32bbdc554a 100644
--- a/guides/source/generators.md
+++ b/guides/source/generators.md
@@ -503,6 +503,14 @@ Adds a specified source to `Gemfile`:
add_source "http://gems.github.com"
```
+This method also takes a block:
+
+```ruby
+add_source "http://gems.github.com" do
+ gem "rspec-rails"
+end
+```
+
### `inject_into_file`
Injects a block of code into a defined position in your file.
diff --git a/guides/source/getting_started.md b/guides/source/getting_started.md
index e64a788ac2..5700e71103 100644
--- a/guides/source/getting_started.md
+++ b/guides/source/getting_started.md
@@ -24,8 +24,11 @@ with Rails. However, to get the most out of it, you need to have some
prerequisites installed:
* The [Ruby](https://www.ruby-lang.org/en/downloads) language version 2.2.2 or newer.
-* The [RubyGems](https://rubygems.org) packaging system, which is installed with Ruby
- versions 1.9 and later. To learn more about RubyGems, please read the [RubyGems Guides](http://guides.rubygems.org).
+* Right version of [Development Kit](http://rubyinstaller.org/downloads/), if you
+ are using Windows.
+* The [RubyGems](https://rubygems.org) packaging system, which is installed with
+ Ruby by default. To learn more about RubyGems, please read the
+ [RubyGems Guides](http://guides.rubygems.org).
* A working installation of the [SQLite3 Database](https://www.sqlite.org).
Rails is a web application framework running on the Ruby programming language.
@@ -34,7 +37,6 @@ curve diving straight into Rails. There are several curated lists of online reso
for learning Ruby:
* [Official Ruby Programming Language website](https://www.ruby-lang.org/en/documentation/)
-* [reSRC's List of Free Programming Books](http://resrc.io/list/10/list-of-free-programming-books/#ruby)
Be aware that some resources, while still excellent, cover versions of Ruby as old as
1.6, and commonly 1.8, and will not include some syntax that you will see in day-to-day
@@ -69,10 +71,9 @@ The Rails philosophy includes two major guiding principles:
Creating a New Rails Project
----------------------------
-
-The best way to use this guide is to follow each step as it happens, no code or
-step needed to make this example application has been left out, so you can
-literally follow along step by step.
+The best way to read this guide is to follow it step by step. All steps are
+essential to run this example application and no additional code or steps are
+needed.
By following along with this guide, you'll create a Rails project called
`blog`, a (very) simple weblog. Before you can start building the application,
@@ -89,17 +90,17 @@ Open up a command line prompt. On Mac OS X open Terminal.app, on Windows choose
dollar sign `$` should be run in the command line. Verify that you have a
current version of Ruby installed:
+```bash
+$ ruby -v
+ruby 2.2.2p95
+```
+
TIP: A number of tools exist to help you quickly install Ruby and Ruby
on Rails on your system. Windows users can use [Rails Installer](http://railsinstaller.org),
while Mac OS X users can use [Tokaido](https://github.com/tokaido/tokaidoapp).
For more installation methods for most Operating Systems take a look at
[ruby-lang.org](https://www.ruby-lang.org/en/documentation/installation/).
-```bash
-$ ruby -v
-ruby 2.2.2p95
-```
-
Many popular UNIX-like OSes ship with an acceptable version of SQLite3.
On Windows, if you installed Rails through Rails Installer, you
already have SQLite installed. Others can find installation instructions
@@ -163,7 +164,7 @@ of the files and folders that Rails created by default:
| File/Folder | Purpose |
| ----------- | ------- |
|app/|Contains the controllers, models, views, helpers, mailers and assets for your application. You'll focus on this folder for the remainder of this guide.|
-|bin/|Contains the rails script that starts your app and can contain other scripts you use to setup, deploy or run your application.|
+|bin/|Contains the rails script that starts your app and can contain other scripts you use to setup, update, deploy or run your application.|
|config/|Configure your application's routes, database, and more. This is covered in more detail in [Configuring Rails Applications](configuring.html).|
|config.ru|Rack configuration for Rack based servers used to start the application.|
|db/|Contains your current database schema, as well as the database migrations.|
@@ -298,6 +299,7 @@ Rails.application.routes.draw do
# The priority is based upon order of creation:
# first created -> highest priority.
+ # See how all your routes lay out with "rake routes".
#
# You can have the root of your site routed with "root"
# root 'welcome#index'
@@ -619,7 +621,7 @@ def create
end
```
-The `render` method here is taking a very simple hash with a key of `plain` and
+The `render` method here is taking a very simple hash with a key of `:plain` and
value of `params[:article].inspect`. The `params` method is the object which
represents the parameters (or fields) coming in from the form. The `params`
method returns an `ActiveSupport::HashWithIndifferentAccess` object, which
@@ -1545,20 +1547,17 @@ class CreateComments < ActiveRecord::Migration
create_table :comments do |t|
t.string :commenter
t.text :body
-
- # this line adds an integer column called `article_id`.
- t.references :article, index: true
+ t.references :article, index: true, foreign_key: true
t.timestamps null: false
end
- add_foreign_key :comments, :articles
end
end
```
-The `t.references` line sets up a foreign key column for the association between
-the two models. An index for this association is also created on this column.
-Go ahead and run the migration:
+The `t.references` line creates an integer column called `article_id`, an index
+for it, and a foreign key constraint that points to the `id` column of the `articles`
+table. Go ahead and run the migration:
```bash
$ bin/rake db:migrate
@@ -1571,8 +1570,6 @@ run against the current database, so in this case you will just see:
== CreateComments: migrating =================================================
-- create_table(:comments)
-> 0.0115s
--- add_foreign_key(:comments, :articles)
- -> 0.0000s
== CreateComments: migrated (0.0119s) ========================================
```
diff --git a/guides/source/i18n.md b/guides/source/i18n.md
index 9f0ed1a85b..87d2fafaf3 100644
--- a/guides/source/i18n.md
+++ b/guides/source/i18n.md
@@ -51,7 +51,7 @@ Thus, the Ruby I18n gem is split into two parts:
As a user you should always only access the public methods on the I18n module, but it is useful to know about the capabilities of the backend.
-NOTE: It is possible (or even desirable) to swap the shipped Simple backend with a more powerful one, which would store translation data in a relational database, GetText dictionary, or similar. See section [Using different backends](#using-different-backends) below.
+NOTE: It is possible to swap the shipped Simple backend with a more powerful one, which would store translation data in a relational database, GetText dictionary, or similar. See section [Using different backends](#using-different-backends) below.
### The Public I18n API
@@ -109,7 +109,7 @@ The **translations load path** (`I18n.load_path`) is an array of paths to files
NOTE: The backend lazy-loads these translations when a translation is looked up for the first time. This backend can be swapped with something else even after translations have already been announced.
-The default `application.rb` file has instructions on how to add locales from another directory and how to set a different default locale.
+The default `config/application.rb` file has instructions on how to add locales from another directory and how to set a different default locale.
```ruby
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
@@ -117,7 +117,7 @@ The default `application.rb` file has instructions on how to add locales from an
# config.i18n.default_locale = :de
```
-The load path must be specified before any translations are looked up. To change the default locale from an initializer instead of `application.rb`:
+The load path must be specified before any translations are looked up. To change the default locale from an initializer instead of `config/application.rb`:
```ruby
# config/initializers/locale.rb
@@ -210,14 +210,14 @@ This approach has almost the same set of advantages as setting the locale from t
Getting the locale from `params` and setting it accordingly is not hard; including it in every URL and thus **passing it through the requests** is. To include an explicit option in every URL, e.g. `link_to(books_url(locale: I18n.locale))`, would be tedious and probably impossible, of course.
-Rails contains infrastructure for "centralizing dynamic decisions about the URLs" in its [`ApplicationController#default_url_options`](http://api.rubyonrails.org/classes/ActionDispatch/Routing/Mapper/Base.html#method-i-default_url_options), which is useful precisely in this scenario: it enables us to set "defaults" for [`url_for`](http://api.rubyonrails.org/classes/ActionDispatch/Routing/UrlFor.html#method-i-url_for) and helper methods dependent on it (by implementing/overriding this method).
+Rails contains infrastructure for "centralizing dynamic decisions about the URLs" in its [`ApplicationController#default_url_options`](http://api.rubyonrails.org/classes/ActionDispatch/Routing/Mapper/Base.html#method-i-default_url_options), which is useful precisely in this scenario: it enables us to set "defaults" for [`url_for`](http://api.rubyonrails.org/classes/ActionDispatch/Routing/UrlFor.html#method-i-url_for) and helper methods dependent on it (by implementing/overriding `default_url_options`).
We can include something like this in our `ApplicationController` then:
```ruby
# app/controllers/application_controller.rb
-def default_url_options(options = {})
- { locale: I18n.locale }.merge options
+def default_url_options
+ { locale: I18n.locale }
end
```
@@ -225,7 +225,7 @@ Every helper method dependent on `url_for` (e.g. helpers for named routes like `
You may be satisfied with this. It does impact the readability of URLs, though, when the locale "hangs" at the end of every URL in your application. Moreover, from the architectural standpoint, locale is usually hierarchically above the other parts of the application domain: and URLs should reflect this.
-You probably want URLs to look like this: `www.example.com/en/books` (which loads the English locale) and `www.example.com/nl/books` (which loads the Dutch locale). This is achievable with the "over-riding `default_url_options`" strategy from above: you just have to set up your routes with [`scoping`](http://api.rubyonrails.org/classes/ActionDispatch/Routing/Mapper/Scoping.html) option in this way:
+You probably want URLs to look like this: `http://www.example.com/en/books` (which loads the English locale) and `http://www.example.com/nl/books` (which loads the Dutch locale). This is achievable with the "over-riding `default_url_options`" strategy from above: you just have to set up your routes with [`scope`](http://api.rubyonrails.org/classes/ActionDispatch/Routing/Mapper/Scoping.html):
```ruby
# config/routes.rb
@@ -234,7 +234,9 @@ scope "/:locale" do
end
```
-Now, when you call the `books_path` method you should get `"/en/books"` (for the default locale). An URL like `http://localhost:3001/nl/books` should load the Dutch locale, then, and following calls to `books_path` should return `"/nl/books"` (because the locale changed).
+Now, when you call the `books_path` method you should get `"/en/books"` (for the default locale). A URL like `http://localhost:3001/nl/books` should load the Dutch locale, then, and following calls to `books_path` should return `"/nl/books"` (because the locale changed).
+
+WARNING. Since the return value of `default_url_options` is cached per request, the URLs in a locale selector cannot be generated invoking helpers in a loop that sets the corresponding `I18n.locale` in each iteration. Instead, leave `I18n.locale` untouched, and pass an explicit `:locale` option to the helper, or edit `request.original_fullpath`.
If you don't want to force the use of a locale in your routes you can use an optional path scope (denoted by the parentheses) like so:
@@ -247,7 +249,7 @@ end
With this approach you will not get a `Routing Error` when accessing your resources such as `http://localhost:3001/books` without a locale. This is useful for when you want to use the default locale when one is not specified.
-Of course, you need to take special care of the root URL (usually "homepage" or "dashboard") of your application. An URL like `http://localhost:3001/nl` will not work automatically, because the `root to: "books#index"` declaration in your `routes.rb` doesn't take locale into account. (And rightly so: there's only one "root" URL.)
+Of course, you need to take special care of the root URL (usually "homepage" or "dashboard") of your application. A URL like `http://localhost:3001/nl` will not work automatically, because the `root to: "books#index"` declaration in your `routes.rb` doesn't take locale into account. (And rightly so: there's only one "root" URL.)
You would probably need to map URLs like these:
diff --git a/guides/source/kindle/layout.html.erb b/guides/source/kindle/layout.html.erb
index f0a286210b..fd8746776b 100644
--- a/guides/source/kindle/layout.html.erb
+++ b/guides/source/kindle/layout.html.erb
@@ -14,12 +14,12 @@
<% if content_for? :header_section %>
<%= yield :header_section %>
- <div class="pagebreak">
+ <div class="pagebreak"></div>
<% end %>
<% if content_for? :index_section %>
<%= yield :index_section %>
- <div class="pagebreak">
+ <div class="pagebreak"></div>
<% end %>
<%= yield.html_safe %>
diff --git a/guides/source/kindle/toc.ncx.erb b/guides/source/kindle/toc.ncx.erb
index 2c6d8e3bdf..5094fea4ca 100644
--- a/guides/source/kindle/toc.ncx.erb
+++ b/guides/source/kindle/toc.ncx.erb
@@ -32,12 +32,12 @@
</navPoint>
<navPoint class="article" id="credits" playOrder="3">
<navLabel><text>Credits</text></navLabel>
- <content src="credits.html">
+ <content src="credits.html"/>
</navPoint>
<navPoint class="article" id="copyright" playOrder="4">
<navLabel><text>Copyright &amp; License</text></navLabel>
- <content src="copyright.html">
- </navPoint>
+ <content src="copyright.html"/>
+ </navPoint>
</navPoint>
<% play_order = 4 %>
@@ -47,7 +47,7 @@
<text><%= section['name'] %></text>
</navLabel>
<content src="<%=section['documents'].first['url'] %>"/>
-
+
<% section['documents'].each_with_index do |document, document_no| %>
<navPoint class="article" id="_<%=section_no+1%>.<%=document_no+1%>" playOrder="<%=play_order +=1 %>">
<navLabel>
diff --git a/guides/source/layouts_and_rendering.md b/guides/source/layouts_and_rendering.md
index 94cd7297e2..71cc030f6a 100644
--- a/guides/source/layouts_and_rendering.md
+++ b/guides/source/layouts_and_rendering.md
@@ -280,7 +280,7 @@ render body: "raw"
```
TIP: This option should be used only if you don't care about the content type of
-the response. Using `:plain` or `:html` might be more appropriate in most of the
+the response. Using `:plain` or `:html` might be more appropriate most of the
time.
NOTE: Unless overridden, your response returned from this render option will be
@@ -360,7 +360,6 @@ Rails understands both numeric status codes and the corresponding symbols shown
| | 303 | :see_other |
| | 304 | :not_modified |
| | 305 | :use_proxy |
-| | 306 | :reserved |
| | 307 | :temporary_redirect |
| | 308 | :permanent_redirect |
| **Client Error** | 400 | :bad_request |
@@ -376,10 +375,10 @@ Rails understands both numeric status codes and the corresponding symbols shown
| | 410 | :gone |
| | 411 | :length_required |
| | 412 | :precondition_failed |
-| | 413 | :request_entity_too_large |
-| | 414 | :request_uri_too_long |
+| | 413 | :payload_too_large |
+| | 414 | :uri_too_long |
| | 415 | :unsupported_media_type |
-| | 416 | :requested_range_not_satisfiable |
+| | 416 | :range_not_satisfiable |
| | 417 | :expectation_failed |
| | 422 | :unprocessable_entity |
| | 423 | :locked |
@@ -782,7 +781,7 @@ The `javascript_include_tag` helper returns an HTML `script` tag for each source
If you are using Rails with the [Asset Pipeline](asset_pipeline.html) enabled, this helper will generate a link to `/assets/javascripts/` rather than `public/javascripts` which was used in earlier versions of Rails. This link is then served by the asset pipeline.
-A JavaScript file within a Rails application or Rails engine goes in one of three locations: `app/assets`, `lib/assets` or `vendor/assets`. These locations are explained in detail in the [Asset Organization section in the Asset Pipeline Guide](asset_pipeline.html#asset-organization)
+A JavaScript file within a Rails application or Rails engine goes in one of three locations: `app/assets`, `lib/assets` or `vendor/assets`. These locations are explained in detail in the [Asset Organization section in the Asset Pipeline Guide](asset_pipeline.html#asset-organization).
You can specify a full path relative to the document root, or a URL, if you prefer. For example, to link to a JavaScript file that is inside a directory called `javascripts` inside of one of `app/assets`, `lib/assets` or `vendor/assets`, you would do this:
diff --git a/guides/source/plugins.md b/guides/source/plugins.md
index 4e630a39f3..b94c26a1ae 100644
--- a/guides/source/plugins.md
+++ b/guides/source/plugins.md
@@ -443,4 +443,3 @@ $ bundle exec rake rdoc
* [Developing a RubyGem using Bundler](https://github.com/radar/guides/blob/master/gem-development.md)
* [Using .gemspecs as Intended](http://yehudakatz.com/2010/04/02/using-gemspecs-as-intended/)
* [Gemspec Reference](http://guides.rubygems.org/specification-reference/)
-* [GemPlugins: A Brief Introduction to the Future of Rails Plugins](http://www.intridea.com/blog/2008/6/11/gemplugins-a-brief-introduction-to-the-future-of-rails-plugins)
diff --git a/guides/source/rails_application_templates.md b/guides/source/rails_application_templates.md
index b7364536c3..edd54826cf 100644
--- a/guides/source/rails_application_templates.md
+++ b/guides/source/rails_application_templates.md
@@ -78,7 +78,7 @@ gem_group :development, :test do
end
```
-### add_source(source, options = {})
+### add_source(source, options={}, &block)
Adds the given source to the generated application's `Gemfile`.
@@ -88,6 +88,14 @@ For example, if you need to source a gem from `"http://code.whytheluckystiff.net
add_source "http://code.whytheluckystiff.net"
```
+If block is given, gem entries in block are wrapped into the source group.
+
+```ruby
+add_source "http://gems.github.com/" do
+ gem "rspec-rails"
+end
+```
+
### environment/application(data=nil, options={}, &block)
Adds a line inside the `Application` class for `config/application.rb`.
diff --git a/guides/source/rails_on_rack.md b/guides/source/rails_on_rack.md
index 993cd5ac44..87f869aff3 100644
--- a/guides/source/rails_on_rack.md
+++ b/guides/source/rails_on_rack.md
@@ -58,23 +58,6 @@ class Server < ::Rack::Server
end
```
-Here's how it loads the middlewares:
-
-```ruby
-def middleware
- middlewares = []
- middlewares << [::Rack::ContentLength]
- Hash.new(middlewares)
-end
-```
-
-`Rails::Rack::Debugger` is primarily useful only in the development environment. The following table explains the usage of the loaded middlewares:
-
-| Middleware | Purpose |
-| ----------------------- | --------------------------------------------------------------------------------- |
-| `Rails::Rack::Debugger` | Starts Debugger |
-| `Rack::ContentLength` | Counts the number of bytes in the response and set the HTTP Content-Length header |
-
### `rackup`
To use `rackup` instead of Rails' `rails server`, you can put the following inside `config.ru` of your Rails application's root directory:
@@ -82,9 +65,6 @@ To use `rackup` instead of Rails' `rails server`, you can put the following insi
```ruby
# Rails.root/config.ru
require ::File.expand_path('../config/environment', __FILE__)
-
-use Rails::Rack::Debugger
-use Rack::ContentLength
run Rails.application
```
@@ -141,7 +121,6 @@ use ActiveRecord::QueryCache
use ActionDispatch::Cookies
use ActionDispatch::Session::CookieStore
use ActionDispatch::Flash
-use ActionDispatch::ParamsParser
use Rack::Head
use Rack::ConditionalGet
use Rack::ETag
@@ -192,7 +171,7 @@ Add the following lines to your application configuration:
```ruby
# config/application.rb
-config.middleware.delete "Rack::Lock"
+config.middleware.delete Rack::Lock
```
And now if you inspect the middleware stack, you'll find that `Rack::Lock` is
@@ -212,16 +191,16 @@ If you want to remove session related middleware, do the following:
```ruby
# config/application.rb
-config.middleware.delete "ActionDispatch::Cookies"
-config.middleware.delete "ActionDispatch::Session::CookieStore"
-config.middleware.delete "ActionDispatch::Flash"
+config.middleware.delete ActionDispatch::Cookies
+config.middleware.delete ActionDispatch::Session::CookieStore
+config.middleware.delete ActionDispatch::Flash
```
And to remove browser related middleware,
```ruby
# config/application.rb
-config.middleware.delete "Rack::MethodOverride"
+config.middleware.delete Rack::MethodOverride
```
### Internal Middleware Stack
@@ -304,10 +283,6 @@ Much of Action Controller's functionality is implemented as Middlewares. The fol
* Sets up the flash keys. Only available if `config.action_controller.session_store` is set to a value.
-**`ActionDispatch::ParamsParser`**
-
-* Parses out parameters from the request into `params`.
-
**`Rack::Head`**
* Converts HEAD requests to `GET` requests and serves them as so.
@@ -329,8 +304,6 @@ Resources
* [Official Rack Website](http://rack.github.io)
* [Introducing Rack](http://chneukirchen.org/blog/archive/2007/02/introducing-rack.html)
-* [Ruby on Rack #1 - Hello Rack!](http://m.onkey.org/ruby-on-rack-1-hello-rack)
-* [Ruby on Rack #2 - The Builder](http://m.onkey.org/ruby-on-rack-2-the-builder)
### Understanding Middlewares
diff --git a/guides/source/routing.md b/guides/source/routing.md
index 52f11f92bd..3175716a9c 100644
--- a/guides/source/routing.md
+++ b/guides/source/routing.md
@@ -7,7 +7,7 @@ This guide covers the user-facing features of Rails routing.
After reading this guide, you will know:
-* How to interpret the code in `routes.rb`.
+* How to interpret the code in `config/routes.rb`.
* How to construct your own routes, using either the preferred resourceful style or the `match` method.
* What parameters to expect an action to receive.
* How to automatically create paths and URLs using route helpers.
@@ -83,7 +83,9 @@ Rails would dispatch that request to the `destroy` method on the `photos` contro
### CRUD, Verbs, and Actions
-In Rails, a resourceful route provides a mapping between HTTP verbs and URLs to controller actions. By convention, each action also maps to particular CRUD operations in a database. A single entry in the routing file, such as:
+In Rails, a resourceful route provides a mapping between HTTP verbs and URLs to
+controller actions. By convention, each action also maps to a specific CRUD
+operation in a database. A single entry in the routing file, such as:
```ruby
resources :photos
@@ -615,6 +617,8 @@ get 'photos/:id', to: 'photos#show', defaults: { format: 'jpg' }
Rails would match `photos/12` to the `show` action of `PhotosController`, and set `params[:format]` to `"jpg"`.
+NOTE: You cannot override defaults via query parameters - this is for security reasons. The only defaults that can be overridden are dynamic segments via substitution in the URL path.
+
### Naming Routes
You can specify a name for any route using the `:as` option:
@@ -793,7 +797,11 @@ get '/stories/:name', to: redirect { |path_params, req| "/articles/#{path_params
get '/stories', to: redirect { |path_params, req| "/articles/#{req.subdomain}" }
```
-Please note that this redirection is a 301 "Moved Permanently" redirect. Keep in mind that some web browsers or proxy servers will cache this type of redirect, making the old page inaccessible.
+Please note that default redirection is a 301 "Moved Permanently" redirect. Keep in mind that some web browsers or proxy servers will cache this type of redirect, making the old page inaccessible. You can use the `:status` option to change the response status:
+
+```ruby
+get '/stories/:name', to: redirect('/articles/%{name}', status: 302)
+```
In all of these cases, if you don't provide the leading host (`http://www.example.com`), Rails will take those details from the current request.
@@ -1087,6 +1095,20 @@ edit_videos GET /videos/:identifier/edit(.:format) videos#edit
Video.find_by(identifier: params[:identifier])
```
+You can override `ActiveRecord::Base#to_param` of a related model to construct
+a URL:
+
+```ruby
+class Video < ActiveRecord::Base
+ def to_param
+ identifier
+ end
+end
+
+video = Video.find_by(identifier: "Roman-Holiday")
+edit_videos_path(video) # => "/videos/Roman-Holiday"
+```
+
Inspecting and Testing Routes
-----------------------------
@@ -1096,7 +1118,7 @@ Rails offers facilities for inspecting and testing your routes.
To get a complete list of the available routes in your application, visit `http://localhost:3000/rails/info/routes` in your browser while your server is running in the **development** environment. You can also execute the `rake routes` command in your terminal to produce the same output.
-Both methods will list all of your routes, in the same order that they appear in `routes.rb`. For each route, you'll see:
+Both methods will list all of your routes, in the same order that they appear in `config/routes.rb`. For each route, you'll see:
* The route name (if any)
* The HTTP verb used (if the route doesn't respond to all verbs)
diff --git a/guides/source/security.md b/guides/source/security.md
index 93580d4d4e..fb9ee7b412 100644
--- a/guides/source/security.md
+++ b/guides/source/security.md
@@ -93,9 +93,16 @@ Rails 2 introduced a new default session storage, CookieStore. CookieStore saves
* Cookies imply a strict size limit of 4kB. This is fine as you should not store large amounts of data in a session anyway, as described before. _Storing the current user's database id in a session is usually ok_.
-* The client can see everything you store in a session, because it is stored in clear-text (actually Base64-encoded, so not encrypted). So, of course, _you don't want to store any secrets here_. To prevent session hash tampering, a digest is calculated from the session with a server-side secret and inserted into the end of the cookie.
+* The client can see everything you store in a session, because it is stored in clear-text (actually Base64-encoded, so not encrypted). So, of course, _you don't want to store any secrets here_. To prevent session hash tampering, a digest is calculated from the session with a server-side secret (`secrets.secret_token`) and inserted into the end of the cookie.
-That means the security of this storage depends on this secret (and on the digest algorithm, which defaults to SHA1, for compatibility). So _don't use a trivial secret, i.e. a word from a dictionary, or one which is shorter than 30 characters_.
+However, since Rails 4, the default store is EncryptedCookieStore. With
+EncryptedCookieStore the session is encrypted before being stored in a cookie.
+This prevents the user from accessing and tampering the content of the cookie.
+Thus the session becomes a more secure place to store data. The encryption is
+done using a server-side secret key `secrets.secret_key_base` stored in
+`config/secrets.yml`.
+
+That means the security of this storage depends on this secret (and on the digest algorithm, which defaults to SHA1, for compatibility). So _don't use a trivial secret, i.e. a word from a dictionary, or one which is shorter than 30 characters, use `rake secret` instead_.
`secrets.secret_key_base` is used for specifying a key which allows sessions for the application to be verified against a known secure key to prevent tampering. Applications get `secrets.secret_key_base` initialized to a random key present in `config/secrets.yml`, e.g.:
@@ -189,13 +196,12 @@ This attack method works by including malicious code or a link in a page that ac
![](images/csrf.png)
-In the [session chapter](#sessions) you have learned that most Rails applications use cookie-based sessions. Either they store the session id in the cookie and have a server-side session hash, or the entire session hash is on the client-side. In either case the browser will automatically send along the cookie on every request to a domain, if it can find a cookie for that domain. The controversial point is, that it will also send the cookie, if the request comes from a site of a different domain. Let's start with an example:
+In the [session chapter](#sessions) you have learned that most Rails applications use cookie-based sessions. Either they store the session id in the cookie and have a server-side session hash, or the entire session hash is on the client-side. In either case the browser will automatically send along the cookie on every request to a domain, if it can find a cookie for that domain. The controversial point is that if the request comes from a site of a different domain, it will also send the cookie. Let's start with an example:
-* Bob browses a message board and views a post from a hacker where there is a crafted HTML image element. The element references a command in Bob's project management application, rather than an image file.
-* `<img src="http://www.webapp.com/project/1/destroy">`
-* Bob's session at www.webapp.com is still alive, because he didn't log out a few minutes ago.
-* By viewing the post, the browser finds an image tag. It tries to load the suspected image from www.webapp.com. As explained before, it will also send along the cookie with the valid session id.
-* The web application at www.webapp.com verifies the user information in the corresponding session hash and destroys the project with the ID 1. It then returns a result page which is an unexpected result for the browser, so it will not display the image.
+* Bob browses a message board and views a post from a hacker where there is a crafted HTML image element. The element references a command in Bob's project management application, rather than an image file: `<img src="http://www.webapp.com/project/1/destroy">`
+* Bob's session at `www.webapp.com` is still alive, because he didn't log out a few minutes ago.
+* By viewing the post, the browser finds an image tag. It tries to load the suspected image from `www.webapp.com`. As explained before, it will also send along the cookie with the valid session id.
+* The web application at `www.webapp.com` verifies the user information in the corresponding session hash and destroys the project with the ID 1. It then returns a result page which is an unexpected result for the browser, so it will not display the image.
* Bob doesn't notice the attack - but a few days later he finds out that project number one is gone.
It is important to notice that the actual crafted image or link doesn't necessarily have to be situated in the web application's domain, it can be anywhere - in a forum, blog post or email.
@@ -218,9 +224,9 @@ The HTTP protocol basically provides two main types of requests - GET and POST (
* The interaction _changes the state_ of the resource in a way that the user would perceive (e.g., a subscription to a service), or
* The user is _held accountable for the results_ of the interaction.
-If your web application is RESTful, you might be used to additional HTTP verbs, such as PATCH, PUT or DELETE. Most of today's web browsers, however do not support them - only GET and POST. Rails uses a hidden `_method` field to handle this barrier.
+If your web application is RESTful, you might be used to additional HTTP verbs, such as PATCH, PUT or DELETE. Most of today's web browsers, however, do not support them - only GET and POST. Rails uses a hidden `_method` field to handle this barrier.
-_POST requests can be sent automatically, too_. Here is an example for a link which displays www.harmless.com as destination in the browser's status bar. In fact it dynamically creates a new form that sends a POST request.
+_POST requests can be sent automatically, too_. In this example, the link www.harmless.com is shown as the destination in the browser's status bar. But it has actually dynamically created a new form that sends a POST request.
```html
<a href="http://www.harmless.com/" onclick="
@@ -239,7 +245,9 @@ Or the attacker places the code into the onmouseover event handler of an image:
<img src="http://www.harmless.com/img" width="400" height="400" onmouseover="..." />
```
-There are many other possibilities, like using a `<script>` tag to make a cross-site request to a URL with a JSONP or JavaScript response. The response is executable code that the attacker can find a way to run, possibly extracting sensitive data. To protect against this data leakage, we disallow cross-site `<script>` tags. Only Ajax requests may have JavaScript responses since `XMLHttpRequest` is subject to the browser Same-Origin policy - meaning only your site can initiate the request.
+There are many other possibilities, like using a `<script>` tag to make a cross-site request to a URL with a JSONP or JavaScript response. The response is executable code that the attacker can find a way to run, possibly extracting sensitive data. To protect against this data leakage, we must disallow cross-site `<script>` tags. Ajax requests, however, obey the browser's same-origin policy (only your own site is allowed to initiate `XmlHttpRequest`) so we can safely allow them to return JavaScript responses.
+
+Note: We can't distinguish a `<script>` tag's origin—whether it's a tag on your own site or on some other malicious site—so we must block all `<script>` across the board, even if it's actually a safe same-origin script served from your own site. In these cases, explicitly skip CSRF protection on actions that serve JavaScript meant for a `<script>` tag.
To protect against all other forged requests, we introduce a _required security token_ that our site knows but other sites don't know. We include the security token in requests and verify it on the server. This is a one-liner in your application controller, and is the default for newly created rails applications:
@@ -293,7 +301,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&param2=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 an 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 whitelist approach, as opposed to removing unexpected parameters). _And if you redirect to a URL, check it with a whitelist or a regular expression_.
#### Self-contained XSS
@@ -398,7 +406,7 @@ NOTE: _Almost every web application has to deal with authorization and authentic
There are a number of authentication plug-ins for Rails available. Good ones, such as the popular [devise](https://github.com/plataformatec/devise) and [authlogic](https://github.com/binarylogic/authlogic), store only encrypted passwords, not plain-text passwords. In Rails 3.1 you can use the built-in `has_secure_password` method which has similar features.
-Every new user gets an activation code to activate their account when they get an e-mail with a link in it. After activating the account, the activation_code columns will be set to NULL in the database. If someone requested an URL like these, they would be logged in as the first activated user found in the database (and chances are that this is the administrator):
+Every new user gets an activation code to activate their account when they get an e-mail with a link in it. After activating the account, the activation_code columns will be set to NULL in the database. If someone requested a URL like these, they would be logged in as the first activated user found in the database (and chances are that this is the administrator):
```
http://localhost:3006/user/activate
@@ -754,7 +762,7 @@ s = sanitize(user_input, tags: tags, attributes: %w(href title))
This allows only the given tags and does a good job, even against all kinds of tricks and malformed tags.
-As a second step, _it is good practice to escape all output of the application_, especially when re-displaying user input, which hasn't been input-filtered (as in the search form example earlier on). _Use `escapeHTML()` (or its alias `h()`) method_ to replace the HTML input characters &amp;, &quot;, &lt;, &gt; by their uninterpreted representations in HTML (`&amp;`, `&quot;`, `&lt`;, and `&gt;`). However, it can easily happen that the programmer forgets to use it, so _it is recommended to use the SafeErb gem. SafeErb reminds you to escape strings from external sources.
+As a second step, _it is good practice to escape all output of the application_, especially when re-displaying user input, which hasn't been input-filtered (as in the search form example earlier on). _Use `escapeHTML()` (or its alias `h()`) method_ to replace the HTML input characters &amp;, &quot;, &lt;, and &gt; by their uninterpreted representations in HTML (`&amp;`, `&quot;`, `&lt;`, and `&gt;`). However, it can easily happen that the programmer forgets to use it, so _it is recommended to use the SafeErb gem. SafeErb reminds you to escape strings from external sources.
##### Obfuscation and Encoding Injection
@@ -785,15 +793,13 @@ Another proof-of-concept webmail worm is Nduja, a cross-domain worm for four Ita
In December 2006, 34,000 actual user names and passwords were stolen in a [MySpace phishing attack](http://news.netcraft.com/archives/2006/10/27/myspace_accounts_compromised_by_phishers.html). The idea of the attack was to create a profile page named "login_home_index_html", so the URL looked very convincing. Specially-crafted HTML and CSS was used to hide the genuine MySpace content from the page and instead display its own login form.
-The MySpace Samy worm will be discussed in the CSS Injection section.
-
### CSS Injection
INFO: _CSS Injection is actually JavaScript injection, because some browsers (IE, some versions of Safari and others) allow JavaScript in CSS. Think twice about allowing custom CSS in your web application._
-CSS Injection is explained best by a well-known worm, the [MySpace Samy worm](http://namb.la/popular/tech.html). This worm automatically sent a friend request to Samy (the attacker) simply by visiting his profile. Within several hours he had over 1 million friend requests, but it creates too much traffic on MySpace, so that the site goes offline. The following is a technical explanation of the worm.
+CSS Injection is explained best by the well-known [MySpace Samy worm](http://namb.la/popular/tech.html). This worm automatically sent a friend request to Samy (the attacker) simply by visiting his profile. Within several hours he had over 1 million friend requests, which created so much traffic that MySpace went offline. The following is a technical explanation of that worm.
-MySpace blocks many tags, however it allows CSS. So the worm's author put JavaScript into CSS like this:
+MySpace blocked many tags, but allowed CSS. So the worm's author put JavaScript into CSS like this:
```html
<div style="background:url('javascript:alert(1)')">
@@ -817,7 +823,7 @@ The next problem was MySpace filtering the word "javascript", so the author used
<div id="mycode" expr="alert('hah!')" style="background:url('java↵
script:eval(document.all.mycode.expr)')">
```
-Another problem for the worm's author were CSRF security tokens. Without them he couldn't send a friend request over POST. He got around it by sending a GET to the page right before adding a user and parsing the result for the CSRF token.
+Another problem for the worm's author was the [CSRF security tokens](#cross-site-request-forgery-csrf). Without them he couldn't send a friend request over POST. He got around it by sending a GET to the page right before adding a user and parsing the result for the CSRF token.
In the end, he got a 4 KB worm, which he injected into his profile page.
@@ -1008,24 +1014,41 @@ config.action_dispatch.default_headers.clear
Here is a list of common headers:
-* X-Frame-Options
-_'SAMEORIGIN' in Rails by default_ - allow framing on same domain. Set it to 'DENY' to deny framing at all or 'ALLOWALL' if you want to allow framing for all website.
-* X-XSS-Protection
-_'1; mode=block' in Rails by default_ - use XSS Auditor and block page if XSS attack is detected. Set it to '0;' if you want to switch XSS Auditor off(useful if response contents scripts from request parameters)
-* X-Content-Type-Options
-_'nosniff' in Rails by default_ - stops the browser from guessing the MIME type of a file.
-* X-Content-Security-Policy
-[A powerful mechanism for controlling which sites certain content types can be loaded from](http://w3c.github.io/webappsec/specs/content-security-policy/csp-specification.dev.html)
-* Access-Control-Allow-Origin
-Used to control which sites are allowed to bypass same origin policies and send cross-origin requests.
-* Strict-Transport-Security
-[Used to control if the browser is allowed to only access a site over a secure connection](http://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security)
+* **X-Frame-Options:** _'SAMEORIGIN' in Rails by default_ - allow framing on same domain. Set it to 'DENY' to deny framing at all or 'ALLOWALL' if you want to allow framing for all website.
+* **X-XSS-Protection:** _'1; mode=block' in Rails by default_ - use XSS Auditor and block page if XSS attack is detected. Set it to '0;' if you want to switch XSS Auditor off(useful if response contents scripts from request parameters)
+* **X-Content-Type-Options:** _'nosniff' in Rails by default_ - stops the browser from guessing the MIME type of a file.
+* **X-Content-Security-Policy:** [A powerful mechanism for controlling which sites certain content types can be loaded from](http://w3c.github.io/webappsec/specs/content-security-policy/csp-specification.dev.html)
+* **Access-Control-Allow-Origin:** Used to control which sites are allowed to bypass same origin policies and send cross-origin requests.
+* **Strict-Transport-Security:** [Used to control if the browser is allowed to only access a site over a secure connection](http://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security)
Environmental Security
----------------------
It is beyond the scope of this guide to inform you on how to secure your application code and environments. However, please secure your database configuration, e.g. `config/database.yml`, and your server-side secret, e.g. stored in `config/secrets.yml`. You may want to further restrict access, using environment-specific versions of these files and any others that may contain sensitive information.
+### Custom secrets
+
+Rails generates a `config/secrets.yml`. By default, this file contains the
+application's `secret_key_base`, but it could also be used to store other
+secrets such as access keys for external APIs.
+
+The secrets added to this file are accessible via `Rails.application.secrets`.
+For example, with the following `config/secrets.yml`:
+
+ development:
+ secret_key_base: 3b7cd727ee24e8444053437c36cc66c3
+ some_api_key: SOMEKEY
+
+`Rails.application.secrets.some_api_key` returns `SOMEKEY` in the development
+environment.
+
+If you want an exception to be raised when some key is blank, use the bang
+version:
+
+```ruby
+Rails.application.secrets.some_api_key! # => raises KeyError
+```
+
Additional Resources
--------------------
@@ -1034,4 +1057,3 @@ The security landscape shifts and it is important to keep up to date, because mi
* Subscribe to the Rails security [mailing list](http://groups.google.com/group/rubyonrails-security)
* [Keep up to date on the other application layers](http://secunia.com/) (they have a weekly newsletter, too)
* A [good security blog](https://www.owasp.org) including the [Cross-Site scripting Cheat Sheet](https://www.owasp.org/index.php/DOM_based_XSS_Prevention_Cheat_Sheet)
-
diff --git a/guides/source/testing.md b/guides/source/testing.md
index 2fd54a48fc..435de30acc 100644
--- a/guides/source/testing.md
+++ b/guides/source/testing.md
@@ -25,15 +25,7 @@ Rails tests can also simulate browser requests and thus you can test your applic
Introduction to Testing
-----------------------
-Testing support was woven into the Rails fabric from the beginning. It wasn't an "oh! let's bolt on support for running tests because they're new and cool" epiphany. Just about every Rails application interacts heavily with a database and, as a result, your tests will need a database to interact with as well. To write efficient tests, you'll need to understand how to set up this database and populate it with sample data.
-
-### The Test Environment
-
-By default, every Rails application has three environments: development, test, and production. The database for each one of them is configured in `config/database.yml`.
-
-A dedicated test database allows you to set up and interact with test data in isolation. This way your tests can mangle test data with confidence, without worrying about the data in the development or production databases.
-
-Also, each environment's configuration can be modified similarly. In this case, we can modify our test environment by changing the options found in `config/environments/test.rb`.
+Testing support was woven into the Rails fabric from the beginning. It wasn't an "oh! let's bolt on support for running tests because they're new and cool" epiphany.
### Rails Sets up for Testing from the Word Go
@@ -51,123 +43,18 @@ Fixtures are a way of organizing test data; they reside in the `fixtures` direct
The `test_helper.rb` file holds the default configuration for your tests.
-### The Low-Down on Fixtures
-
-For good tests, you'll need to give some thought to setting up test data.
-In Rails, you can handle this by defining and customizing fixtures.
-You can find comprehensive documentation in the [Fixtures API documentation](http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html).
-
-#### What Are Fixtures?
-
-_Fixtures_ is a fancy word for sample data. Fixtures allow you to populate your testing database with predefined data before your tests run. Fixtures are database independent and written in YAML. There is one file per model.
-
-You'll find fixtures under your `test/fixtures` directory. When you run `rails generate model` to create a new model, Rails automatically creates fixture stubs in this directory.
-#### YAML
-
-YAML-formatted fixtures are a human-friendly way to describe your sample data. These types of fixtures have the **.yml** file extension (as in `users.yml`).
-
-Here's a sample YAML fixture file:
-
-```yaml
-# lo & behold! I am a YAML comment!
-david:
- name: David Heinemeier Hansson
- birthday: 1979-10-15
- profession: Systems development
-
-steve:
- name: Steve Ross Kellock
- birthday: 1974-09-27
- profession: guy with keyboard
-```
-
-Each fixture is given a name followed by an indented list of colon-separated key/value pairs. Records are typically separated by a blank line. You can place comments in a fixture file by using the # character in the first column.
-
-If you are working with [associations](/association_basics.html), you can simply
-define a reference node between two different fixtures. Here's an example with
-a `belongs_to`/`has_many` association:
-
-```yaml
-# In fixtures/categories.yml
-about:
- name: About
-
-# In fixtures/articles.yml
-one:
- title: Welcome to Rails!
- body: Hello world!
- category: about
-```
-
-Notice the `category` key of the `one` article found in `fixtures/articles.yml` has a value of `about`. This tells Rails to load the category `about` found in `fixtures/categories.yml`.
-
-NOTE: For associations to reference one another by name, you cannot specify the `id:` attribute on the associated fixtures. Rails will auto assign a primary key to be consistent between runs. For more information on this association behavior please read the [Fixtures API documentation](http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html).
-
-#### ERB'in It Up
-
-ERB allows you to embed Ruby code within templates. The YAML fixture format is pre-processed with ERB when Rails loads fixtures. This allows you to use Ruby to help you generate some sample data. For example, the following code generates a thousand users:
-
-```erb
-<% 1000.times do |n| %>
-user_<%= n %>:
- username: <%= "user#{n}" %>
- email: <%= "user#{n}@example.com" %>
-<% end %>
-```
-
-#### Fixtures in Action
-
-Rails by default automatically loads all fixtures from the `test/fixtures` directory for your models and controllers test. Loading involves three steps:
-
-1. Remove any existing data from the table corresponding to the fixture
-2. Load the fixture data into the table
-3. Dump the fixture data into a method in case you want to access it directly
-
-TIP: In order to remove existing data from the database, Rails tries to disable referential integrity triggers (like foreign keys and check constraints). If you are getting annoying permission errors on running tests, make sure the database user has privilege to disable these triggers in testing environment. (In PostgreSQL, only superusers can disable all triggers. Read more about PostgreSQL permissions [here](http://blog.endpoint.com/2012/10/postgres-system-triggers-error.html))
-
-#### Fixtures are Active Record objects
-
-Fixtures are instances of Active Record. As mentioned in point #3 above, you can access the object directly because it is automatically available as a method whose scope is local of the test case. For example:
-
-```ruby
-# this will return the User object for the fixture named david
-users(:david)
-
-# this will return the property for david called id
-users(:david).id
-
-# one can also access methods available on the User class
-email(david.partner.email, david.location_tonight)
-```
-
-To get multiple fixtures at once, you can pass in a list of fixture names. For example:
-
-```ruby
-# this will return an array containing the fixtures david and steve
-users(:david, :steve)
-```
-
-### Console Tasks for Running your Tests
-
-Rails comes with a CLI command to run tests.
-Here are some examples of how to use it:
+### The Test Environment
-```bash
-$ bin/rails test # run all tests in the `test` directory
-$ bin/rails test test/controllers # run all tests from specific directory
-$ bin/rails test test/models/post_test.rb # run specific test
-$ bin/rails test test/models/post_test.rb:44 # run specific test and line
-```
+By default, every Rails application has three environments: development, test, and production.
-We will cover each of types Rails tests listed above in this guide.
+Each environment's configuration can be modified similarly. In this case, we can modify our test environment by changing the options found in `config/environments/test.rb`.
-Model Testing
-------------------------
+NOTE: Your tests are run under `RAILS_ENV=test`.
-For this guide we will be using the application we built in the [Getting Started with Rails](getting_started.html) guide.
+### Rails meets Minitest
-If you remember when you used the `rails generate scaffold` command from earlier. We created our first resource among other things it created a test stub in the `test/models` directory:
+If you remember when you used the `rails generate scaffold` command from the [Getting Started with Rails](getting_started.html) guide. We created our first resource among other things it created test stubs in the `test` directory:
```bash
$ bin/rails generate scaffold article title:string body:text
@@ -242,47 +129,6 @@ An assertion is a line of code that evaluates an object (or expression) for expe
Every test must contain at least one assertion, with no restriction as to how many assertions are allowed. Only when all the assertions are successful will the test pass.
-### Maintaining the test database schema
-
-In order to run your tests, your test database will need to have the current
-structure. The test helper checks whether your test database has any pending
-migrations. If so, it will try to load your `db/schema.rb` or `db/structure.sql`
-into the test database. If migrations are still pending, an error will be
-raised. Usually this indicates that your schema is not fully migrated. Running
-the migrations against the development database (`bin/rake db:migrate`) will
-bring the schema up to date.
-
-NOTE: If existing migrations required modifications, the test database needs to
-be rebuilt. This can be done by executing `bin/rake db:test:prepare`.
-
-### Running Tests
-
-Running a test is as simple as invoking the file containing the test cases through `rails test` command.
-
-```bash
-$ bin/rails test test/models/article_test.rb
-.
-
-Finished tests in 0.009262s, 107.9680 tests/s, 107.9680 assertions/s.
-
-1 tests, 1 assertions, 0 failures, 0 errors, 0 skips
-```
-
-This will run all test methods from the test case.
-
-You can also run a particular test method from the test case by running the test and providing the `test method name`.
-
-```bash
-$ bin/rails test test/models/article_test.rb test_the_truth
-.
-
-Finished tests in 0.009064s, 110.3266 tests/s, 110.3266 assertions/s.
-
-1 tests, 1 assertions, 0 failures, 0 errors, 0 skips
-```
-
-The `.` (dot) above indicates a passing test. When a test fails you see an `F`; when a test throws an error you see an `E` in its place. The last line of the output is the summary.
-
#### Your first failing test
To see how a test failure is reported, you can add a failing test to the `article_test.rb` test case.
@@ -435,8 +281,8 @@ specify to make your test failure messages clearer. It's not required.
| `assert_no_match( regexp, string, [msg] )` | Ensures that a string doesn't match the regular expression.|
| `assert_includes( collection, obj, [msg] )` | Ensures that `obj` is in `collection`.|
| `assert_not_includes( collection, obj, [msg] )` | Ensures that `obj` is not in `collection`.|
-| `assert_in_delta( expecting, actual, [delta], [msg] )` | Ensures that the numbers `expected` and `actual` are within `delta` of each other.|
-| `assert_not_in_delta( expecting, actual, [delta], [msg] )` | Ensures that the numbers `expected` and `actual` are not within `delta` of each other.|
+| `assert_in_delta( expected, actual, [delta], [msg] )` | Ensures that the numbers `expected` and `actual` are within `delta` of each other.|
+| `assert_not_in_delta( expected, actual, [delta], [msg] )` | Ensures that the numbers `expected` and `actual` are not within `delta` of each other.|
| `assert_throws( symbol, [msg] ) { block }` | Ensures that the given block throws the symbol.|
| `assert_raises( exception1, exception2, ... ) { block }` | Ensures that the given block raises one of the given exceptions.|
| `assert_nothing_raised( exception1, exception2, ... ) { block }` | Ensures that the given block doesn't raise one of the given exceptions.|
@@ -456,7 +302,7 @@ specify to make your test failure messages clearer. It's not required.
The above are a subset of assertions that minitest supports. For an exhaustive &
more up-to-date list, please check
[Minitest API documentation](http://docs.seattlerb.org/minitest/), specifically
-[`Minitest::Assertions`](http://docs.seattlerb.org/minitest/Minitest/Assertions.html)
+[`Minitest::Assertions`](http://docs.seattlerb.org/minitest/Minitest/Assertions.html).
Because of the modular nature of the testing framework, it is possible to create your own assertions. In fact, that's exactly what Rails does. It includes some specialized assertions to make your life easier.
@@ -477,7 +323,7 @@ Rails adds some custom assertions of its own to the `minitest` framework:
You'll see the usage of some of these assertions in the next chapter.
-### A Brief Note About Minitest
+### A Brief Note About Test Cases
All the basic assertions such as `assert_equal` defined in `Minitest::Assertions` are also available in the classes we use in our own test cases. In fact, Rails provides the following classes for you to inherit from:
@@ -490,7 +336,303 @@ All the basic assertions such as `assert_equal` defined in `Minitest::Assertions
Each of these classes include `Minitest::Assertions`, allowing us to use all of the basic assertions in our tests.
-NOTE: For more information on `Minitest`, refer to [Minitest](http://docs.seattlerb.org/minitest)
+NOTE: For more information on `Minitest`, refer to [its
+documentation](http://docs.seattlerb.org/minitest).
+
+### The Rails Test Runner
+
+We can run all of our tests at once by using the `rails test` command.
+
+Or we can run a single test by passing the `rails test` command the filename containing the test cases.
+
+```bash
+$ bin/rails test test/models/article_test.rb
+.
+
+Finished tests in 0.009262s, 107.9680 tests/s, 107.9680 assertions/s.
+
+1 tests, 1 assertions, 0 failures, 0 errors, 0 skips
+```
+
+This will run all test methods from the test case.
+
+You can also run a particular test method from the test case by providing the
+`-n` or `--name` flag and the test's method name.
+
+```bash
+$ bin/rails test test/models/article_test.rb -n test_the_truth
+.
+
+Finished tests in 0.009064s, 110.3266 tests/s, 110.3266 assertions/s.
+
+1 tests, 1 assertions, 0 failures, 0 errors, 0 skips
+```
+
+You can also run a test at a specific line by providing the line number.
+
+```bash
+$ bin/rails test test/models/post_test.rb:44 # run specific test and line
+```
+
+You can also run an entire directory of tests by providing the path to the directory.
+
+```bash
+$ bin/rails test test/controllers # run all tests from specific directory
+```
+
+
+The Test Database
+-----------------
+
+Just about every Rails application interacts heavily with a database and, as a result, your tests will need a database to interact with as well. To write efficient tests, you'll need to understand how to set up this database and populate it with sample data.
+
+By default, every Rails application has three environments: development, test, and production. The database for each one of them is configured in `config/database.yml`.
+
+A dedicated test database allows you to set up and interact with test data in isolation. This way your tests can mangle test data with confidence, without worrying about the data in the development or production databases.
+
+
+### Maintaining the test database schema
+
+In order to run your tests, your test database will need to have the current
+structure. The test helper checks whether your test database has any pending
+migrations. If so, it will try to load your `db/schema.rb` or `db/structure.sql`
+into the test database. If migrations are still pending, an error will be
+raised. Usually this indicates that your schema is not fully migrated. Running
+the migrations against the development database (`bin/rake db:migrate`) will
+bring the schema up to date.
+
+NOTE: If existing migrations required modifications, the test database needs to
+be rebuilt. This can be done by executing `bin/rake db:test:prepare`.
+
+### The Low-Down on Fixtures
+
+For good tests, you'll need to give some thought to setting up test data.
+In Rails, you can handle this by defining and customizing fixtures.
+You can find comprehensive documentation in the [Fixtures API documentation](http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html).
+
+#### What Are Fixtures?
+
+_Fixtures_ is a fancy word for sample data. Fixtures allow you to populate your testing database with predefined data before your tests run. Fixtures are database independent and written in YAML. There is one file per model.
+
+You'll find fixtures under your `test/fixtures` directory. When you run `rails generate model` to create a new model, Rails automatically creates fixture stubs in this directory.
+
+#### YAML
+
+YAML-formatted fixtures are a human-friendly way to describe your sample data. These types of fixtures have the **.yml** file extension (as in `users.yml`).
+
+Here's a sample YAML fixture file:
+
+```yaml
+# lo & behold! I am a YAML comment!
+david:
+ name: David Heinemeier Hansson
+ birthday: 1979-10-15
+ profession: Systems development
+
+steve:
+ name: Steve Ross Kellock
+ birthday: 1974-09-27
+ profession: guy with keyboard
+```
+
+Each fixture is given a name followed by an indented list of colon-separated key/value pairs. Records are typically separated by a blank line. You can place comments in a fixture file by using the # character in the first column.
+
+If you are working with [associations](/association_basics.html), you can simply
+define a reference node between two different fixtures. Here's an example with
+a `belongs_to`/`has_many` association:
+
+```yaml
+# In fixtures/categories.yml
+about:
+ name: About
+
+# In fixtures/articles.yml
+one:
+ title: Welcome to Rails!
+ body: Hello world!
+ category: about
+```
+
+Notice the `category` key of the `one` article found in `fixtures/articles.yml` has a value of `about`. This tells Rails to load the category `about` found in `fixtures/categories.yml`.
+
+NOTE: For associations to reference one another by name, you cannot specify the `id:` attribute on the associated fixtures. Rails will auto assign a primary key to be consistent between runs. For more information on this association behavior please read the [Fixtures API documentation](http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html).
+
+#### ERB'in It Up
+
+ERB allows you to embed Ruby code within templates. The YAML fixture format is pre-processed with ERB when Rails loads fixtures. This allows you to use Ruby to help you generate some sample data. For example, the following code generates a thousand users:
+
+```erb
+<% 1000.times do |n| %>
+user_<%= n %>:
+ username: <%= "user#{n}" %>
+ email: <%= "user#{n}@example.com" %>
+<% end %>
+```
+
+#### Fixtures in Action
+
+Rails automatically loads all fixtures from the `test/fixtures` directory by
+default. Loading involves three steps:
+
+1. Remove any existing data from the table corresponding to the fixture
+2. Load the fixture data into the table
+3. Dump the fixture data into a method in case you want to access it directly
+
+TIP: In order to remove existing data from the database, Rails tries to disable referential integrity triggers (like foreign keys and check constraints). If you are getting annoying permission errors on running tests, make sure the database user has privilege to disable these triggers in testing environment. (In PostgreSQL, only superusers can disable all triggers. Read more about PostgreSQL permissions [here](http://blog.endpoint.com/2012/10/postgres-system-triggers-error.html)).
+
+#### Fixtures are Active Record objects
+
+Fixtures are instances of Active Record. As mentioned in point #3 above, you can access the object directly because it is automatically available as a method whose scope is local of the test case. For example:
+
+```ruby
+# this will return the User object for the fixture named david
+users(:david)
+
+# this will return the property for david called id
+users(:david).id
+
+# one can also access methods available on the User class
+email(david.partner.email, david.location_tonight)
+```
+
+To get multiple fixtures at once, you can pass in a list of fixture names. For example:
+
+```ruby
+# this will return an array containing the fixtures david and steve
+users(:david, :steve)
+```
+
+
+Model Testing
+-------------
+
+Model tests are used to test the various models of your application.
+
+Rails model tests are stored under the `test/models` directory. Rails provides
+a generator to create a model test skeleton for you.
+
+```bash
+$ bin/rails generate test_unit:model article title:string body:text
+create test/models/article_test.rb
+create test/fixtures/articles.yml
+```
+
+Model tests don't have their own superclass like `ActionMailer::TestCase` instead they inherit from `ActiveSupport::TestCase`.
+
+
+Integration Testing
+-------------------
+
+Integration tests are used to test how various parts of your application interact. They are generally used to test important work flows within your application.
+
+For creating Rails integration tests, we use the 'test/integration' directory for your application. Rails provides a generator to create an integration test skeleton for you.
+
+```bash
+$ bin/rails generate integration_test user_flows
+ exists test/integration/
+ create test/integration/user_flows_test.rb
+```
+
+Here's what a freshly-generated integration test looks like:
+
+```ruby
+require 'test_helper'
+
+class UserFlowsTest < ActionDispatch::IntegrationTest
+ # test "the truth" do
+ # assert true
+ # end
+end
+```
+
+Inheriting from `ActionDispatch::IntegrationTest` comes with some advantages. This makes available some additional helpers to use in your integration tests.
+
+### Helpers Available for Integration Tests
+
+In addition to the standard testing helpers, inheriting `ActionDispatch::IntegrationTest` comes with some additional helpers available when writing integration tests. Let's briefly introduce you to the three categories of helpers you get to choose from.
+
+For dealing with the integration test runner, see [`ActionDispatch::Integration::Runner`](http://api.rubyonrails.org/classes/ActionDispatch/Integration/Runner.html).
+
+When performing requests, you will have [`ActionDispatch::Integration::RequestHelpers`](http://api.rubyonrails.org/classes/ActionDispatch/Integration/RequestHelpers.html) available for your use.
+
+If you'd like to modify the session, or state of your integration test you should look for [`ActionDispatch::Integration::Session`](http://api.rubyonrails.org/classes/ActionDispatch/Integration/Session.html) to help.
+
+### Implementing an integration test
+
+Let's add an integration test to our blog application. We'll start with a basic workflow of creating a new blog article, to verify that everything is working properly.
+
+We'll start by generating our integration test skeleton:
+
+```bash
+$ bin/rails generate integration_test blog_flow
+```
+
+It should have created a test file placeholder for us. With the output of the
+previous command you should see:
+
+```bash
+ invoke test_unit
+ create test/integration/blog_flow_test.rb
+```
+
+Now let's open that file and write our first assertion:
+
+```ruby
+require 'test_helper'
+
+class BlogFlowTest < ActionDispatch::IntegrationTest
+ test "can see the welcome page" do
+ get "/"
+ assert_select "h1", "Welcome#index"
+ end
+end
+```
+
+If you remember from earlier in the "Testing Views" section we covered `assert_select` to query the resulting HTML of a request.
+
+When visit our root path, we should see `welcome/index.html.erb` rendered for the view. So this assertion should pass.
+
+#### Creating articles integration
+
+How about testing our ability to create a new article in our blog and see the resulting article.
+
+```ruby
+test "can create an article" do
+ get "/articles/new"
+ assert_response :success
+
+ post "/articles",
+ params: { article: { title: "can create", body: "article successfully." } }
+ assert_response :redirect
+ follow_redirect!
+ assert_response :success
+ assert_select "p", "Title:\n can create"
+end
+```
+
+Let's break this test down so we can understand it.
+
+We start by calling the `:new` action on our Articles controller. This response should be successful.
+
+After this we make a post request to the `:create` action of our Articles controller:
+
+```ruby
+post "/articles",
+ params: { article: { title: "can create", body: "article successfully." } }
+assert_response :redirect
+follow_redirect!
+```
+
+The two lines following the request are to handle the redirect we setup when creating a new article.
+
+NOTE: Don't forget to call `follow_redirect!` if you plan to make subsequent requests after a redirect is made.
+
+Finally we can assert that our response was successful and our new article is readable on the page.
+
+#### Taking it further
+
+We were able to successfully test a very small workflow for visiting our blog and creating a new article. If we wanted to take this further we could add tests for commenting, removing articles, or editing comments. Integration tests are a great place to experiment with all kinds of use-cases for our applications.
+
Functional Tests for Your Controllers
-------------------------------------
@@ -509,6 +651,14 @@ You should test for things such as:
Now that we have used Rails scaffold generator for our `Article` resource, it has already created the controller code and tests. You can take look at the file `articles_controller_test.rb` in the `test/controllers` directory.
+The following command will generate a controller test case with a filled up
+test for each of the seven default actions.
+
+```bash
+$ bin/rails generate test_unit:scaffold article
+create test/controllers/articles_controller_test.rb
+```
+
Let me take you through one such test, `test_should_get_index` from the file `articles_controller_test.rb`.
```ruby
@@ -596,13 +746,13 @@ test "ajax request" do
end
```
-### The Four Hashes of the Apocalypse
+### The Three Hashes of the Apocalypse
-After a request has been made and processed, you will have 4 Hash objects ready for use:
+After a request has been made and processed, you will have 3 Hash objects ready for use:
-* `cookies` - Any cookies that are set.
-* `flash` - Any objects living in the flash.
-* `session` - Any object living in session variables.
+* `cookies` - Any cookies that are set
+* `flash` - Any objects living in the flash
+* `session` - Any object living in session variables
As is the case with normal Hash objects, you can access the values by referencing the keys by string. You can also reference them by symbol name. For example:
@@ -639,7 +789,7 @@ post :create # simulate the request with custom env variable
### Testing `flash` notices
-If you remember from earlier one of the Four Hashes of the Apocalypse was `flash`.
+If you remember from earlier one of the Three Hashes of the Apocalypse was `flash`.
We want to add a `flash` message to our blog application whenever someone
successfully creates a new Article.
@@ -828,33 +978,7 @@ end
Testing Routes
--------------
-Like everything else in your Rails application, it is recommended that you test your routes. Below are example tests for the routes of default `show` and `create` action of `Articles` controller above and it should look like:
-
-```ruby
-class ArticleRoutesTest < ActionController::TestCase
- test "should route to article" do
- assert_routing '/articles/1', { controller: "articles", action: "show", id: "1" }
- end
-
- test "should route to create article" do
- assert_routing({ method: 'post', path: '/articles' }, { controller: "articles", action: "create" })
- end
-end
-```
-
-I've added this file here `test/controllers/articles_routes_test.rb` and if we run the test we should see:
-
-```bash
-$ bin/rails test test/controllers/articles_routes_test.rb
-
-# Running:
-
-..
-
-Finished in 0.069381s, 28.8263 runs/s, 86.4790 assertions/s.
-
-2 runs, 6 assertions, 0 failures, 0 errors, 0 skips
-```
+Like everything else in your Rails application, you can test your routes.
For more information on routing assertions available in Rails, see the API documentation for [`ActionDispatch::Assertions::RoutingAssertions`](http://api.rubyonrails.org/classes/ActionDispatch/Assertions/RoutingAssertions.html).
@@ -944,8 +1068,6 @@ have to use a mixin like this:
```ruby
class UserHelperTest < ActionView::TestCase
- include UserHelper
-
test "should return the user name" do
# ...
end
@@ -955,118 +1077,6 @@ end
Moreover, since the test class extends from `ActionView::TestCase`, you have
access to Rails' helper methods such as `link_to` or `pluralize`.
-Integration Testing
--------------------
-
-Integration tests are used to test how various parts of your application interact. They are generally used to test important work flows within your application.
-
-For creating Rails integration tests, we use the 'test/integration' directory for your application. Rails provides a generator to create an integration test skeleton for you.
-
-```bash
-$ bin/rails generate integration_test user_flows
- exists test/integration/
- create test/integration/user_flows_test.rb
-```
-
-Here's what a freshly-generated integration test looks like:
-
-```ruby
-require 'test_helper'
-
-class UserFlowsTest < ActionDispatch::IntegrationTest
- # test "the truth" do
- # assert true
- # end
-end
-```
-
-Inheriting from `ActionDispatch::IntegrationTest` comes with some advantages. This makes available some additional helpers to use in your integration tests.
-
-### Helpers Available for Integration Tests
-
-In addition to the standard testing helpers, inheriting `ActionDispatch::IntegrationTest` comes with some additional helpers available when writing integration tests. Let's briefly introduce you to the three categories of helpers you get to choose from.
-
-For dealing with the integration test runner, see [`ActionDispatch::Integration::Runner`](http://api.rubyonrails.org/classes/ActionDispatch/Integration/Runner.html).
-
-When performing requests, you will have [`ActionDispatch::Integration::RequestHelpers`](http://api.rubyonrails.org/classes/ActionDispatch/Integration/RequestHelpers.html) available for your use.
-
-If you'd like to modify the session, or state of your integration test you should look for [`ActionDispatch::Integration::Session`](http://api.rubyonrails.org/classes/ActionDispatch/Integration/Session.html) to help.
-
-### Implementing an integration test
-
-Let's add an integration test to our blog application. We'll start with a basic workflow of creating a new blog article, to verify that everything is working properly.
-
-We'll start by generating our integration test skeleton:
-
-```bash
-$ bin/rails generate integration_test blog_flow
-```
-
-It should have created a test file placeholder for us, with the output of the previous command you should see:
-
-```bash
- invoke test_unit
- create test/integration/blog_flow_test.rb
-```
-
-Now let's open that file and write our first assertion:
-
-```ruby
-require 'test_helper'
-
-class BlogFlowTest < ActionDispatch::IntegrationTest
- test "can see the welcome page" do
- get "/"
- assert_select "h1", "Welcome#index"
- end
-end
-```
-
-If you remember from earlier in the "Testing Views" section we covered `assert_select` to query the resulting HTML of a request.
-
-When visit our root path, we should see `welcome/index.html.erb` rendered for the view. So this assertion should pass.
-
-#### Creating articles integration
-
-How about testing our ability to create a new article in our blog and see the resulting article.
-
-```ruby
-test "can create an article" do
- get "/articles/new"
- assert_response :success
-
- post "/articles",
- params: { article: { title: "can create", body: "article successfully." } }
- assert_response :redirect
- follow_redirect!
- assert_response :success
- assert_select "p", "Title:\n can create"
-end
-```
-
-Let's break this test down so we can understand it.
-
-We start by calling the `:new` action on our Articles controller. This response should be successful, and we can verify the correct template is rendered including the form partial.
-
-After this we make a post request to the `:create` action of our Articles controller:
-
-```ruby
-post "/articles",
- params: { article: { title: "can create", body: "article successfully." } }
-assert_response :redirect
-follow_redirect!
-```
-
-The two lines following the request are to handle the redirect we setup when creating a new article.
-
-NOTE: Don't forget to call `follow_redirect!` if you plan to make subsequent requests after a redirect is made.
-
-Finally we can assert that our response was successful, template was rendered, and our new article is readable on the page.
-
-#### Taking it further
-
-We were able to successfully test a very small workflow for visiting our blog and creating a new article. If we wanted to take this further we could add tests for commenting, removing articles, or editting comments. Integration tests are a great place to experiment with all kinds of use-cases for our applications.
-
Testing Your Mailers
--------------------
@@ -1105,10 +1115,13 @@ require 'test_helper'
class UserMailerTest < ActionMailer::TestCase
test "invite" do
+ # Create the email and store it for further assertions
+ email = UserMailer.create_invite('me@example.com',
+ 'friend@example.com', Time.now)
+
# Send the email, then test that it got queued
assert_emails 1 do
- email = UserMailer.create_invite('me@example.com',
- 'friend@example.com', Time.now).deliver_now
+ email.deliver_now
end
# Test the body of the sent email contains what we expect it to
@@ -1219,16 +1232,3 @@ class ProductTest < ActiveJob::TestCase
end
end
```
-
-Other Testing Approaches
-------------------------
-
-The built-in `minitest` based testing is not the only way to test Rails applications. Rails developers have come up with a wide variety of other approaches and aids for testing, including:
-
-* [NullDB](http://avdi.org/projects/nulldb/), a way to speed up testing by avoiding database use.
-* [Factory Girl](https://github.com/thoughtbot/factory_girl/tree/master), a replacement for fixtures.
-* [Fixture Builder](https://github.com/rdy/fixture_builder), a tool that compiles Ruby factories into fixtures before a test run.
-* [MiniTest::Spec Rails](https://github.com/metaskills/minitest-spec-rails), use the MiniTest::Spec DSL within your rails tests.
-* [Shoulda](http://www.thoughtbot.com/projects/shoulda), an extension to `test/unit` with additional helpers, macros, and assertions.
-* [RSpec](http://relishapp.com/rspec), a behavior-driven development framework
-* [Capybara](http://jnicklas.github.com/capybara/), Acceptance test framework for web applications
diff --git a/guides/source/upgrading_ruby_on_rails.md b/guides/source/upgrading_ruby_on_rails.md
index 17309d4b47..490bda3571 100644
--- a/guides/source/upgrading_ruby_on_rails.md
+++ b/guides/source/upgrading_ruby_on_rails.md
@@ -55,27 +55,30 @@ Upgrading from Rails 4.2 to Rails 5.0
### Halting callback chains by returning `false`
-In Rails 4.2, when a 'before' callback returns `false` in ActiveRecord,
-ActiveModel and ActiveModel::Validations, then the entire callback chain
-is halted. In other words, successive 'before' callbacks are not executed,
-and neither is the action wrapped in callbacks.
+In Rails 4.2, when a 'before' callback returns `false` in Active Record
+and Active Model, then the entire callback chain is halted. In other words,
+successive 'before' callbacks are not executed, and neither is the action wrapped
+in callbacks.
-In Rails 5.0, returning `false` in a callback will not have this side effect
-of halting the callback chain. Instead, callback chains must be explicitly
-halted by calling `throw(:abort)`.
+In Rails 5.0, returning `false` in an Active Record or Active Model callback
+will not have this side effect of halting the callback chain. Instead, callback
+chains must be explicitly halted by calling `throw(:abort)`.
-When you upgrade from Rails 4.2 to Rails 5.0, returning `false` in a callback
-will still halt the callback chain, but you will receive a deprecation warning
-about this upcoming change.
+When you upgrade from Rails 4.2 to Rails 5.0, returning `false` in those kind of
+callbacks will still halt the callback chain, but you will receive a deprecation
+warning about this upcoming change.
When you are ready, you can opt into the new behavior and remove the deprecation
warning by adding the following configuration to your `config/application.rb`:
- config.active_support.halt_callback_chains_on_return_false = false
+ ActiveSupport.halt_callback_chains_on_return_false = false
+
+Note that this option will not affect Active Support callbacks since they never
+halted the chain when any value was returned.
See [#17227](https://github.com/rails/rails/pull/17227) for more details.
-### ActiveJob jobs now inherent from ApplicationJob by default
+### ActiveJob jobs now inherit from ApplicationJob by default
In Rails 4.2 an ActiveJob inherits from `ActiveJob::Base`. In Rails 5.0 this
behavior has changed to now inherit from `ApplicationJob`.
@@ -314,11 +317,11 @@ Upgrading from Rails 4.0 to Rails 4.1
### CSRF protection from remote `<script>` tags
-Or, "whaaat my tests are failing!!!?"
+Or, "whaaat my tests are failing!!!?" or "my `<script>` widget is busted!!"
Cross-site request forgery (CSRF) protection now covers GET requests with
-JavaScript responses, too. This prevents a third-party site from referencing
-your JavaScript URL and attempting to run it to extract sensitive data.
+JavaScript responses, too. This prevents a third-party site from remotely
+referencing your JavaScript with a `<script>` tag to extract sensitive data.
This means that your functional and integration tests that use
@@ -334,8 +337,9 @@ xhr :get, :index, format: :js
to explicitly test an `XmlHttpRequest`.
-If you really mean to load JavaScript from remote `<script>` tags, skip CSRF
-protection on that action.
+Note: Your own `<script>` tags are treated as cross-origin and blocked by
+default, too. If you really mean to load JavaScript from `<script>` tags,
+you must now explicitly skip CSRF protection on those actions.
### Spring
@@ -895,7 +899,7 @@ CatalogProduct < ActiveRecord::Base
end
```
-* Note that the the prefix takes scopes into account as well, so relations between `Catalog::Category` and `Catalog::Product` or `Catalog::Category` and `CatalogProduct` need to be updated similarly.
+* Note that the prefix takes scopes into account as well, so relations between `Catalog::Category` and `Catalog::Product` or `Catalog::Category` and `CatalogProduct` need to be updated similarly.
### Active Resource
diff --git a/guides/source/working_with_javascript_in_rails.md b/guides/source/working_with_javascript_in_rails.md
index f3d3a83afc..1c42ff2914 100644
--- a/guides/source/working_with_javascript_in_rails.md
+++ b/guides/source/working_with_javascript_in_rails.md
@@ -258,7 +258,7 @@ this generates
```html
<form action="/articles/1" class="button_to" data-remote="true" method="post">
- <div><input type="submit" value="An article"></div>
+ <input type="submit" value="An article" />
</form>
```
@@ -357,7 +357,7 @@ This gem uses Ajax to speed up page rendering in most applications.
Turbolinks attaches a click handler to all `<a>` on the page. If your browser
supports
-[PushState](https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history#The_pushState()_method),
+[PushState](https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history#The_pushState%28%29_method),
Turbolinks will make an Ajax request for the page, parse the response, and
replace the entire `<body>` of the page with the `<body>` of the response. It
will then use PushState to change the URL to the correct one, preserving