aboutsummaryrefslogtreecommitdiffstats
path: root/guides
diff options
context:
space:
mode:
Diffstat (limited to 'guides')
-rw-r--r--guides/bug_report_templates/action_controller_gem.rb15
-rw-r--r--guides/bug_report_templates/action_controller_master.rb21
-rw-r--r--guides/bug_report_templates/active_record_gem.rb16
-rw-r--r--guides/bug_report_templates/active_record_master.rb22
-rw-r--r--guides/bug_report_templates/generic_gem.rb16
-rw-r--r--guides/bug_report_templates/generic_master.rb20
-rw-r--r--guides/source/3_0_release_notes.md2
-rw-r--r--guides/source/3_1_release_notes.md4
-rw-r--r--guides/source/3_2_release_notes.md2
-rw-r--r--guides/source/4_0_release_notes.md2
-rw-r--r--guides/source/action_controller_overview.md4
-rw-r--r--guides/source/action_mailer_basics.md6
-rw-r--r--guides/source/action_view_overview.md31
-rw-r--r--guides/source/active_job_basics.md34
-rw-r--r--guides/source/active_record_basics.md4
-rw-r--r--guides/source/active_record_migrations.md7
-rw-r--r--guides/source/active_record_postgresql.md54
-rw-r--r--guides/source/active_record_querying.md7
-rw-r--r--guides/source/active_record_validations.md28
-rw-r--r--guides/source/active_support_core_extensions.md30
-rw-r--r--guides/source/active_support_instrumentation.md14
-rw-r--r--guides/source/api_app.md408
-rw-r--r--guides/source/association_basics.md42
-rw-r--r--guides/source/command_line.md4
-rw-r--r--guides/source/configuring.md19
-rw-r--r--guides/source/contributing_to_ruby_on_rails.md13
-rw-r--r--guides/source/debugging_rails_applications.md11
-rw-r--r--guides/source/development_dependencies_install.md4
-rw-r--r--guides/source/documents.yaml10
-rw-r--r--guides/source/engines.md14
-rw-r--r--guides/source/form_helpers.md6
-rw-r--r--guides/source/getting_started.md8
-rw-r--r--guides/source/i18n.md15
-rw-r--r--guides/source/initialization.md13
-rw-r--r--guides/source/kindle/welcome.html.erb4
-rw-r--r--guides/source/layouts_and_rendering.md26
-rw-r--r--guides/source/nested_model_forms.md2
-rw-r--r--guides/source/rails_application_templates.md2
-rw-r--r--guides/source/rails_on_rack.md4
-rw-r--r--guides/source/routing.md7
-rw-r--r--guides/source/security.md11
-rw-r--r--guides/source/testing.md87
-rw-r--r--guides/source/upgrading_ruby_on_rails.md6
-rw-r--r--guides/source/working_with_javascript_in_rails.md28
44 files changed, 742 insertions, 341 deletions
diff --git a/guides/bug_report_templates/action_controller_gem.rb b/guides/bug_report_templates/action_controller_gem.rb
index 032e6bfe11..11561c55f9 100644
--- a/guides/bug_report_templates/action_controller_gem.rb
+++ b/guides/bug_report_templates/action_controller_gem.rb
@@ -1,7 +1,16 @@
-# Activate the gem you are reporting the issue against.
-gem 'rails', '4.2.0'
+begin
+ require 'bundler/inline'
+rescue LoadError => e
+ $stderr.puts 'Bundler version 1.10 or later is required. Please update your Bundler'
+ raise e
+end
+
+gemfile(true) do
+ source 'https://rubygems.org'
+ # Activate the gem you are reporting the issue against.
+ gem 'rails', '4.2.0'
+end
-require 'rails'
require 'rack/test'
require 'action_controller/railtie'
diff --git a/guides/bug_report_templates/action_controller_master.rb b/guides/bug_report_templates/action_controller_master.rb
index 9be8130884..66887398b9 100644
--- a/guides/bug_report_templates/action_controller_master.rb
+++ b/guides/bug_report_templates/action_controller_master.rb
@@ -1,17 +1,16 @@
-unless File.exist?('Gemfile')
- File.write('Gemfile', <<-GEMFILE)
- source 'https://rubygems.org'
- gem 'rails', github: 'rails/rails'
- gem 'arel', github: 'rails/arel'
- GEMFILE
-
- system 'bundle'
+begin
+ require 'bundler/inline'
+rescue LoadError => e
+ $stderr.puts 'Bundler version 1.10 or later is required. Please update your Bundler'
+ raise e
end
-require 'bundler'
-Bundler.setup(:default)
+gemfile(true) do
+ source 'https://rubygems.org'
+ gem 'rails', github: 'rails/rails'
+ gem 'arel', github: 'rails/arel'
+end
-require 'rails'
require 'action_controller/railtie'
class TestApp < Rails::Application
diff --git a/guides/bug_report_templates/active_record_gem.rb b/guides/bug_report_templates/active_record_gem.rb
index b295d9d21f..09d6e7b331 100644
--- a/guides/bug_report_templates/active_record_gem.rb
+++ b/guides/bug_report_templates/active_record_gem.rb
@@ -1,5 +1,17 @@
-# Activate the gem you are reporting the issue against.
-gem 'activerecord', '4.2.0'
+begin
+ require 'bundler/inline'
+rescue LoadError => e
+ $stderr.puts 'Bundler version 1.10 or later is required. Please update your Bundler'
+ raise e
+end
+
+gemfile(true) do
+ source 'https://rubygems.org'
+ # Activate the gem you are reporting the issue against.
+ gem 'activerecord', '4.2.0'
+ gem 'sqlite3'
+end
+
require 'active_record'
require 'minitest/autorun'
require 'logger'
diff --git a/guides/bug_report_templates/active_record_master.rb b/guides/bug_report_templates/active_record_master.rb
index 9557f0b7c5..270dbe7df7 100644
--- a/guides/bug_report_templates/active_record_master.rb
+++ b/guides/bug_report_templates/active_record_master.rb
@@ -1,16 +1,16 @@
-unless File.exist?('Gemfile')
- File.write('Gemfile', <<-GEMFILE)
- source 'https://rubygems.org'
- gem 'rails', github: 'rails/rails'
- gem 'arel', github: 'rails/arel'
- gem 'sqlite3'
- GEMFILE
-
- system 'bundle'
+begin
+ require 'bundler/inline'
+rescue LoadError => e
+ $stderr.puts 'Bundler version 1.10 or later is required. Please update your Bundler'
+ raise e
end
-require 'bundler'
-Bundler.setup(:default)
+gemfile(true) do
+ source 'https://rubygems.org'
+ gem 'rails', github: 'rails/rails'
+ gem 'arel', github: 'rails/arel'
+ gem 'sqlite3'
+end
require 'active_record'
require 'minitest/autorun'
diff --git a/guides/bug_report_templates/generic_gem.rb b/guides/bug_report_templates/generic_gem.rb
index 3e3f8593d4..a4fe51156d 100644
--- a/guides/bug_report_templates/generic_gem.rb
+++ b/guides/bug_report_templates/generic_gem.rb
@@ -1,6 +1,16 @@
-# Activate the gems you are reporting the issue against.
-gem 'activesupport', '4.2.0'
-require 'active_support'
+begin
+ require 'bundler/inline'
+rescue LoadError => e
+ $stderr.puts 'Bundler version 1.10 or later is required. Please update your Bundler'
+ raise e
+end
+
+gemfile(true) do
+ source 'https://rubygems.org'
+ # Activate the gem you are reporting the issue against.
+ gem 'activesupport', '4.2.0'
+end
+
require 'active_support/core_ext/object/blank'
require 'minitest/autorun'
diff --git a/guides/bug_report_templates/generic_master.rb b/guides/bug_report_templates/generic_master.rb
index d930482d4e..b6b4562751 100644
--- a/guides/bug_report_templates/generic_master.rb
+++ b/guides/bug_report_templates/generic_master.rb
@@ -1,15 +1,15 @@
-unless File.exist?('Gemfile')
- File.write('Gemfile', <<-GEMFILE)
- source 'https://rubygems.org'
- gem 'rails', github: 'rails/rails'
- gem 'arel', github: 'rails/arel'
- GEMFILE
-
- system 'bundle'
+begin
+ require 'bundler/inline'
+rescue LoadError => e
+ $stderr.puts 'Bundler version 1.10 or later is required. Please update your Bundler'
+ raise e
end
-require 'bundler'
-Bundler.setup(:default)
+gemfile(true) do
+ source 'https://rubygems.org'
+ gem 'rails', github: 'rails/rails'
+ gem 'arel', github: 'rails/arel'
+end
require 'active_support'
require 'active_support/core_ext/object/blank'
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 537aa5a371..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
@@ -199,7 +199,7 @@ Railties
* jQuery is the new default JavaScript library.
-* jQuery and Prototype are no longer vendored and is provided from now on by the jquery-rails and prototype-rails gems.
+* jQuery and Prototype are no longer vendored and is provided from now on by the `jquery-rails` and `prototype-rails` gems.
* The application generator accepts an option `-j` which can be an arbitrary string. If passed "foo", the gem "foo-rails" is added to the `Gemfile`, and the application JavaScript manifest requires "foo" and "foo_ujs". Currently only "prototype-rails" and "jquery-rails" exist and provide those files via the asset pipeline.
diff --git a/guides/source/3_2_release_notes.md b/guides/source/3_2_release_notes.md
index 6ddf77d9c0..c52c39b705 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
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/action_controller_overview.md b/guides/source/action_controller_overview.md
index 7d95d4792e..d506722f75 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
diff --git a/guides/source/action_mailer_basics.md b/guides/source/action_mailer_basics.md
index 089ce53f07..bf3bf5d19e 100644
--- a/guides/source/action_mailer_basics.md
+++ b/guides/source/action_mailer_basics.md
@@ -344,7 +344,7 @@ The same format can be used to set carbon copy (Cc:) and blind carbon copy
Sometimes you wish to show the name of the person instead of just their email
address when they receive the email. The trick to doing that is to format the
-email address in the format `"Full Name <email>"`.
+email address in the format `"Full Name" <email>`.
```ruby
def welcome_email(user)
@@ -503,7 +503,7 @@ You will need to use:
By using the full URL, your links will now work in your emails.
-#### generating URLs with `url_for`
+#### Generating URLs with `url_for`
`url_for` generate full URL by default in templates.
@@ -517,7 +517,7 @@ If you did not configure the `:host` option globally make sure to pass it to
action: 'greeting') %>
```
-#### generating URLs with named routes
+#### Generating URLs with Named Routes
Email clients have no web context and so paths have no base URL to form complete
web addresses. Thus, you should always use the "_url" variant of named route
diff --git a/guides/source/action_view_overview.md b/guides/source/action_view_overview.md
index 3541bbaa93..09fac41491 100644
--- a/guides/source/action_view_overview.md
+++ b/guides/source/action_view_overview.md
@@ -214,7 +214,8 @@ By default `ActionView::Partials::PartialRenderer` has its object in a local var
<%= render partial: "product" %>
```
-within product we'll get `@product` in the local variable `product`, as if we had written:
+within `_product` partial we'll get `@product` in the local variable `product`,
+as if we had written:
```erb
<%= render partial: "product", locals: { product: @product } %>
@@ -317,26 +318,6 @@ The `box` layout simply wraps the `_article` partial in a `div`:
</div>
```
-The `_article` partial wraps the article's `body` in a `div` with the `id` of the article using the `div_for` helper:
-
-**articles/_article.html.erb**
-
-```html+erb
-<%= div_for(article) do %>
- <p><%= article.body %></p>
-<% end %>
-```
-
-this would output the following:
-
-```html
-<div class='box'>
- <div id='article_1'>
- <p>Partial Layouts are cool!</p>
- </div>
-</div>
-```
-
Note that the partial layout has access to the local `article` variable that was passed into the `render` call. However, unlike application-wide layouts, partial layouts still have the underscore prefix.
You can also render a block of code within a partial layout instead of calling `yield`. For example, if we didn't have the `_article` partial, we could do this instead:
@@ -345,9 +326,9 @@ You can also render a block of code within a partial layout instead of calling `
```html+erb
<% render(layout: 'box', locals: { article: @article }) do %>
- <%= div_for(article) do %>
+ <div>
<p><%= article.body %></p>
- <% end %>
+ </div>
<% end %>
```
@@ -552,7 +533,7 @@ end
```ruby
atom_feed do |feed|
feed.title("Articles Index")
- feed.updated((@articles.first.created_at))
+ feed.updated(@articles.first.created_at)
@articles.each do |article|
feed.entry(article) do |entry|
@@ -726,7 +707,7 @@ Returns a select tag with options for each of the minutes 0 through 59 with the
```ruby
# Generates a select field for minutes that defaults to the minutes for the time provided.
-select_minute(Time.now + 6.hours)
+select_minute(Time.now + 10.minutes)
```
#### select_month
diff --git a/guides/source/active_job_basics.md b/guides/source/active_job_basics.md
index 29d0c32b09..22f3c0146a 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
@@ -78,7 +81,7 @@ end
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
```
@@ -99,17 +102,20 @@ 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 +129,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 +222,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.
diff --git a/guides/source/active_record_basics.md b/guides/source/active_record_basics.md
index 6551ba0389..a227b54040 100644
--- a/guides/source/active_record_basics.md
+++ b/guides/source/active_record_basics.md
@@ -74,8 +74,8 @@ By default, Active Record uses some naming conventions to find out how the
mapping between models and database tables should be created. Rails will
pluralize your class names to find the respective database table. So, for
a class `Book`, you should have a database table called **books**. The Rails
-pluralization mechanisms are very powerful, being capable to pluralize (and
-singularize) both regular and irregular words. When using class names composed
+pluralization mechanisms are very powerful, being capable of pluralizing (and
+singularizing) both regular and irregular words. When using class names composed
of two or more words, the model class name should follow the Ruby conventions,
using the CamelCase form, while the table name must contain the words separated
by underscores. Examples:
diff --git a/guides/source/active_record_migrations.md b/guides/source/active_record_migrations.md
index 7a994cc5de..ad069a112e 100644
--- a/guides/source/active_record_migrations.md
+++ b/guides/source/active_record_migrations.md
@@ -475,7 +475,8 @@ 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 random characters.
+`fk_rails_` followed by 10 character which is deterministically
+generated from the `from_table` and `column`.
There is a `:name` option to specify a different name if needed.
NOTE: Active Record only supports single column foreign keys. `execute` and
@@ -554,7 +555,7 @@ or write the `up` and `down` methods instead of using the `change` method.
Complex migrations may require processing that Active Record doesn't know how
to reverse. You can use `reversible` to specify what to do when running a
-migration what else to do when reverting it. For example:
+migration and what else to do when reverting it. For example:
```ruby
class ExampleMigration < ActiveRecord::Migration
@@ -606,7 +607,7 @@ schema, and the `down` method of your migration should revert the
transformations done by the `up` method. In other words, the database schema
should be unchanged if you do an `up` followed by a `down`. For example, if you
create a table in the `up` method, you should drop it in the `down` method. It
-is wise to reverse the transformations in precisely the reverse order they were
+is wise to perform the transformations in precisely the reverse order they were
made in the `up` method. The example in the `reversible` section is equivalent to:
```ruby
diff --git a/guides/source/active_record_postgresql.md b/guides/source/active_record_postgresql.md
index 5e58d5baeb..fe112a4708 100644
--- a/guides/source/active_record_postgresql.md
+++ b/guides/source/active_record_postgresql.md
@@ -29,8 +29,8 @@ that are supported by the PostgreSQL adapter.
### Bytea
-* [type definition](http://www.postgresql.org/docs/9.3/static/datatype-binary.html)
-* [functions and operators](http://www.postgresql.org/docs/9.3/static/functions-binarystring.html)
+* [type definition](http://www.postgresql.org/docs/current/static/datatype-binary.html)
+* [functions and operators](http://www.postgresql.org/docs/current/static/functions-binarystring.html)
```ruby
# db/migrate/20140207133952_create_documents.rb
@@ -49,8 +49,8 @@ Document.create payload: data
### Array
-* [type definition](http://www.postgresql.org/docs/9.3/static/arrays.html)
-* [functions and operators](http://www.postgresql.org/docs/9.3/static/functions-array.html)
+* [type definition](http://www.postgresql.org/docs/current/static/arrays.html)
+* [functions and operators](http://www.postgresql.org/docs/current/static/functions-array.html)
```ruby
# db/migrate/20140207133952_create_books.rb
@@ -83,7 +83,7 @@ Book.where("array_length(ratings, 1) >= 3")
### Hstore
-* [type definition](http://www.postgresql.org/docs/9.3/static/hstore.html)
+* [type definition](http://www.postgresql.org/docs/current/static/hstore.html)
NOTE: you need to enable the `hstore` extension to use hstore.
@@ -112,8 +112,8 @@ profile.save!
### JSON
-* [type definition](http://www.postgresql.org/docs/9.3/static/datatype-json.html)
-* [functions and operators](http://www.postgresql.org/docs/9.3/static/functions-json.html)
+* [type definition](http://www.postgresql.org/docs/current/static/datatype-json.html)
+* [functions and operators](http://www.postgresql.org/docs/current/static/functions-json.html)
```ruby
# db/migrate/20131220144913_create_events.rb
@@ -138,10 +138,10 @@ Event.where("payload->>'kind' = ?", "user_renamed")
### Range Types
-* [type definition](http://www.postgresql.org/docs/9.3/static/rangetypes.html)
-* [functions and operators](http://www.postgresql.org/docs/9.3/static/functions-range.html)
+* [type definition](http://www.postgresql.org/docs/current/static/rangetypes.html)
+* [functions and operators](http://www.postgresql.org/docs/current/static/functions-range.html)
-This type is mapped to Ruby [`Range`](http://www.ruby-doc.org/core-2.1.1/Range.html) objects.
+This type is mapped to Ruby [`Range`](http://www.ruby-doc.org/core-2.2.2/Range.html) objects.
```ruby
# db/migrate/20130923065404_create_events.rb
@@ -173,7 +173,7 @@ event.ends_at # => Thu, 13 Feb 2014
### Composite Types
-* [type definition](http://www.postgresql.org/docs/9.3/static/rowtypes.html)
+* [type definition](http://www.postgresql.org/docs/current/static/rowtypes.html)
Currently there is no special support for composite types. They are mapped to
normal text columns:
@@ -213,7 +213,7 @@ contact.save!
### Enumerated Types
-* [type definition](http://www.postgresql.org/docs/9.3/static/datatype-enum.html)
+* [type definition](http://www.postgresql.org/docs/current/static/datatype-enum.html)
Currently there is no special support for enumerated types. They are mapped as
normal text columns:
@@ -242,9 +242,9 @@ article.save!
### UUID
-* [type definition](http://www.postgresql.org/docs/9.4/static/datatype-uuid.html)
-* [pgcrypto generator function](http://www.postgresql.org/docs/9.4/static/pgcrypto.html#AEN159361)
-* [uuid-ossp generator functions](http://www.postgresql.org/docs/9.4/static/uuid-ossp.html)
+* [type definition](http://www.postgresql.org/docs/current/static/datatype-uuid.html)
+* [pgcrypto generator function](http://www.postgresql.org/docs/current/static/pgcrypto.html#AEN159361)
+* [uuid-ossp generator functions](http://www.postgresql.org/docs/current/static/uuid-ossp.html)
NOTE: you need to enable the `pgcrypto` (only PostgreSQL >= 9.4) or `uuid-ossp`
extension to use uuid.
@@ -266,13 +266,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,10 +289,12 @@ 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/9.3/static/datatype-bit.html)
-* [functions and operators](http://www.postgresql.org/docs/9.3/static/functions-bitstring.html)
+* [type definition](http://www.postgresql.org/docs/current/static/datatype-bit.html)
+* [functions and operators](http://www.postgresql.org/docs/current/static/functions-bitstring.html)
```ruby
# db/migrate/20131220144913_create_users.rb
@@ -314,10 +317,10 @@ user.save!
### Network Address Types
-* [type definition](http://www.postgresql.org/docs/9.3/static/datatype-net-types.html)
+* [type definition](http://www.postgresql.org/docs/current/static/datatype-net-types.html)
The types `inet` and `cidr` are mapped to Ruby
-[`IPAddr`](http://www.ruby-doc.org/stdlib-2.1.1/libdoc/ipaddr/rdoc/IPAddr.html)
+[`IPAddr`](http://www.ruby-doc.org/stdlib-2.2.2/libdoc/ipaddr/rdoc/IPAddr.html)
objects. The `macaddr` type is mapped to normal text.
```ruby
@@ -349,7 +352,7 @@ macbook.address
### Geometric Types
-* [type definition](http://www.postgresql.org/docs/9.3/static/datatype-geometric.html)
+* [type definition](http://www.postgresql.org/docs/current/static/datatype-geometric.html)
All geometric types, with the exception of `points` are mapped to normal text.
A point is casted to an array containing `x` and `y` coordinates.
@@ -377,6 +380,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
----------------
@@ -404,7 +410,7 @@ Document.where("to_tsvector('english', title || ' ' || body) @@ to_tsquery(?)",
Database Views
--------------
-* [view creation](http://www.postgresql.org/docs/9.3/static/sql-createview.html)
+* [view creation](http://www.postgresql.org/docs/current/static/sql-createview.html)
Imagine you need to work with a legacy database containing the following table:
diff --git a/guides/source/active_record_querying.md b/guides/source/active_record_querying.md
index 2f10bc4e7c..e3cfabb327 100644
--- a/guides/source/active_record_querying.md
+++ b/guides/source/active_record_querying.md
@@ -898,7 +898,7 @@ For example:
Item.transaction do
i = Item.lock.first
i.name = 'Jones'
- i.save
+ i.save!
end
```
@@ -1787,8 +1787,9 @@ EXPLAIN for: SELECT `users`.* FROM `users` INNER JOIN `articles` ON `articles`.`
under MySQL.
-Active Record performs a pretty printing that emulates the one of the database
-shells. So, the same query running with the PostgreSQL adapter would yield instead
+Active Record performs a pretty printing that emulates that of the
+corresponding database shell. So, the same query running with the
+PostgreSQL adapter would yield instead
```
EXPLAIN for: SELECT "users".* FROM "users" INNER JOIN "articles" ON "articles"."user_id" = "users"."id" WHERE "users"."id" = 1
diff --git a/guides/source/active_record_validations.md b/guides/source/active_record_validations.md
index 343b761e93..7932853c11 100644
--- a/guides/source/active_record_validations.md
+++ b/guides/source/active_record_validations.md
@@ -47,7 +47,7 @@ built-in helpers for common needs, and allows you to create your own validation
methods as well.
There are several other ways to validate data before it is saved into your
-database, including native database constraints, client-side validations,
+database, including native database constraints, client-side validations and
controller-level validations. Here's a summary of the pros and cons:
* Database constraints and/or stored procedures make the validation mechanisms
@@ -122,7 +122,7 @@ database only if the object is valid:
* `update!`
The bang versions (e.g. `save!`) raise an exception if the record is invalid.
-The non-bang versions don't, `save` and `update` return `false`,
+The non-bang versions don't: `save` and `update` return `false`, and
`create` just returns the object.
### Skipping Validations
@@ -143,7 +143,7 @@ database regardless of its validity. They should be used with caution.
* `update_counters`
Note that `save` also has the ability to skip validations if passed `validate:
-false` as argument. This technique should be used with caution.
+false` as an argument. This technique should be used with caution.
* `save(validate: false)`
@@ -272,7 +272,7 @@ 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 reading some text, or any similar
+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).
@@ -283,6 +283,7 @@ class Person < ActiveRecord::Base
end
```
+This check is performed only if `terms_of_service` is not `nil`.
The default error message for this helper is _"must be accepted"_.
It can receive an `:accept` option, which determines the value that will be
@@ -338,7 +339,7 @@ In your view template you could use something like
This check is performed only if `email_confirmation` is not `nil`. To require
confirmation, make sure to add a presence check for the confirmation attribute
-(we'll take a look at `presence` later on this guide):
+(we'll take a look at `presence` later on in this guide):
```ruby
class Person < ActiveRecord::Base
@@ -499,9 +500,9 @@ constraints to acceptable values:
default error message for this option is _"must be equal to %{count}"_.
* `:less_than` - Specifies the value must be less than the supplied value. The
default error message for this option is _"must be less than %{count}"_.
-* `:less_than_or_equal_to` - Specifies the value must be less than or equal the
- supplied value. The default error message for this option is _"must be less
- than or equal to %{count}"_.
+* `:less_than_or_equal_to` - Specifies the value must be less than or equal to
+ the supplied value. The default error message for this option is _"must be
+ less than or equal to %{count}"_.
* `:odd` - Specifies the value must be an odd number if set to true. The
default error message for this option is _"must be odd"_.
* `:even` - Specifies the value must be an even number if set to true. The
@@ -551,7 +552,6 @@ Since `false.blank?` is true, if you want to validate the presence of a boolean
field you should use one of the following validations:
```ruby
-validates :boolean_field_name, presence: true
validates :boolean_field_name, inclusion: { in: [true, false] }
validates :boolean_field_name, exclusion: { in: [nil] }
```
@@ -626,7 +626,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/9.4/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.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.
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
@@ -813,7 +813,7 @@ end
Person.new.valid? # => ActiveModel::StrictValidationFailed: Name can't be blank
```
-There is also an ability to pass custom exception to `:strict` option.
+There is also the ability to pass a custom exception to the `:strict` option.
```ruby
class Person < ActiveRecord::Base
@@ -877,7 +877,7 @@ end
### Grouping Conditional validations
-Sometimes it is useful to have multiple validations use one condition, it can
+Sometimes it is useful to have multiple validations use one condition. It can
be easily achieved using `with_options`.
```ruby
@@ -889,8 +889,8 @@ class User < ActiveRecord::Base
end
```
-All validations inside of `with_options` block will have automatically passed
-the condition `if: :is_admin?`
+All validations inside of the `with_options` block will have automatically
+passed the condition `if: :is_admin?`
### Combining Validation Conditions
diff --git a/guides/source/active_support_core_extensions.md b/guides/source/active_support_core_extensions.md
index 2a643680f7..01bf928407 100644
--- a/guides/source/active_support_core_extensions.md
+++ b/guides/source/active_support_core_extensions.md
@@ -1936,6 +1936,8 @@ as well as adding or subtracting their results from a Time object. For example:
(4.months + 5.years).from_now
```
+NOTE: Defined in `active_support/core_ext/numeric/time.rb`
+
### Formatting
Enables the formatting of numbers in a variety of ways.
@@ -2193,6 +2195,16 @@ removed:
NOTE: Defined in `active_support/core_ext/enumerable.rb`.
+### `pluck`
+
+The method `pluck` returns an array based on the given key:
+
+```ruby
+[{ name: "David" }, { name: "Rafael" }, { name: "Aaron" }].pluck(:name) # => ["David", "Rafael", "Aaron"]
+```
+
+NOTE: Defined in `active_support/core_ext/enumerable.rb`.
+
Extensions to `Array`
---------------------
@@ -2201,14 +2213,14 @@ Extensions to `Array`
Active Support augments the API of arrays to ease certain ways of accessing them. For example, `to` returns the subarray of elements up to the one at the passed index:
```ruby
-%w(a b c d).to(2) # => %w(a b c)
+%w(a b c d).to(2) # => ["a", "b", "c"]
[].to(7) # => []
```
Similarly, `from` returns the tail from the element at the passed index to the end. If the index is greater than the length of the array, it returns an empty array.
```ruby
-%w(a b c d).from(2) # => %w(c d)
+%w(a b c d).from(2) # => ["c", "d"]
%w(a b c d).from(10) # => []
[].from(0) # => []
```
@@ -2216,7 +2228,7 @@ Similarly, `from` returns the tail from the element at the passed index to the e
The methods `second`, `third`, `fourth`, and `fifth` return the corresponding element (`first` is built-in). Thanks to social wisdom and positive constructiveness all around, `forty_two` is also available.
```ruby
-%w(a b c d).third # => c
+%w(a b c d).third # => "c"
%w(a b c d).fifth # => nil
```
@@ -2229,7 +2241,7 @@ NOTE: Defined in `active_support/core_ext/array/access.rb`.
This method is an alias of `Array#unshift`.
```ruby
-%w(a b c d).prepend('e') # => %w(e a b c d)
+%w(a b c d).prepend('e') # => ["e", "a", "b", "c", "d"]
[].prepend(10) # => [10]
```
@@ -2240,8 +2252,8 @@ NOTE: Defined in `active_support/core_ext/array/prepend_and_append.rb`.
This method is an alias of `Array#<<`.
```ruby
-%w(a b c d).append('e') # => %w(a b c d e)
-[].append([1,2]) # => [[1,2]]
+%w(a b c d).append('e') # => ["a", "b", "c", "d", "e"]
+[].append([1,2]) # => [[1, 2]]
```
NOTE: Defined in `active_support/core_ext/array/prepend_and_append.rb`.
@@ -2465,7 +2477,7 @@ NOTE: Defined in `active_support/core_ext/array/wrap.rb`.
### Duplicating
-The method `Array.deep_dup` duplicates itself and all objects inside
+The method `Array#deep_dup` duplicates itself and all objects inside
recursively with Active Support method `Object#deep_dup`. It works like `Array#map` with sending `deep_dup` method to each object inside.
```ruby
@@ -2687,7 +2699,7 @@ NOTE: Defined in `active_support/core_ext/hash/deep_merge.rb`.
### Deep duplicating
-The method `Hash.deep_dup` duplicates itself and all keys and values
+The method `Hash#deep_dup` duplicates itself and all keys and values
inside recursively with Active Support method `Object#deep_dup`. It works like `Enumerator#each_with_object` with sending `deep_dup` method to each pair inside.
```ruby
@@ -2883,7 +2895,7 @@ The method `transform_values` accepts a block and returns a hash that has applie
```
There's also the bang variant `transform_values!` that applies the block operations to values in the very receiver.
-NOTE: Defined in `active_support/core_text/hash/transform_values.rb`.
+NOTE: Defined in `active_support/core_ext/hash/transform_values.rb`.
### Slicing
diff --git a/guides/source/active_support_instrumentation.md b/guides/source/active_support_instrumentation.md
index 1b14bedfbf..373dbbb9aa 100644
--- a/guides/source/active_support_instrumentation.md
+++ b/guides/source/active_support_instrumentation.md
@@ -252,6 +252,20 @@ INFO. The adapters will add their own data as well.
| `:name` | Record's class |
| `:connection_id` | `self.object_id` |
+### instantiation.active_record
+
+| Key | Value |
+| ---------------- | ----------------------------------------- |
+| `:record_count` | Number of records that instantiated |
+| `:class_name` | Record's class |
+
+```ruby
+{
+ record_count: 1,
+ class_name: "User"
+}
+```
+
Action Mailer
-------------
diff --git a/guides/source/api_app.md b/guides/source/api_app.md
new file mode 100644
index 0000000000..29ca872254
--- /dev/null
+++ b/guides/source/api_app.md
@@ -0,0 +1,408 @@
+**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 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.
+
+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.
+
+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** a client-side framework.
+
+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?".
+
+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.
+
+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.
+
+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 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:
+
+```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 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 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`
+- `ActionDispatch::ParamsParser`
+- `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:
+
+```bash
+$ rake middleware
+```
+
+### Using the Cache Middleware
+
+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.
+
+For instance, using the `stale?` method:
+
+```ruby
+def show
+ @post = Post.find(params[:id])
+
+ 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 in it.
+
+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?`:
+
+```ruby
+def show
+ @post = Post.find(params[:id])
+
+ if stale?(last_modified: @post.updated_at, public: true)
+ render json: @post
+ end
+end
+```
+
+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: This middleware is always outside of the `Rack::Lock` mutex, even in
+single-threaded applications.
+
+### Using Rack::Sendfile
+
+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.
+
+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
+front-ends in [the Rack::Sendfile
+documentation](http://rubydoc.info/github/rack/rack/master/Rack/Sendfile).
+
+Here are some values for popular servers, once they are configured, to support
+accelerated file sending:
+
+```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::ParamsParser
+
+`ActionDispatch::ParamsParser` 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:
+
+```javascript
+jQuery.ajax({
+ type: 'POST',
+ url: '/people',
+ dataType: 'json',
+ contentType: 'application/json',
+ data: JSON.stringify({ person: { firstName: "Yehuda", lastName: "Katz" } }),
+ success: function(json) { }
+});
+```
+
+`ActionDispatch::ParamsParser` will see the `Content-Type` and your parameters
+will be:
+
+```ruby
+{ :person => { :firstName => "Yehuda", :lastName => "Katz" } }
+```
+
+### Other Middlewares
+
+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:
+
+- `Rack::MethodOverride`
+- `ActionDispatch::Cookies`
+- `ActionDispatch::Flash`
+- For sessions management
+ * `ActionDispatch::Session::CacheStore`
+ * `ActionDispatch::Session::CookieStore`
+ * `ActionDispatch::Session::MemCacheStore`
+
+Any of these middlewares can be added via:
+
+```ruby
+config.middleware.use Rack::MethodOverride
+```
+
+### Removing Middlewares
+
+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.delete ::Rack::Sendfile
+```
+
+Keep in mind that removing these middlewares will remove support for certain
+features in Action Controller.
+
+Choosing Controller Modules
+---------------------------
+
+An API application (using `ActionController::API`) comes with the following
+controller modules by default:
+
+- `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 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.
+
+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
+```
+
+### Adding Other Modules
+
+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.
+- `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/association_basics.md b/guides/source/association_basics.md
index 412cfd198a..05dd0d2a04 100644
--- a/guides/source/association_basics.md
+++ b/guides/source/association_basics.md
@@ -435,7 +435,7 @@ end
The simplest rule of thumb is that you should set up a `has_many :through` relationship if you need to work with the relationship model as an independent entity. If you don't need to do anything with the relationship model, it may be simpler to set up a `has_and_belongs_to_many` relationship (though you'll need to remember to create the joining table in the database).
-You should use `has_many :through` if you need validations, callbacks, or extra attributes on the join model.
+You should use `has_many :through` if you need validations, callbacks or extra attributes on the join model.
### Polymorphic Associations
@@ -590,7 +590,7 @@ If you create an association some time after you build the underlying model, you
If you create a `has_and_belongs_to_many` association, you need to explicitly create the joining table. Unless the name of the join table is explicitly specified by using the `:join_table` option, Active Record creates the name by using the lexical order of the class names. So a join between customer and order models will give the default join table name of "customers_orders" because "c" outranks "o" in lexical ordering.
-WARNING: The precedence between model names is calculated using the `<` operator for `String`. This means that if the strings are of different lengths, and the strings are equal when compared up to the shortest length, then the longer string is considered of higher lexical precedence than the shorter one. For example, one would expect the tables "paper_boxes" and "papers" to generate a join table name of "papers_paper_boxes" because of the length of the name "paper_boxes", but it in fact generates a join table name of "paper_boxes_papers" (because the underscore '_' is lexicographically _less_ than 's' in common encodings).
+WARNING: The precedence between model names is calculated using the `<=>` operator for `String`. This means that if the strings are of different lengths, and the strings are equal when compared up to the shortest length, then the longer string is considered of higher lexical precedence than the shorter one. For example, one would expect the tables "paper_boxes" and "papers" to generate a join table name of "papers_paper_boxes" because of the length of the name "paper_boxes", but it in fact generates a join table name of "paper_boxes_papers" (because the underscore '\_' is lexicographically _less_ than 's' in common encodings).
Whatever the name, you must manually generate the join table with an appropriate migration. For example, consider these associations:
@@ -620,7 +620,7 @@ class CreateAssembliesPartsJoinTable < ActiveRecord::Migration
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 models IDs, or exceptions about conflicting IDs, chances are you forgot that bit.
+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.
### Controlling Association Scope
@@ -793,7 +793,7 @@ If the associated object has already been retrieved from the database for this o
##### `association=(associate)`
-The `association=` method assigns an associated object to this object. Behind the scenes, this means extracting the primary key from the associate object and setting this object's foreign key to the same value.
+The `association=` method assigns an associated object to this object. Behind the scenes, this means extracting the primary key from the associated object and setting this object's foreign key to the same value.
```ruby
@order.customer = @customer
@@ -1138,7 +1138,7 @@ If the associated object has already been retrieved from the database for this o
##### `association=(associate)`
-The `association=` method assigns an associated object to this object. Behind the scenes, this means extracting the primary key from this object and setting the associate object's foreign key to the same value.
+The `association=` method assigns an associated object to this object. Behind the scenes, this means extracting the primary key from this object and setting the associated object's foreign key to the same value.
```ruby
@supplier.account = @account
@@ -1219,8 +1219,8 @@ Controls what happens to the associated object when its owner is destroyed:
It's necessary not to set or leave `:nullify` option for those associations
that have `NOT NULL` database constraints. If you don't set `dependent` to
destroy such associations you won't be able to change the associated object
-because initial associated object foreign key will be set to unallowed `NULL`
-value.
+because the initial associated object's foreign key will be set to the
+unallowed `NULL` value.
##### `:foreign_key`
@@ -1467,7 +1467,14 @@ The `collection_singular_ids=` method makes the collection contain only the obje
##### `collection.clear`
-The `collection.clear` method removes every object from the collection. This destroys the associated objects if they are associated with `dependent: :destroy`, deletes them directly from the database if `dependent: :delete_all`, and otherwise sets their foreign keys to `NULL`.
+The `collection.clear` method removes all objects from the collection according to the strategy specified by the `dependent` option. If no option is given, it follows the default strategy. The default strategy for `has_many :through` associations is `delete_all`, and for `has_many` associations is to set the foreign keys to `NULL`.
+
+```ruby
+@customer.orders.clear
+```
+
+WARNING: Objects will be deleted if they're associated with `dependent: :destroy`,
+just like `dependent: :delete_all`.
##### `collection.empty?`
@@ -1506,7 +1513,9 @@ The `collection.where` method finds objects within the collection based on the c
##### `collection.exists?(...)`
-The `collection.exists?` method checks whether an object meeting the supplied conditions exists in the collection. It uses the same syntax and options as `ActiveRecord::Base.exists?`.
+The `collection.exists?` method checks whether an object meeting the supplied
+conditions exists in the collection. It uses the same syntax and options as
+[`ActiveRecord::Base.exists?`](http://api.rubyonrails.org/classes/ActiveRecord/FinderMethods.html#method-i-exists-3F).
##### `collection.build(attributes = {}, ...)`
@@ -1617,9 +1626,10 @@ end
By convention, Rails assumes that the column used to hold the primary key of the association is `id`. You can override this and explicitly specify the primary key with the `:primary_key` option.
-Let's say that `users` table has `id` as the primary_key but it also has
-`guid` column. And the requirement is that `todos` table should hold
-`guid` column value and not `id` value. This can be achieved like this
+Let's say the `users` table has `id` as the primary_key but it also
+has a `guid` column. The requirement is that the `todos` table should
+hold the `guid` column value as the foreign key and not `id`
+value. This can be achieved like this:
```ruby
class User < ActiveRecord::Base
@@ -1627,8 +1637,8 @@ class User < ActiveRecord::Base
end
```
-Now if we execute `@user.todos.create` then `@todo` record will have
-`user_id` value as the `guid` value of `@user`.
+Now if we execute `@todo = @user.todos.create` then the `@todo`
+record's `user_id` value will be the `guid` value of `@user`.
##### `:source`
@@ -2004,7 +2014,9 @@ The `collection.where` method finds objects within the collection based on the c
##### `collection.exists?(...)`
-The `collection.exists?` method checks whether an object meeting the supplied conditions exists in the collection. It uses the same syntax and options as `ActiveRecord::Base.exists?`.
+The `collection.exists?` method checks whether an object meeting the supplied
+conditions exists in the collection. It uses the same syntax and options as
+[`ActiveRecord::Base.exists?`](http://api.rubyonrails.org/classes/ActiveRecord/FinderMethods.html#method-i-exists-3F).
##### `collection.build(attributes = {})`
diff --git a/guides/source/command_line.md b/guides/source/command_line.md
index 315d8c14b6..0f5a9e4e39 100644
--- a/guides/source/command_line.md
+++ b/guides/source/command_line.md
@@ -64,10 +64,10 @@ $ cd commandsapp
$ bin/rails server
=> Booting WEBrick
=> Rails 5.0.0 application starting in development on http://localhost:3000
-=> Call with -d to detach
+=> Run `rails server -h` for more startup options
=> Ctrl-C to shutdown server
[2013-08-07 02:00:01] INFO WEBrick 1.3.1
-[2013-08-07 02:00:01] INFO ruby 2.0.0 (2013-06-27) [x86_64-darwin11.2.0]
+[2013-08-07 02:00:01] INFO ruby 2.2.2 (2015-06-27) [x86_64-darwin11.2.0]
[2013-08-07 02:00:01] INFO WEBrick::HTTPServer#start: pid=69680 port=3000
```
diff --git a/guides/source/configuring.md b/guides/source/configuring.md
index 4da369be5e..bb6c395c96 100644
--- a/guides/source/configuring.md
+++ b/guides/source/configuring.md
@@ -88,8 +88,6 @@ application. Accepts a valid week day symbol (e.g. `:monday`).
end
```
-* `config.dependency_loading` is a flag that allows you to disable constant autoloading setting it to false. It only has effect if `config.cache_classes` is true, which it is by default in production mode.
-
* `config.eager_load` when true, eager loads all registered `config.eager_load_namespaces`. This includes your application, engines, Rails frameworks and any other registered namespace.
* `config.eager_load_namespaces` registers namespaces that are eager loaded when `config.eager_load` is true. All namespaces in the list must respond to the `eager_load!` method.
@@ -163,8 +161,6 @@ pipeline is enabled. It is set to true by default.
* `config.assets.cache_store` defines the cache store that Sprockets will use. The default is the Rails file store.
-* `config.assets.version` is an option string that is used in MD5 hash generation. This can be changed to force all files to be recompiled.
-
* `config.assets.compile` is a boolean that can be used to turn on live Sprockets compilation in production.
* `config.assets.logger` accepts a logger conforming to the interface of Log4r or the default Ruby `Logger` class. Defaults to the same configured at `config.logger`. Setting `config.assets.logger` to false will turn off served assets logging.
@@ -187,13 +183,15 @@ The full set of methods that can be used in this block are as follows:
* `helper` defines whether or not to generate helpers. Defaults to `true`.
* `integration_tool` defines which integration tool to use. Defaults to `nil`.
* `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 `nil`.
+* `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.
* `resource_controller` defines which generator to use for generating a controller when using `rails generate resource`. Defaults to `:controller`.
+* `resource_route` defines whether a resource route definition should be generated
+ or not. Defaults to `true`.
* `scaffold_controller` different from `resource_controller`, defines which generator to use for generating a _scaffolded_ controller when using `rails generate scaffold`. Defaults to `:scaffold_controller`.
* `stylesheets` turns on the hook for stylesheets in generators. Used in Rails for when the `scaffold` generator is run, but this hook can be used in other generates as well. Defaults to `true`.
* `stylesheet_engine` configures the stylesheet engine (for eg. sass) to be used when generating assets. Defaults to `:css`.
-* `test_framework` defines which test framework to use. Defaults to `false` and will use Test::Unit by default.
+* `test_framework` defines which test framework to use. Defaults to `false` and will use Minitest by default.
* `template_engine` defines which template engine to use, such as ERB or Haml. Defaults to `:erb`.
### Configuring Middleware
@@ -201,7 +199,7 @@ The full set of methods that can be used in this block are as follows:
Every Rails application comes with a standard set of middleware which it uses in this order in the development environment:
* `ActionDispatch::SSL` forces every request to be under HTTPS protocol. Will be available if `config.force_ssl` is set to `true`. Options passed to this can be configured by using `config.ssl_options`.
-* `ActionDispatch::Static` is used to serve static assets. Disabled if `config.serve_static_files` is `false`.
+* `ActionDispatch::Static` is used to serve static assets. Disabled if `config.serve_static_files` is `false`. Set `config.static_index` if you need to serve a static directory index file that is not named `index`. For example, to serve `main.html` instead of `index.html` for directory requests, set `config.static_index` to `"main"`.
* `Rack::Lock` wraps the app in mutex so it can only be called by a single thread at a time. Only enabled when `config.cache_classes` is `false`.
* `ActiveSupport::Cache::Strategy::LocalCache` serves as a basic memory backed cache. This cache is not thread safe and is intended only for serving as a temporary memory cache for a single thread.
* `Rack::Runtime` sets an `X-Runtime` header, containing the time (in seconds) taken to execute the request.
@@ -518,6 +516,9 @@ There are a number of settings available on `config.action_mailer`:
config.action_mailer.show_previews = false
```
+* `config.action_mailer.deliver_later_queue_name` specifies the queue name for
+ mailers. By default this is `mailers`.
+
### Configuring Active Support
There are a few configuration options available in Active Support:
@@ -526,7 +527,7 @@ There are a few configuration options available in Active Support:
* `config.active_support.test_order` sets the order that test cases are executed. Possible values are `:random` and `:sorted`. This option is set to `:random` in `config/environments/test.rb` in newly-generated applications. If you have an application that does not specify a `test_order`, it will default to `:sorted`, *until* Rails 5.0, when the default will become `:random`.
-* `config.active_support.escape_html_entities_in_json` enables or disables the escaping of HTML entities in JSON serialization. Defaults to `false`.
+* `config.active_support.escape_html_entities_in_json` enables or disables the escaping of HTML entities in JSON serialization. Defaults to `true`.
* `config.active_support.use_standard_json_time_format` enables or disables serializing dates to ISO 8601 format. Defaults to `true`.
@@ -1126,7 +1127,7 @@ Search Engines Indexing
Sometimes, you may want to prevent some pages of your application to be visible
on search sites like Google, Bing, Yahoo or Duck Duck Go. The robots that index
-these sites will first analyse the `http://your-site.com/robots.txt` file to
+these sites will first analyze the `http://your-site.com/robots.txt` file to
know which pages it is allowed to index.
Rails creates this file for you inside the `/public` folder. By default, it allows
diff --git a/guides/source/contributing_to_ruby_on_rails.md b/guides/source/contributing_to_ruby_on_rails.md
index 244add0aee..3279c99c42 100644
--- a/guides/source/contributing_to_ruby_on_rails.md
+++ b/guides/source/contributing_to_ruby_on_rails.md
@@ -66,7 +66,7 @@ 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.
-If you'd like feedback on an idea for a feature before doing the work for make
+If you'd like feedback on an idea for a feature before doing the work to make
a patch, please send an email to the [rails-core mailing
list](https://groups.google.com/forum/?fromgroups#!forum/rubyonrails-core). You
might get no response, which means that everyone is indifferent. You might find
@@ -79,17 +79,17 @@ discussions new features require.
Helping to Resolve Existing Issues
----------------------------------
-As a next step beyond reporting issues, you can help the core team resolve existing issues. If you check the [Everyone's Issues](https://github.com/rails/rails/issues) list in GitHub Issues, you'll find lots of issues already requiring attention. What can you do for these? Quite a bit, actually:
+As a next step beyond reporting issues, you can help the core team resolve existing issues. If you check the [issues list](https://github.com/rails/rails/issues) in GitHub Issues, you'll find lots of issues already requiring attention. What can you do for these? Quite a bit, actually:
### Verifying Bug Reports
For starters, it helps just to verify bug reports. Can you reproduce the reported issue on your own computer? If so, you can add a comment to the issue saying that you're seeing the same thing.
-If something is very vague, can you help squash it down into something specific? Maybe you can provide additional information to help reproduce a bug, or help by eliminating needless steps that aren't required to demonstrate the problem.
+If an issue is very vague, can you help narrow it down to something more specific? Maybe you can provide additional information to help reproduce a bug, or help by eliminating needless steps that aren't required to demonstrate the problem.
If you find a bug report without a test, it's very useful to contribute a failing test. This is also a great way to get started exploring the source code: looking at the existing test files will teach you how to write more tests. New tests are best contributed in the form of a patch, as explained later on in the "Contributing to the Rails Code" section.
-Anything you can do to make bug reports more succinct or easier to reproduce is a help to folks trying to write code to fix those bugs - whether you end up writing the code yourself or not.
+Anything you can do to make bug reports more succinct or easier to reproduce helps folks trying to write code to fix those bugs - whether you end up writing the code yourself or not.
### Testing Patches
@@ -117,7 +117,7 @@ Once you're happy that the pull request contains a good change, comment on the G
>I like the way you've restructured that code in generate_finder_sql - much nicer. The tests look good too.
-If your comment simply says "+1", then odds are that other reviewers aren't going to take it too seriously. Show that you took the time to review the pull request.
+If your comment simply reads "+1", then odds are that other reviewers aren't going to take it too seriously. Show that you took the time to review the pull request.
Contributing to the Rails Documentation
---------------------------------------
@@ -579,8 +579,7 @@ following:
```bash
$ git fetch upstream
$ git checkout my_pull_request
-$ git rebase upstream/master
-$ git rebase -i
+$ git rebase -i upstream/master
< Choose 'squash' for all of your commits except the first one. >
< Edit the commit message to make sense, and describe all your changes. >
diff --git a/guides/source/debugging_rails_applications.md b/guides/source/debugging_rails_applications.md
index ec3ac62b8c..dc1df8f229 100644
--- a/guides/source/debugging_rails_applications.md
+++ b/guides/source/debugging_rails_applications.md
@@ -317,7 +317,7 @@ For example:
=> Notice: server is listening on all interfaces (0.0.0.0). Consider using 127.0.0.1 (--binding option)
=> Ctrl-C to shutdown server
[2014-04-11 13:11:47] INFO WEBrick 1.3.1
-[2014-04-11 13:11:47] INFO ruby 2.1.1 (2014-02-24) [i686-linux]
+[2014-04-11 13:11:47] INFO ruby 2.2.2 (2015-04-13) [i686-linux]
[2014-04-11 13:11:47] INFO WEBrick::HTTPServer#start: pid=6370 port=3000
@@ -531,8 +531,11 @@ command later in this guide).
And then ask again for the instance_variables:
```
-(byebug) instance_variables.include? "@articles"
-true
+(byebug) instance_variables
+[:@_action_has_layout, :@_routes, :@_headers, :@_status, :@_request,
+ :@_response, :@_env, :@_prefixes, :@_lookup_context, :@_action_name,
+ :@_response_body, :@marked_for_same_origin_verification, :@_config,
+ :@articles]
```
Now `@articles` is included in the instance variables, because the line defining it
@@ -778,7 +781,7 @@ will be stopped and you will have to start it again.
### Settings
-`byebug` has a few available options to tweak its behaviour:
+`byebug` has a few available options to tweak its behavior:
* `set autoreload`: Reload source code when changed (defaults: true).
* `set autolist`: Execute `list` command on every breakpoint (defaults: true).
diff --git a/guides/source/development_dependencies_install.md b/guides/source/development_dependencies_install.md
index 989b29956c..295e48f493 100644
--- a/guides/source/development_dependencies_install.md
+++ b/guides/source/development_dependencies_install.md
@@ -21,14 +21,14 @@ The easiest and recommended way to get a development environment ready to hack i
The Hard Way
------------
-In case you can't use the Rails development box, see section above, these are the steps to manually build a development box for Ruby on Rails core development.
+In case you can't use the Rails development box, see section below, these are the steps to manually build a development box for Ruby on Rails core development.
### Install Git
Ruby on Rails uses Git for source code control. The [Git homepage](http://git-scm.com/) has installation instructions. There are a variety of resources on the net that will help you get familiar with Git:
* [Try Git course](http://try.github.io/) is an interactive course that will teach you the basics.
-* The [official Documentation](http://git-scm.com/documentation) is pretty comprehensive and also contains some videos with the basics of Git
+* The [official Documentation](http://git-scm.com/documentation) is pretty comprehensive and also contains some videos with the basics of Git.
* [Everyday Git](http://schacon.github.io/git/everyday.html) will teach you just enough about Git to get by.
* The [PeepCode screencast](https://peepcode.com/products/git) on Git is easier to follow.
* [GitHub](http://help.github.com) offers links to a variety of Git resources.
diff --git a/guides/source/documents.yaml b/guides/source/documents.yaml
index 7ae3640937..9145aee009 100644
--- a/guides/source/documents.yaml
+++ b/guides/source/documents.yaml
@@ -11,7 +11,7 @@
-
name: Active Record Basics
url: active_record_basics.html
- description: This guide will get you started with models, persistence to database and the Active Record pattern and library.
+ description: This guide will get you started with models, persistence to database, and the Active Record pattern and library.
-
name: Active Record Migrations
url: active_record_migrations.html
@@ -19,7 +19,7 @@
-
name: Active Record Validations
url: active_record_validations.html
- description: This guide covers how you can use Active Record validations
+ description: This guide covers how you can use Active Record validations.
-
name: Active Record Callbacks
url: active_record_callbacks.html
@@ -74,7 +74,7 @@
-
name: Rails Internationalization API
url: i18n.html
- description: This guide covers how to add internationalization to your applications. Your application will be able to translate content to different languages, change pluralization rules, use correct date formats for each country and so on.
+ description: This guide covers how to add internationalization to your applications. Your application will be able to translate content to different languages, change pluralization rules, use correct date formats for each country, and so on.
-
name: Action Mailer Basics
url: action_mailer_basics.html
@@ -82,7 +82,7 @@
-
name: Active Job Basics
url: active_job_basics.html
- description: This guide provides you with all you need to get started in creating, enqueueing and executing background jobs.
+ description: This guide provides you with all you need to get started creating, enqueuing, and executing background jobs.
-
name: Testing Rails Applications
work_in_progress: true
@@ -116,7 +116,7 @@
name: The Rails Initialization Process
work_in_progress: true
url: initialization.html
- description: This guide explains the internals of the Rails initialization process as of Rails 4
+ description: This guide explains the internals of the Rails initialization process as of Rails 4.
-
name: Autoloading and Reloading Constants
url: autoloading_and_reloading_constants.html
diff --git a/guides/source/engines.md b/guides/source/engines.md
index bcb0ee7d5d..3b1588b75a 100644
--- a/guides/source/engines.md
+++ b/guides/source/engines.md
@@ -582,7 +582,7 @@ the comments, however, is not quite right yet. If you were to create a comment
right now, you would see this error:
```
-Missing partial blorgh/comments/comment with {:handlers=>[:erb, :builder],
+Missing partial blorgh/comments/_comment with {:handlers=>[:erb, :builder],
:formats=>[:html], :locale=>[:en, :en]}. Searched in: *
"/Users/ryan/Sites/side_projects/blorgh/test/dummy/app/views" *
"/Users/ryan/Sites/side_projects/blorgh/app/views"
@@ -591,7 +591,7 @@ Missing partial blorgh/comments/comment with {:handlers=>[:erb, :builder],
The engine is unable to find the partial required for rendering the comments.
Rails looks first in the application's (`test/dummy`) `app/views` directory and
then in the engine's `app/views` directory. When it can't find it, it will throw
-this error. The engine knows to look for `blorgh/comments/comment` because the
+this error. The engine knows to look for `blorgh/comments/_comment` because the
model object it is receiving is from the `Blorgh::Comment` class.
This partial will be responsible for rendering just the comment text, for now.
@@ -689,8 +689,8 @@ haven't been copied over already. The first run for this command will output
something such as this:
```bash
-Copied migration [timestamp_1]_create_blorgh_articles.rb from blorgh
-Copied migration [timestamp_2]_create_blorgh_comments.rb from blorgh
+Copied migration [timestamp_1]_create_blorgh_articles.blorgh.rb from blorgh
+Copied migration [timestamp_2]_create_blorgh_comments.blorgh.rb from blorgh
```
The first timestamp (`[timestamp_1]`) will be the current time, and the second
@@ -822,9 +822,9 @@ Notice that only _one_ migration was copied over here. This is because the first
two migrations were copied over the first time this command was run.
```
-NOTE Migration [timestamp]_create_blorgh_articles.rb from blorgh has been skipped. Migration with the same name already exists.
-NOTE Migration [timestamp]_create_blorgh_comments.rb from blorgh has been skipped. Migration with the same name already exists.
-Copied migration [timestamp]_add_author_id_to_blorgh_articles.rb from blorgh
+NOTE Migration [timestamp]_create_blorgh_articles.blorgh.rb from blorgh has been skipped. Migration with the same name already exists.
+NOTE Migration [timestamp]_create_blorgh_comments.blorgh.rb from blorgh has been skipped. Migration with the same name already exists.
+Copied migration [timestamp]_add_author_id_to_blorgh_articles.blorgh.rb from blorgh
```
Run the migration using:
diff --git a/guides/source/form_helpers.md b/guides/source/form_helpers.md
index 853227e2a1..8f7d97844e 100644
--- a/guides/source/form_helpers.md
+++ b/guides/source/form_helpers.md
@@ -291,8 +291,8 @@ You can create a similar binding without actually creating `<form>` tags with th
```erb
<%= form_for @person, url: {action: "create"} do |person_form| %>
<%= person_form.text_field :name %>
- <%= fields_for @person.contact_detail do |contact_details_form| %>
- <%= contact_details_form.text_field :phone_number %>
+ <%= fields_for @person.contact_detail do |contact_detail_form| %>
+ <%= contact_detail_form.text_field :phone_number %>
<% end %>
<% end %>
```
@@ -441,7 +441,7 @@ Whenever Rails sees that the internal value of an option being generated matches
TIP: The second argument to `options_for_select` must be exactly equal to the desired internal value. In particular if the value is the integer `2` you cannot pass `"2"` to `options_for_select` - you must pass `2`. Be aware of values extracted from the `params` hash as they are all strings.
-WARNING: when `:include_blank` or `:prompt` are not present, `:include_blank` is forced true if the select attribute `required` is true, display `size` is one and `multiple` is not true.
+WARNING: When `:include_blank` or `:prompt` are not present, `:include_blank` is forced true if the select attribute `required` is true, display `size` is one and `multiple` is not true.
You can add arbitrary attributes to the options using hashes:
diff --git a/guides/source/getting_started.md b/guides/source/getting_started.md
index 68ab454660..e64a788ac2 100644
--- a/guides/source/getting_started.md
+++ b/guides/source/getting_started.md
@@ -400,7 +400,7 @@ a controller called `ArticlesController`. You can do this by running this
command:
```bash
-$ bin/rails g controller articles
+$ bin/rails generate controller articles
```
If you open up the newly generated `app/controllers/articles_controller.rb`
@@ -1240,7 +1240,9 @@ article we want to show the form back to the user.
We reuse the `article_params` method that we defined earlier for the create
action.
-TIP: It is not necessary to pass all the attributes to `update`. For example, if `@article.update(title: 'A new title')` were called, Rails would only update the `title` attribute, leaving all other attributes untouched.
+TIP: It is not necessary to pass all the attributes to `update`. For example,
+if `@article.update(title: 'A new title')` was called, Rails would only update
+the `title` attribute, leaving all other attributes untouched.
Finally, we want to show a link to the `edit` action in the list of all the
articles, so let's add that now to `app/views/articles/index.html.erb` to make
@@ -1488,7 +1490,7 @@ appear.
![Confirm Dialog](images/getting_started/confirm_dialog.png)
TIP: Learn more about jQuery Unobtrusive Adapter (jQuery UJS) on
-[Working With Javascript in Rails](working_with_javascript_in_rails.html) guide.
+[Working With JavaScript in Rails](working_with_javascript_in_rails.html) guide.
Congratulations, you can now create, show, list, update and destroy
articles.
diff --git a/guides/source/i18n.md b/guides/source/i18n.md
index 51eaf4ba5a..31682464ee 100644
--- a/guides/source/i18n.md
+++ b/guides/source/i18n.md
@@ -216,8 +216,8 @@ 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:
@@ -500,7 +502,10 @@ You can make use of this feature, e.g. when working with a large amount of stati
### Organization of Locale Files
-When you are using the default SimpleStore shipped with the i18n library, dictionaries are stored in plain-text files on the disc. Putting translations for all parts of your application in one file per locale could be hard to manage. You can store these files in a hierarchy which makes sense to you.
+When you are using the default SimpleStore shipped with the i18n library,
+dictionaries are stored in plain-text files on the disk. Putting translations
+for all parts of your application in one file per locale could be hard to
+manage. You can store these files in a hierarchy which makes sense to you.
For example, your `config/locales` directory could look like this:
diff --git a/guides/source/initialization.md b/guides/source/initialization.md
index 199545a3b3..43083ebb86 100644
--- a/guides/source/initialization.md
+++ b/guides/source/initialization.md
@@ -53,11 +53,11 @@ require "rails/cli"
```
The file `railties/lib/rails/cli` in turn calls
-`Rails::AppRailsLoader.exec_app_rails`.
+`Rails::AppLoader.exec_app`.
-### `railties/lib/rails/app_rails_loader.rb`
+### `railties/lib/rails/app_loader.rb`
-The primary goal of the function `exec_app_rails` is to execute your app's
+The primary goal of the function `exec_app` is to execute your app's
`bin/rails`. If the current directory does not have a `bin/rails`, it will
navigate upwards until it finds a `bin/rails` executable. Thus one can invoke a
`rails` command from anywhere inside a rails application.
@@ -106,6 +106,7 @@ A standard Rails application depends on several gems, specifically:
* activemodel
* activerecord
* activesupport
+* activejob
* arel
* builder
* bundler
@@ -532,6 +533,7 @@ require "rails"
action_controller
action_view
action_mailer
+ active_job
rails/test_unit
sprockets
).each do |framework|
@@ -555,9 +557,8 @@ I18n and Rails configuration are all being defined here.
The rest of `config/application.rb` defines the configuration for the
`Rails::Application` which will be used once the application is fully
initialized. When `config/application.rb` has finished loading Rails and defined
-the application namespace, we go back to `config/environment.rb`,
-where the application is initialized. For example, if the application was called
-`Blog`, here we would find `Rails.application.initialize!`, which is
+the application namespace, we go back to `config/environment.rb`. Here, the
+application is initialized with `Rails.application.initialize!`, which is
defined in `rails/application.rb`.
### `railties/lib/rails/application.rb`
diff --git a/guides/source/kindle/welcome.html.erb b/guides/source/kindle/welcome.html.erb
index 610a71570f..ef3397f58f 100644
--- a/guides/source/kindle/welcome.html.erb
+++ b/guides/source/kindle/welcome.html.erb
@@ -2,4 +2,6 @@
<h3>Kindle Edition</h3>
-The Kindle Edition of the Rails Guides should be considered a work in progress. Feedback is really welcome. Please see the "Feedback" section at the end of each guide for instructions.
+<div>
+ The Kindle Edition of the Rails Guides should be considered a work in progress. Feedback is really welcome. Please see the "Feedback" section at the end of each guide for instructions.
+</div>
diff --git a/guides/source/layouts_and_rendering.md b/guides/source/layouts_and_rendering.md
index 737f392995..94cd7297e2 100644
--- a/guides/source/layouts_and_rendering.md
+++ b/guides/source/layouts_and_rendering.md
@@ -103,32 +103,6 @@ In most cases, the `ActionController::Base#render` method does the heavy lifting
TIP: If you want to see the exact results of a call to `render` without needing to inspect it in a browser, you can call `render_to_string`. This method takes exactly the same options as `render`, but it returns a string instead of sending a response back to the browser.
-#### Rendering Nothing
-
-Perhaps the simplest thing you can do with `render` is to render nothing at all:
-
-```ruby
-render nothing: true
-```
-
-If you look at the response for this using cURL, you will see the following:
-
-```bash
-$ curl -i 127.0.0.1:3000/books
-HTTP/1.1 200 OK
-Connection: close
-Date: Sun, 24 Jan 2010 09:25:18 GMT
-Transfer-Encoding: chunked
-Content-Type: */*; charset=utf-8
-X-Runtime: 0.014297
-Set-Cookie: _blog_session=...snip...; path=/; HttpOnly
-Cache-Control: no-cache
-```
-
-We see there is an empty response (no data after the `Cache-Control` line), but the request was successful because Rails has set the response to 200 OK. You can set the `:status` option on render to change this response. Rendering nothing can be useful for Ajax requests where all you want to send back to the browser is an acknowledgment that the request was completed.
-
-TIP: You should probably be using the `head` method, discussed later in this guide, instead of `render :nothing`. This provides additional flexibility and makes it explicit that you're only generating HTTP headers.
-
#### Rendering an Action's View
If you want to render the view that corresponds to a different template within the same controller, you can use `render` with the name of the view:
diff --git a/guides/source/nested_model_forms.md b/guides/source/nested_model_forms.md
index 1937369776..121cf2b185 100644
--- a/guides/source/nested_model_forms.md
+++ b/guides/source/nested_model_forms.md
@@ -106,7 +106,7 @@ Consider the following typical RESTful controller which will prepare a new Perso
class PeopleController < ApplicationController
def new
@person = Person.new
- @person.built_address
+ @person.build_address
2.times { @person.projects.build }
end
diff --git a/guides/source/rails_application_templates.md b/guides/source/rails_application_templates.md
index b3e1874048..b7364536c3 100644
--- a/guides/source/rails_application_templates.md
+++ b/guides/source/rails_application_templates.md
@@ -215,7 +215,7 @@ CODE
### yes?(question) or no?(question)
-These methods let you ask questions from templates and decide the flow based on the user's answer. Let's say you want to freeze rails only if the user wants to:
+These methods let you ask questions from templates and decide the flow based on the user's answer. Let's say you want to Freeze Rails only if the user wants to:
```ruby
rake("rails:freeze:gems") if yes?("Freeze rails gems?")
diff --git a/guides/source/rails_on_rack.md b/guides/source/rails_on_rack.md
index 993cd5ac44..117017af90 100644
--- a/guides/source/rails_on_rack.md
+++ b/guides/source/rails_on_rack.md
@@ -68,11 +68,10 @@ def middleware
end
```
-`Rails::Rack::Debugger` is primarily useful only in the development environment. The following table explains the usage of the loaded middlewares:
+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`
@@ -83,7 +82,6 @@ To use `rackup` instead of Rails' `rails server`, you can put the following insi
# Rails.root/config.ru
require ::File.expand_path('../config/environment', __FILE__)
-use Rails::Rack::Debugger
use Rack::ContentLength
run Rails.application
```
diff --git a/guides/source/routing.md b/guides/source/routing.md
index b1e4c8ad86..52f11f92bd 100644
--- a/guides/source/routing.md
+++ b/guides/source/routing.md
@@ -809,13 +809,16 @@ As long as `Sprockets` responds to `call` and returns a `[status, headers, body]
NOTE: For the curious, `'articles#index'` actually expands out to `ArticlesController.action(:index)`, which returns a valid Rack application.
-If you specify a rack application as the endpoint for a matcher remember that the route will be unchanged in the receiving application. With the following route your rack application should expect the route to be '/admin':
+If you specify a Rack application as the endpoint for a matcher, remember that
+the route will be unchanged in the receiving application. With the following
+route your Rack application should expect the route to be '/admin':
```ruby
match '/admin', to: AdminApp, via: :all
```
-If you would prefer to have your rack application receive requests at the root path instead use mount:
+If you would prefer to have your Rack application receive requests at the root
+path instead, use mount:
```ruby
mount AdminApp, at: '/admin'
diff --git a/guides/source/security.md b/guides/source/security.md
index 91d520e997..93580d4d4e 100644
--- a/guides/source/security.md
+++ b/guides/source/security.md
@@ -572,7 +572,7 @@ NOTE: _When sanitizing, protecting or verifying something, prefer whitelists ove
A blacklist can be a list of bad e-mail addresses, non-public actions or bad HTML tags. This is opposed to a whitelist which lists the good e-mail addresses, public actions, good HTML tags and so on. Although sometimes it is not possible to create a whitelist (in a SPAM filter, for example), _prefer to use whitelist approaches_:
-* Use before_action only: [...] instead of except: [...]. This way you don't forget to turn it off for newly added actions.
+* Use before_action except: [...] instead of only: [...] for security-related actions. This way you don't forget to enable security checks for newly added actions.
* Allow &lt;strong&gt; instead of removing &lt;script&gt; against Cross-Site Scripting (XSS). See below for details.
* Don't try to correct user input by blacklists:
* This will make the attack work: "&lt;sc&lt;script&gt;ript&gt;".gsub("&lt;script&gt;", "")
@@ -712,7 +712,7 @@ The log files on www.attacker.com will read like this:
GET http://www.attacker.com/_app_session=836c1c25278e5b321d6bea4f19cb57e2
```
-You can mitigate these attacks (in the obvious way) by adding the **httpOnly** flag to cookies, so that document.cookie may not be read by JavaScript. Http only cookies can be used from IE v6.SP1, Firefox v2.0.0.5 and Opera 9.5. Safari is still considering, it ignores the option. But other, older browsers (such as WebTV and IE 5.5 on Mac) can actually cause the page to fail to load. Be warned that cookies [will still be visible using Ajax](http://ha.ckers.org/blog/20070719/firefox-implements-httponly-and-is-vulnerable-to-xmlhttprequest/), though.
+You can mitigate these attacks (in the obvious way) by adding the **httpOnly** flag to cookies, so that document.cookie may not be read by JavaScript. Http only cookies can be used from IE v6.SP1, Firefox v2.0.0.5 and Opera 9.5. Safari is still considering, it ignores the option. But other, older browsers (such as WebTV and IE 5.5 on Mac) can actually cause the page to fail to load. Be warned that cookies [will still be visible using Ajax](https://www.owasp.org/index.php/HTTPOnly#Browsers_Supporting_HttpOnly), though.
##### Defacement
@@ -925,7 +925,7 @@ HTTP/1.1 200 OK [Second New response created by attacker begins]
Content-Type: text/html
-&lt;html&gt;&lt;font color=red&gt;hey&lt;/font&gt;&lt;/html&gt; [Arbitary malicious input is
+&lt;html&gt;&lt;font color=red&gt;hey&lt;/font&gt;&lt;/html&gt; [Arbitrary malicious input is
Keep-Alive: timeout=15, max=100 shown as the redirected page]
Connection: Keep-Alive
Transfer-Encoding: chunked
@@ -971,7 +971,7 @@ request:
| `{ "person": [null, null, ...] }` | `{ :person => [] }` |
| `{ "person": ["foo", null] }` | `{ :person => ["foo"] }` |
-It is possible to return to old behaviour and disable `deep_munge` configuring
+It is possible to return to old behavior and disable `deep_munge` configuring
your application if you are aware of the risk and know how to handle it:
```ruby
@@ -1033,4 +1033,5 @@ 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](http://ha.ckers.org/blog/) including the [Cross-Site scripting Cheat Sheet](http://ha.ckers.org/xss.html)
+* 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 cc469f4dae..2fd54a48fc 100644
--- a/guides/source/testing.md
+++ b/guides/source/testing.md
@@ -141,6 +141,13 @@ users(:david).id
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.
@@ -377,7 +384,7 @@ Notice the 'E' in the output. It denotes a test with error.
NOTE: The execution of each test method stops as soon as any error or an
assertion failure is encountered, and the test suite continues with the next
method. All test methods are executed in random order. The
-[`config.active_support.test_order` option](http://edgeguides.rubyonrails.org/configuring.html#configuring-active-support)
+[`config.active_support.test_order` option](configuring.html#configuring-active-support)
can be used to configure test order.
When a test fails you are presented with the corresponding backtrace. By default
@@ -435,7 +442,7 @@ specify to make your test failure messages clearer. It's not required.
| `assert_nothing_raised( exception1, exception2, ... ) { block }` | Ensures that the given block doesn't raise one of the given exceptions.|
| `assert_instance_of( class, obj, [msg] )` | Ensures that `obj` is an instance of `class`.|
| `assert_not_instance_of( class, obj, [msg] )` | Ensures that `obj` is not an instance of `class`.|
-| `assert_kind_of( class, obj, [msg] )` | Ensures that `obj` is or descends from `class`.|
+| `assert_kind_of( class, obj, [msg] )` | Ensures that `obj` is an instance of `class` or is descending from it.|
| `assert_not_kind_of( class, obj, [msg] )` | Ensures that `obj` is not an instance of `class` and is not descending from it.|
| `assert_respond_to( obj, symbol, [msg] )` | Ensures that `obj` responds to `symbol`.|
| `assert_not_respond_to( obj, symbol, [msg] )` | Ensures that `obj` does not respond to `symbol`.|
@@ -462,12 +469,11 @@ Rails adds some custom assertions of its own to the `minitest` framework:
| Assertion | Purpose |
| --------------------------------------------------------------------------------- | ------- |
| `assert_difference(expressions, difference = 1, message = nil) {...}` | Test numeric difference between the return value of an expression as a result of what is evaluated in the yielded block.|
-| `assert_no_difference(expressions, message = nil, &amp;block)` | Asserts that the numeric result of evaluating an expression is not changed before and after invoking the passed in block.|
+| `assert_no_difference(expressions, message = nil, &block)` | Asserts that the numeric result of evaluating an expression is not changed before and after invoking the passed in block.|
| `assert_recognizes(expected_options, path, extras={}, message=nil)` | Asserts that the routing of the given path was handled correctly and that the parsed options (given in the expected_options hash) match path. Basically, it asserts that Rails recognizes the route given by expected_options.|
| `assert_generates(expected_path, options, defaults={}, extras = {}, message=nil)` | Asserts that the provided options can be used to generate the provided path. This is the inverse of assert_recognizes. The extras parameter is used to tell the request the names and values of additional request parameters that would be in a query string. The message parameter allows you to specify a custom error message for assertion failures.|
| `assert_response(type, message = nil)` | Asserts that the response comes with a specific status code. You can specify `:success` to indicate 200-299, `:redirect` to indicate 300-399, `:missing` to indicate 404, or `:error` to match the 500-599 range. You can also pass an explicit status number or its symbolic equivalent. For more information, see [full list of status codes](http://rubydoc.info/github/rack/rack/master/Rack/Utils#HTTP_STATUS_CODES-constant) and how their [mapping](http://rubydoc.info/github/rack/rack/master/Rack/Utils#SYMBOL_TO_STATUS_CODE-constant) works.|
| `assert_redirected_to(options = {}, message=nil)` | Assert that the redirection options passed in match those of the redirect called in the latest action. This match can be partial, such that `assert_redirected_to(controller: "weblog")` will also match the redirection of `redirect_to(controller: "weblog", action: "show")` and so on. You can also pass named routes such as `assert_redirected_to root_path` and Active Record objects such as `assert_redirected_to @article`.|
-| `assert_template(expected = nil, message=nil)` | Asserts that the request was rendered with the appropriate template file.|
You'll see the usage of some of these assertions in the next chapter.
@@ -484,7 +490,7 @@ 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://ruby-doc.org/stdlib-2.1.0/libdoc/minitest/rdoc/MiniTest.html)
+NOTE: For more information on `Minitest`, refer to [Minitest](http://docs.seattlerb.org/minitest)
Functional Tests for Your Controllers
-------------------------------------
@@ -506,16 +512,18 @@ Now that we have used Rails scaffold generator for our `Article` resource, it ha
Let me take you through one such test, `test_should_get_index` from the file `articles_controller_test.rb`.
```ruby
+# articles_controller_test.rb
class ArticlesControllerTest < ActionController::TestCase
test "should get index" do
get :index
assert_response :success
- assert_not_nil assigns(:articles)
+ assert_includes @response.body, 'Articles'
end
end
```
-In the `test_should_get_index` test, Rails simulates a request on the action called `index`, making sure the request was successful and also ensuring that it assigns a valid `articles` instance variable.
+In the `test_should_get_index` test, Rails simulates a request on the action called `index`, making sure the request was successful
+and also ensuring that the right response body has been generated.
The `get` method kicks off the web request and populates the results into the response. It accepts 4 arguments:
@@ -553,7 +561,7 @@ test "should create article" do
post :create, params: { article: { title: 'Some title' } }
end
- assert_redirected_to article_path(assigns(:article))
+ assert_redirected_to article_path(Article.last)
end
```
@@ -580,11 +588,11 @@ To test AJAX requests, you can specify the `xhr: true` option to `get`, `post`,
`patch`, `put`, and `delete` methods:
```ruby
-test "ajax request responds with no layout" do
+test "ajax request" do
get :show, params: { id: articles(:first).id }, xhr: true
- assert_template :index
- assert_template layout: nil
+ assert_equal 'hello world', @response.body
+ assert_equal "text/javascript", @response.content_type
end
```
@@ -592,20 +600,16 @@ end
After a request has been made and processed, you will have 4 Hash objects ready for use:
-* `assigns` - Any objects that are stored as instance variables in actions for use in views.
* `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, except for `assigns`. For example:
+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:
```ruby
flash["gordon"] flash[:gordon]
session["shmession"] session[:shmession]
cookies["are_good_for_u"] cookies[:are_good_for_u]
-
-# Because you can't use assigns[:something] for historical reasons:
-assigns["something"] assigns(:something)
```
### Instance Variables Available
@@ -633,46 +637,6 @@ get :index # simulate the request with custom header
post :create # simulate the request with custom env variable
```
-### Testing Templates and Layouts
-
-Eventually, you may want to test whether a specific layout is rendered in the view of a response.
-
-#### Asserting Templates
-
-If you want to make sure that the response rendered the correct template and layout, you can use the `assert_template`
-method:
-
-```ruby
-test "index should render correct template and layout" do
- get :index
- assert_template :index
- assert_template layout: "layouts/application"
-
- # You can also pass a regular expression.
- assert_template layout: /layouts\/application/
-end
-```
-
-NOTE: You cannot test for template and layout at the same time, with a single call to `assert_template`.
-
-WARNING: You must include the "layouts" directory name even if you save your layout file in this standard layout directory. Hence, `assert_template layout: "application"` will not work.
-
-#### Asserting Partials
-
-If your view renders any partial, when asserting for the layout, you can to assert for the partial at the same time.
-Otherwise, assertion will fail.
-
-Remember, we added the "_form" partial to our new Article view? Let's write an assertion for that in the `:new` action now:
-
-```ruby
-test "new should render correct layout" do
- get :new
- assert_template layout: "layouts/application", partial: "_form"
-end
-```
-
-This is the correct way to assert for when the view renders a partial with a given name. As identified by the `:partial` key passed to the `assert_template` call.
-
### Testing `flash` notices
If you remember from earlier one of the Four Hashes of the Apocalypse was `flash`.
@@ -688,7 +652,7 @@ test "should create article" do
post :create, params: { article: { title: 'Some title' } }
end
- assert_redirected_to article_path(assigns(:article))
+ assert_redirected_to article_path(Article.last)
assert_equal 'Article was successfully created.', flash[:notice]
end
```
@@ -781,7 +745,7 @@ We can also add a test for updating an existing Article.
test "should update article" do
article = articles(:one)
patch :update, params: { id: article.id, article: { title: "updated" } }
- assert_redirected_to article_path(assigns(:article))
+ assert_redirected_to article_path(article)
end
```
@@ -820,7 +784,7 @@ class ArticlesControllerTest < ActionController::TestCase
test "should update article" do
patch :update, params: { id: @article.id, article: { title: "updated" } }
- assert_redirected_to article_path(assigns(:article))
+ assert_redirected_to article_path(@article)
end
end
```
@@ -857,7 +821,6 @@ class ProfileControllerTest < ActionController::TestCase
get :show
assert_response :success
- assert_equal users(:david), assigns(:user)
end
end
```
@@ -898,7 +861,7 @@ For more information on routing assertions available in Rails, see the API docum
Testing Views
-------------
-Testing the response to your request by asserting the presence of key HTML elements and their content is a common way to test the views of your application. The `assert_select` method allows you to query HTML elements of the response by using a simple yet powerful syntax.
+Testing the response to your request by asserting the presence of key HTML elements and their content is a common way to test the views of your application. Like route tests, view tests reside in `test/controllers/` or are part of controller tests. The `assert_select` method allows you to query HTML elements of the response by using a simple yet powerful syntax.
There are two forms of `assert_select`:
@@ -1071,14 +1034,12 @@ How about testing our ability to create a new article in our blog and see the re
test "can create an article" do
get "/articles/new"
assert_response :success
- assert_template "articles/new", partial: "articles/_form"
post "/articles",
params: { article: { title: "can create", body: "article successfully." } }
assert_response :redirect
follow_redirect!
assert_response :success
- assert_template "articles/show"
assert_select "p", "Title:\n can create"
end
```
diff --git a/guides/source/upgrading_ruby_on_rails.md b/guides/source/upgrading_ruby_on_rails.md
index 49834fa8a2..17309d4b47 100644
--- a/guides/source/upgrading_ruby_on_rails.md
+++ b/guides/source/upgrading_ruby_on_rails.md
@@ -460,7 +460,7 @@ If your application currently depend on MultiJSON directly, you have a few optio
WARNING: Do not simply replace `MultiJson.dump` and `MultiJson.load` with
`JSON.dump` and `JSON.load`. These JSON gem APIs are meant for serializing and
-deserializing arbitrary Ruby objects and are generally [unsafe](http://www.ruby-doc.org/stdlib-2.0.0/libdoc/json/rdoc/JSON.html#method-i-load).
+deserializing arbitrary Ruby objects and are generally [unsafe](http://www.ruby-doc.org/stdlib-2.2.2/libdoc/json/rdoc/JSON.html#method-i-load).
#### JSON gem compatibility
@@ -926,7 +926,7 @@ Rails 4.0 extracted Active Resource to its own gem. If you still need the featur
Please note that you should wait to set `secret_key_base` until you have 100% of your userbase on Rails 4.x and are reasonably sure you will not need to rollback to Rails 3.x. This is because cookies signed based on the new `secret_key_base` in Rails 4.x are not backwards compatible with Rails 3.x. You are free to leave your existing `secret_token` in place, not set the new `secret_key_base`, and ignore the deprecation warnings until you are reasonably sure that your upgrade is otherwise complete.
-If you are relying on the ability for external applications or Javascript to be able to read your Rails app's signed session cookies (or signed cookies in general) you should not set `secret_key_base` until you have decoupled these concerns.
+If you are relying on the ability for external applications or JavaScript to be able to read your Rails app's signed session cookies (or signed cookies in general) you should not set `secret_key_base` until you have decoupled these concerns.
* Rails 4.0 encrypts the contents of cookie-based sessions if `secret_key_base` has been set. Rails 3.x signed, but did not encrypt, the contents of cookie-based session. Signed cookies are "secure" in that they are verified to have been generated by your app and are tamper-proof. However, the contents can be viewed by end users, and encrypting the contents eliminates this caveat/concern without a significant performance penalty.
@@ -940,6 +940,8 @@ Please read [Pull Request #9978](https://github.com/rails/rails/pull/9978) for d
* Rails 4.0 has removed the XML parameters parser. You will need to add the `actionpack-xml_parser` gem if you require this feature.
+* Rails 4.0 changes the default `layout` lookup set using symbols or procs that return nil. To get the "no layout" behavior, return false instead of nil.
+
* Rails 4.0 changes the default memcached client from `memcache-client` to `dalli`. To upgrade, simply add `gem 'dalli'` to your `Gemfile`.
* Rails 4.0 deprecates the `dom_id` and `dom_class` methods in controllers (they are fine in views). You will need to include the `ActionView::RecordIdentifier` module in controllers requiring this feature.
diff --git a/guides/source/working_with_javascript_in_rails.md b/guides/source/working_with_javascript_in_rails.md
index e3856a285a..f3d3a83afc 100644
--- a/guides/source/working_with_javascript_in_rails.md
+++ b/guides/source/working_with_javascript_in_rails.md
@@ -191,34 +191,6 @@ $(document).ready ->
Obviously, you'll want to be a bit more sophisticated than that, but it's a
start. You can see more about the events [in the jquery-ujs wiki](https://github.com/rails/jquery-ujs/wiki/ajax).
-Another possibility is returning javascript directly from the server side on
-remote calls:
-
-```ruby
-# articles_controller
-def create
- respond_to do |format|
- if @article.save
- format.html { ... }
- format.js do
- render js: <<-endjs
- alert('Article saved successfully!');
- window.location = '#{article_path(@article)}';
- endjs
- end
- else
- format.html { ... }
- format.js do
- render js: "alert('There are empty fields in the form!');"
- end
- end
- end
-end
-```
-
-NOTE: If javascript is disabled in the user browser, `format.html { ... }`
-block should be executed as fallback.
-
### form_tag
[`form_tag`](http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html#method-i-form_tag)