aboutsummaryrefslogtreecommitdiffstats
path: root/guides
diff options
context:
space:
mode:
Diffstat (limited to 'guides')
-rw-r--r--guides/CHANGELOG.md12
-rw-r--r--guides/assets/images/belongs_to.pngbin26076 -> 25803 bytes
-rw-r--r--guides/assets/images/getting_started/rails_welcome.pngbin142320 -> 1053549 bytes
-rw-r--r--guides/assets/images/has_many.pngbin28988 -> 28919 bytes
-rw-r--r--guides/assets/images/rails_guides_logo.gifbin5106 -> 3770 bytes
-rw-r--r--[-rwxr-xr-x]guides/assets/javascripts/responsive-tables.js0
-rw-r--r--guides/bug_report_templates/action_controller_master.rb5
-rw-r--r--guides/bug_report_templates/active_record_master.rb5
-rw-r--r--guides/bug_report_templates/generic_master.rb8
-rw-r--r--guides/rails_guides/markdown/renderer.rb2
-rw-r--r--guides/source/4_2_release_notes.md2
-rw-r--r--guides/source/5_0_release_notes.md790
-rw-r--r--guides/source/action_controller_overview.md12
-rw-r--r--guides/source/action_mailer_basics.md20
-rw-r--r--guides/source/action_view_overview.md4
-rw-r--r--guides/source/active_job_basics.md14
-rw-r--r--guides/source/active_model_basics.md2
-rw-r--r--guides/source/active_record_callbacks.md2
-rw-r--r--guides/source/active_record_migrations.md18
-rw-r--r--guides/source/active_record_postgresql.md6
-rw-r--r--guides/source/active_record_querying.md78
-rw-r--r--guides/source/active_record_validations.md2
-rw-r--r--guides/source/active_support_core_extensions.md22
-rw-r--r--guides/source/api_app.md118
-rw-r--r--guides/source/asset_pipeline.md56
-rw-r--r--guides/source/association_basics.md480
-rw-r--r--guides/source/caching_with_rails.md8
-rw-r--r--guides/source/command_line.md134
-rw-r--r--guides/source/configuring.md101
-rw-r--r--guides/source/contributing_to_ruby_on_rails.md11
-rw-r--r--guides/source/debugging_rails_applications.md20
-rw-r--r--guides/source/development_dependencies_install.md2
-rw-r--r--guides/source/documents.yaml4
-rw-r--r--guides/source/engines.md32
-rw-r--r--guides/source/form_helpers.md2
-rw-r--r--guides/source/getting_started.md74
-rw-r--r--guides/source/i18n.md4
-rw-r--r--guides/source/initialization.md21
-rw-r--r--guides/source/layout.html.erb11
-rw-r--r--guides/source/layouts_and_rendering.md18
-rw-r--r--guides/source/maintenance_policy.md6
-rw-r--r--guides/source/plugins.md101
-rw-r--r--guides/source/rails_application_templates.md26
-rw-r--r--guides/source/rails_on_rack.md14
-rw-r--r--guides/source/routing.md27
-rw-r--r--guides/source/security.md8
-rw-r--r--guides/source/testing.md160
-rw-r--r--guides/source/upgrading_ruby_on_rails.md33
-rw-r--r--guides/source/working_with_javascript_in_rails.md18
49 files changed, 1783 insertions, 710 deletions
diff --git a/guides/CHANGELOG.md b/guides/CHANGELOG.md
index 09fb7b1a0e..d35d0f1976 100644
--- a/guides/CHANGELOG.md
+++ b/guides/CHANGELOG.md
@@ -1,3 +1,15 @@
+## Rails 5.0.0.beta3 (February 24, 2016) ##
+
+* No changes.
+
+
+## Rails 5.0.0.beta2 (February 01, 2016) ##
+
+* No changes.
+
+
+## Rails 5.0.0.beta1 (December 18, 2015) ##
+
* Add code of conduct to contributing guide
*Jon Moss*
diff --git a/guides/assets/images/belongs_to.png b/guides/assets/images/belongs_to.png
index 43c963ffa8..077d237e4e 100644
--- a/guides/assets/images/belongs_to.png
+++ b/guides/assets/images/belongs_to.png
Binary files differ
diff --git a/guides/assets/images/getting_started/rails_welcome.png b/guides/assets/images/getting_started/rails_welcome.png
index 4d0cb417b7..baccb11322 100644
--- a/guides/assets/images/getting_started/rails_welcome.png
+++ b/guides/assets/images/getting_started/rails_welcome.png
Binary files differ
diff --git a/guides/assets/images/has_many.png b/guides/assets/images/has_many.png
index e7589e3b75..79da2613d7 100644
--- a/guides/assets/images/has_many.png
+++ b/guides/assets/images/has_many.png
Binary files differ
diff --git a/guides/assets/images/rails_guides_logo.gif b/guides/assets/images/rails_guides_logo.gif
index 9b0ad5af28..f7149a0415 100644
--- a/guides/assets/images/rails_guides_logo.gif
+++ b/guides/assets/images/rails_guides_logo.gif
Binary files differ
diff --git a/guides/assets/javascripts/responsive-tables.js b/guides/assets/javascripts/responsive-tables.js
index 8554a1343b..8554a1343b 100755..100644
--- a/guides/assets/javascripts/responsive-tables.js
+++ b/guides/assets/javascripts/responsive-tables.js
diff --git a/guides/bug_report_templates/action_controller_master.rb b/guides/bug_report_templates/action_controller_master.rb
index 3f24aa3b4d..8322707495 100644
--- a/guides/bug_report_templates/action_controller_master.rb
+++ b/guides/bug_report_templates/action_controller_master.rb
@@ -8,11 +8,6 @@ end
gemfile(true) do
source 'https://rubygems.org'
gem 'rails', github: 'rails/rails'
- gem 'arel', github: 'rails/arel'
- gem 'rack', github: 'rack/rack'
- gem 'sprockets', github: 'rails/sprockets'
- gem 'sprockets-rails', github: 'rails/sprockets-rails'
- gem 'sass-rails', github: 'rails/sass-rails'
end
require 'action_controller/railtie'
diff --git a/guides/bug_report_templates/active_record_master.rb b/guides/bug_report_templates/active_record_master.rb
index 5b742a9093..a86edd9121 100644
--- a/guides/bug_report_templates/active_record_master.rb
+++ b/guides/bug_report_templates/active_record_master.rb
@@ -8,11 +8,6 @@ end
gemfile(true) do
source 'https://rubygems.org'
gem 'rails', github: 'rails/rails'
- gem 'arel', github: 'rails/arel'
- gem 'rack', github: 'rack/rack'
- gem 'sprockets', github: 'rails/sprockets'
- gem 'sprockets-rails', github: 'rails/sprockets-rails'
- gem 'sass-rails', github: 'rails/sass-rails'
gem 'sqlite3'
end
diff --git a/guides/bug_report_templates/generic_master.rb b/guides/bug_report_templates/generic_master.rb
index 0a8048cc48..70cf931f34 100644
--- a/guides/bug_report_templates/generic_master.rb
+++ b/guides/bug_report_templates/generic_master.rb
@@ -8,20 +8,12 @@ end
gemfile(true) do
source 'https://rubygems.org'
gem 'rails', github: 'rails/rails'
- gem 'arel', github: 'rails/arel'
- gem 'rack', github: 'rack/rack'
- gem 'sprockets', github: 'rails/sprockets'
- gem 'sprockets-rails', github: 'rails/sprockets-rails'
- gem 'sass-rails', github: 'rails/sass-rails'
end
require 'active_support'
require 'active_support/core_ext/object/blank'
require 'minitest/autorun'
-# Ensure backward compatibility with Minitest 4
-Minitest::Test = MiniTest::Unit::TestCase unless defined?(Minitest::Test)
-
class BugTest < Minitest::Test
def test_stuff
assert "zomg".present?
diff --git a/guides/rails_guides/markdown/renderer.rb b/guides/rails_guides/markdown/renderer.rb
index 554d94ad50..73ca600361 100644
--- a/guides/rails_guides/markdown/renderer.rb
+++ b/guides/rails_guides/markdown/renderer.rb
@@ -16,7 +16,7 @@ HTML
end
def header(text, header_level)
- # Always increase the heading level by, so we can use h1, h2 heading in the document
+ # Always increase the heading level by 1, so we can use h1, h2 heading in the document
header_level += 1
%(<h#{header_level}>#{text}</h#{header_level}>)
diff --git a/guides/source/4_2_release_notes.md b/guides/source/4_2_release_notes.md
index 8a59007420..73e6c2c05b 100644
--- a/guides/source/4_2_release_notes.md
+++ b/guides/source/4_2_release_notes.md
@@ -405,7 +405,7 @@ Please refer to the [Changelog][railties] for detailed changes.
url: http://localhost:3001
namespace: my_app_development
- # config/production.rb
+ # config/environments/production.rb
Rails.application.configure do
config.middleware.use ExceptionNotifier, config_for(:exception_notification)
end
diff --git a/guides/source/5_0_release_notes.md b/guides/source/5_0_release_notes.md
new file mode 100644
index 0000000000..dc631e5cb9
--- /dev/null
+++ b/guides/source/5_0_release_notes.md
@@ -0,0 +1,790 @@
+**DO NOT READ THIS FILE ON GITHUB, GUIDES ARE PUBLISHED ON http://guides.rubyonrails.org.**
+
+Ruby on Rails 5.0 Release Notes
+===============================
+
+Highlights in Rails 5.0:
+
+* Action Cable
+* Rails API
+* Active Record Attributes API
+* Test Runner
+* Exclusive use of `rails` CLI over Rake
+* Sprockets 3
+* Turbolinks 5
+* Ruby 2.2.2+ required
+
+These release notes cover only the major changes. To learn about various bug
+fixes and changes, please refer to the change logs or check out the [list of
+commits](https://github.com/rails/rails/commits/5-0-stable) in the main Rails
+repository on GitHub.
+
+--------------------------------------------------------------------------------
+
+Upgrading to Rails 5.0
+----------------------
+
+If you're upgrading an existing application, it's a great idea to have good test
+coverage before going in. You should also first upgrade to Rails 4.2 in case you
+haven't and make sure your application still runs as expected before attempting
+an update to Rails 5.0. A list of things to watch out for when upgrading is
+available in the
+[Upgrading Ruby on Rails](upgrading_ruby_on_rails.html#upgrading-from-rails-4-2-to-rails-5-0)
+guide.
+
+
+Major Features
+--------------
+
+### Action Cable
+[Pull Request](https://github.com/rails/rails/pull/22586)
+
+ToDo...
+
+### Rails API
+[Pull Request](https://github.com/rails/rails/pull/19832)
+
+ToDo...
+
+### Active Record attributes API
+
+ToDo...
+
+### Test Runner
+[Pull Request](https://github.com/rails/rails/pull/19216)
+
+ToDo...
+
+
+Railties
+--------
+
+Please refer to the [Changelog][railties] for detailed changes.
+
+### Removals
+
+* Removed debugger support, use byebug instead. `debugger` is not supported by
+ Ruby
+ 2.2. ([commit](https://github.com/rails/rails/commit/93559da4826546d07014f8cfa399b64b4a143127))
+
+* Removed deprecated `test:all` and `test:all:db` tasks.
+ ([commit](https://github.com/rails/rails/commit/f663132eef0e5d96bf2a58cec9f7c856db20be7c))
+
+* Removed deprecated `Rails::Rack::LogTailer`.
+ ([commit](https://github.com/rails/rails/commit/c564dcb75c191ab3d21cc6f920998b0d6fbca623))
+
+* Removed deprecated `RAILS_CACHE` constant.
+ ([commit](https://github.com/rails/rails/commit/b7f856ce488ef8f6bf4c12bb549f462cb7671c08))
+
+* Removed deprecated `serve_static_assets` configuration.
+ ([commit](https://github.com/rails/rails/commit/463b5d7581ee16bfaddf34ca349b7d1b5878097c))
+
+* Removed the documentation tasks `doc:app`, `doc:rails`, and `doc:guides`.
+ ([commit](https://github.com/rails/rails/commit/cd7cc5254b090ccbb84dcee4408a5acede25ef2a))
+
+* Removed `Rack::ContentLength` middleware from the default
+ stack. ([Commit](https://github.com/rails/rails/commit/56903585a099ab67a7acfaaef0a02db8fe80c450))
+
+### Deprecations
+
+* Deprecated `config.static_cache_control` in favor of
+ `config.public_file_server.headers`.
+ ([Pull Request](https://github.com/rails/rails/pull/22173))
+
+* Deprecated `config.serve_static_files` in favor of `config.public_file_server.enabled`.
+ ([Pull Request](https://github.com/rails/rails/pull/22173))
+
+### Notable changes
+
+* Added Rails test runner `bin/rails test`.
+ ([Pull Request](https://github.com/rails/rails/pull/19216))
+
+* Newly generated applications and plugins get a `README.md` in Markdown.
+ ([commit](https://github.com/rails/rails/commit/89a12c931b1f00b90e74afffcdc2fc21f14ca663),
+ [Pull Request](https://github.com/rails/rails/pull/22068))
+
+* Added `bin/rails restart` task to restart your Rails app by touching `tmp/restart.txt`.
+ ([Pull Request](https://github.com/rails/rails/pull/18965))
+
+* Added `bin/rails initializers` task to print out all defined initializers in
+ the order they are invoked by Rails.
+ ([Pull Request](https://github.com/rails/rails/pull/19323))
+
+* Added `bin/rails dev:cache` to enable or disable caching in development mode.
+ ([Pull Request](https://github.com/rails/rails/pull/20961))
+
+* Added `bin/update` script to update the development environment automatically.
+ ([Pull Request](https://github.com/rails/rails/pull/20972))
+
+* Proxy Rake tasks through `bin/rails`.
+ ([Pull Request](https://github.com/rails/rails/pull/22457),
+ [Pull Request](https://github.com/rails/rails/pull/22288))
+
+
+Action Pack
+-----------
+
+Please refer to the [Changelog][action-pack] for detailed changes.
+
+### Removals
+
+* Removed `ActionDispatch::Request::Utils.deep_munge`.
+ ([commit](https://github.com/rails/rails/commit/52cf1a71b393486435fab4386a8663b146608996))
+
+* Removed `ActionController::HideActions`.
+ ([Pull Request](https://github.com/rails/rails/pull/18371))
+
+* Removed `respond_to` and `respond_with` placeholder methods, this functionality
+ has been extracted to the
+ [responders](https://github.com/plataformatec/responders) gem.
+ ([commit](https://github.com/rails/rails/commit/afd5e9a7ff0072e482b0b0e8e238d21b070b6280))
+
+* Removed deprecated assertion files.
+ ([commit](https://github.com/rails/rails/commit/92e27d30d8112962ee068f7b14aa7b10daf0c976))
+
+* Removed deprecated usage of string keys in URL helpers.
+ ([commit](https://github.com/rails/rails/commit/34e380764edede47f7ebe0c7671d6f9c9dc7e809))
+
+* Removed deprecated `only_path` option on `*_path` helpers.
+ ([commit](https://github.com/rails/rails/commit/e4e1fd7ade47771067177254cb133564a3422b8a))
+
+* Removed deprecated `NamedRouteCollection#helpers`.
+ ([commit](https://github.com/rails/rails/commit/2cc91c37bc2e32b7a04b2d782fb8f4a69a14503f))
+
+* Removed deprecated support to define routes with `:to` option that doesn't contain `#`.
+ ([commit](https://github.com/rails/rails/commit/1f3b0a8609c00278b9a10076040ac9c90a9cc4a6))
+
+* Removed deprecated `ActionDispatch::Response#to_ary`.
+ ([commit](https://github.com/rails/rails/commit/4b19d5b7bcdf4f11bd1e2e9ed2149a958e338c01))
+
+* Removed deprecated `ActionDispatch::Request#deep_munge`.
+ ([commit](https://github.com/rails/rails/commit/7676659633057dacd97b8da66e0d9119809b343e))
+
+* Removed deprecated
+ `ActionDispatch::Http::Parameters#symbolized_path_parameters`.
+ ([commit](https://github.com/rails/rails/commit/7fe7973cd8bd119b724d72c5f617cf94c18edf9e))
+
+* Removed deprecated option `use_route` in controller tests.
+ ([commit](https://github.com/rails/rails/commit/e4cfd353a47369dd32198b0e67b8cbb2f9a1c548))
+
+* Removed `assigns` and `assert_template`. Both methods have been extracted
+ into the
+ [rails-controller-testing](https://github.com/rails/rails-controller-testing)
+ gem.
+ ([Pull Request](https://github.com/rails/rails/pull/20138))
+
+### Deprecations
+
+* Deprecated all `*_filter` callbacks in favor of `*_action` callbacks.
+ ([Pull Request](https://github.com/rails/rails/pull/18410))
+
+* Deprecated `*_via_redirect` integration test methods. Use `follow_redirect!`
+ manually after the request call for the same behavior.
+ ([Pull Request](https://github.com/rails/rails/pull/18693))
+
+* Deprecated `AbstractController#skip_action_callback` in favor of individual
+ skip_callback methods.
+ ([Pull Request](https://github.com/rails/rails/pull/19060))
+
+* Deprecated `:nothing` option for `render` method.
+ ([Pull Request](https://github.com/rails/rails/pull/20336))
+
+* Deprecated passing first parameter as `Hash` and default status code for
+ `head` method.
+ ([Pull Request](https://github.com/rails/rails/pull/20407))
+
+* Deprecated using strings or symbols for middleware class names. Use class
+ names instead.
+ ([commit](https://github.com/rails/rails/commit/83b767ce))
+
+* Deprecated accessing mime types via constants (eg. `Mime::HTML`). Use the
+ subscript operator with a symbol instead (eg. `Mime[:html]`).
+ ([Pull Request](https://github.com/rails/rails/pull/21869))
+
+* Deprecated `redirect_to :back` in favor of `redirect_back`, which accepts a
+ required `fallback_location` argument, thus eliminating the possibility of a
+ `RedirectBackError`.
+ ([Pull Request](https://github.com/rails/rails/pull/22506))
+
+### Notable changes
+
+* Added `ActionController::Renderer` to render arbitrary templates
+ outside controller actions.
+ ([Pull Request](https://github.com/rails/rails/pull/18546))
+
+* Migrating to keyword arguments syntax in `ActionController::TestCase` and
+ `ActionDispatch::Integration` HTTP request methods.
+ ([Pull Request](https://github.com/rails/rails/pull/18323))
+
+* Added `http_cache_forever` to Action Controller, so we can cache a response
+ that never gets expired.
+ ([Pull Request](https://github.com/rails/rails/pull/18394))
+
+* Provide friendlier access to request variants.
+ ([Pull Request](https://github.com/rails/rails/pull/18939))
+
+* For actions with no corresponding templates, render `head :no_content`
+ instead of raising an error.
+ ([Pull Request](https://github.com/rails/rails/pull/19377))
+
+* Added the ability to override default form builder for a controller.
+ ([Pull Request](https://github.com/rails/rails/pull/19736))
+
+* Added support for API only apps.
+ `ActionController::API` is added as a replacement of
+ `ActionController::Base` for this kind of applications.
+ ([Pull Request](https://github.com/rails/rails/pull/19832))
+
+* Make `ActionController::Parameters` no longer inherits from
+ `HashWithIndifferentAccess`.
+ ([Pull Request](https://github.com/rails/rails/pull/20868))
+
+* Make it easier to opt in to `config.force_ssl` and `config.ssl_options` by
+ making them less dangerous to try and easier to disable.
+ ([Pull Request](https://github.com/rails/rails/pull/21520))
+
+* Added the ability of returning arbitrary headers to `ActionDispatch::Static`.
+ ([Pull Request](https://github.com/rails/rails/pull/19135))
+
+* Changed the `protect_from_forgery` prepend default to `false`.
+ ([commit](https://github.com/rails/rails/commit/39794037817703575c35a75f1961b01b83791191))
+
+* `ActionController::TestCase` will be moved to it's own gem in Rails 5.1. Use
+ `ActionDispatch::IntegrationTest` instead.
+ ([commit](https://github.com/rails/rails/commit/4414c5d1795e815b102571425974a8b1d46d932d))
+
+* Rails will only generate "weak", instead of strong ETags.
+ ([Pull Request](https://github.com/rails/rails/pull/17573))
+
+* Controller actions without an explicit `render` call and with no
+ corresponding templates will render `head :no_content` implicitly
+ instead of raising an error.
+ (Pull Request [1](https://github.com/rails/rails/pull/19377),
+ [2](https://github.com/rails/rails/pull/23827))
+
+Action View
+-------------
+
+Please refer to the [Changelog][action-view] for detailed changes.
+
+### Removals
+
+* Removed deprecated `AbstractController::Base::parent_prefixes`.
+ ([commit](https://github.com/rails/rails/commit/34bcbcf35701ca44be559ff391535c0dd865c333))
+
+* Removed `ActionView::Helpers::RecordTagHelper`, this functionality
+ has been extracted to the
+ [record_tag_helper](https://github.com/rails/record_tag_helper) gem.
+ ([Pull Request](https://github.com/rails/rails/pull/18411))
+
+* Removed `:rescue_format` option for `translate` helper since it's no longer
+ supported by I18n.
+ ([Pull Request](https://github.com/rails/rails/pull/20019))
+
+### Notable Changes
+
+* Changed the default template handler from `ERB` to `Raw`.
+ ([commit](https://github.com/rails/rails/commit/4be859f0fdf7b3059a28d03c279f03f5938efc80))
+
+* Collection rendering automatically caches and fetches multiple partials.
+ ([Pull Request](https://github.com/rails/rails/pull/18948))
+
+* Allow defining explicit collection caching using a `# Template Collection: ...`
+ directive inside templates.
+ ([Pull Request](https://github.com/rails/rails/pull/20781))
+
+* Added wildcard matching to explicit dependencies.
+ ([Pull Request](https://github.com/rails/rails/pull/20904))
+
+* Make `disable_with` the default behavior for submit tags. Disables the
+ button on submit to prevent double submits.
+ ([Pull Request](https://github.com/rails/rails/pull/21135))
+
+* Downcase model name in form submit tags rather than humanize.
+ ([Pull Request](https://github.com/rails/rails/pull/22764))
+
+
+Action Mailer
+-------------
+
+Please refer to the [Changelog][action-mailer] for detailed changes.
+
+### Removals
+
+* Removed deprecated `*_path` helpers in email views.
+ ([commit](https://github.com/rails/rails/commit/d282125a18c1697a9b5bb775628a2db239142ac7))
+
+* Removed deprecated `deliver` and `deliver!` methods.
+ ([commit](https://github.com/rails/rails/commit/755dcd0691f74079c24196135f89b917062b0715))
+
+### Notable changes
+
+* Template lookup now respects default locale and I18n fallbacks.
+ ([commit](https://github.com/rails/rails/commit/ecb1981b))
+
+* Template can use fragment cache like Action View template.
+ ([Pull Request](https://github.com/rails/rails/pull/22825))
+
+* Added `_mailer` suffix to mailers created via generator, following the same
+ naming convention used in controllers and jobs.
+ ([Pull Request](https://github.com/rails/rails/pull/18074))
+
+* Added `assert_enqueued_emails` and `assert_no_enqueued_emails`.
+ ([Pull Request](https://github.com/rails/rails/pull/18403))
+
+* Added `config.action_mailer.deliver_later_queue_name` configuration to set
+ the mailer queue name.
+ ([Pull Request](https://github.com/rails/rails/pull/18587))
+
+* Added `config.action_mailer.perform_caching` configuration to determine whether your templates should perform caching or not.
+ ([Pull Request](https://github.com/rails/rails/pull/22825))
+
+
+Active Record
+-------------
+
+Please refer to the [Changelog][active-record] for detailed changes.
+
+### Removals
+
+* Removed deprecated behavior allowing nested arrays to be passed as query
+ values. ([Pull Request](https://github.com/rails/rails/pull/17919))
+
+* Removed deprecated `ActiveRecord::Tasks::DatabaseTasks#load_schema`. This
+ method was replaced by `ActiveRecord::Tasks::DatabaseTasks#load_schema_for`.
+ ([commit](https://github.com/rails/rails/commit/ad783136d747f73329350b9bb5a5e17c8f8800da))
+
+* Removed deprecated `serialized_attributes`.
+ ([commit](https://github.com/rails/rails/commit/82043ab53cb186d59b1b3be06122861758f814b2))
+
+* Removed deprecated automatic counter caches on `has_many :through`.
+ ([commit](https://github.com/rails/rails/commit/87c8ce340c6c83342df988df247e9035393ed7a0))
+
+* Removed deprecated `sanitize_sql_hash_for_conditions`.
+ ([commit](https://github.com/rails/rails/commit/3a59dd212315ebb9bae8338b98af259ac00bbef3))
+
+* Removed deprecated `Reflection#source_macro`.
+ ([commit](https://github.com/rails/rails/commit/ede8c199a85cfbb6457d5630ec1e285e5ec49313))
+
+* Removed deprecated `symbolized_base_class` and `symbolized_sti_name`.
+ ([commit](https://github.com/rails/rails/commit/9013e28e52eba3a6ffcede26f85df48d264b8951))
+
+* Removed deprecated `ActiveRecord::Base.disable_implicit_join_references=`.
+ ([commit](https://github.com/rails/rails/commit/0fbd1fc888ffb8cbe1191193bf86933110693dfc))
+
+* Removed deprecated access to connection specification using a string accessor.
+ ([commit](https://github.com/rails/rails/commit/efdc20f36ccc37afbb2705eb9acca76dd8aabd4f))
+
+* Removed deprecated support to preload instance-dependent associations.
+ ([commit](https://github.com/rails/rails/commit/4ed97979d14c5e92eb212b1a629da0a214084078))
+
+* Removed deprecated support for PostgreSQL ranges with exclusive lower bounds.
+ ([commit](https://github.com/rails/rails/commit/a076256d63f64d194b8f634890527a5ed2651115))
+
+* Removed deprecation when modifying a relation with cached Arel.
+ This raises an `ImmutableRelation` error instead.
+ ([commit](https://github.com/rails/rails/commit/3ae98181433dda1b5e19910e107494762512a86c))
+
+* Removed `ActiveRecord::Serialization::XmlSerializer` from core. This feature
+ has been extracted into the
+ [activemodel-serializers-xml](https://github.com/rails/activemodel-serializers-xml)
+ gem. ([Pull Request](https://github.com/rails/rails/pull/21161))
+
+* Removed support for the legacy `mysql` database adapter from core. It will
+ live on in a separate gem for now, but most users should just use `mysql2`.
+
+* Removed support for the `protected_attributes` gem.
+ ([commit](https://github.com/rails/rails/commit/f4fbc0301021f13ae05c8e941c8efc4ae351fdf9))
+
+* Removed support for PostgreSQL versions below 9.1.
+ ([Pull Request](https://github.com/rails/rails/pull/23434))
+
+### Deprecations
+
+* Deprecated passing a class as a value in a query. Users should pass strings
+ instead. ([Pull Request](https://github.com/rails/rails/pull/17916))
+
+* Deprecated returning `false` as a way to halt Active Record callback
+ chains. The recommended way is to
+ `throw(:abort)`. ([Pull Request](https://github.com/rails/rails/pull/17227))
+
+* Deprecated `ActiveRecord::Base.errors_in_transactional_callbacks=`.
+ ([commit](https://github.com/rails/rails/commit/07d3d402341e81ada0214f2cb2be1da69eadfe72))
+
+* Deprecated passing of `start` value to `find_in_batches` and `find_each`
+ in favour of `begin_at` value.
+ ([Pull Request](https://github.com/rails/rails/pull/18961))
+
+* Deprecated `Relation#uniq` use `Relation#distinct` instead.
+ ([commit](https://github.com/rails/rails/commit/adfab2dcf4003ca564d78d4425566dd2d9cd8b4f))
+
+* Deprecated the PostgreSQL `:point` type in favor of a new one which will return
+ `Point` objects instead of an `Array`
+ ([Pull Request](https://github.com/rails/rails/pull/20448))
+
+* Deprecated force association reload by passing a truthy argument to
+ association method.
+ ([Pull Request](https://github.com/rails/rails/pull/20888))
+
+* Deprecated the keys for association `restrict_dependent_destroy` errors in favor
+ of new key names.
+ ([Pull Request](https://github.com/rails/rails/pull/20668))
+
+* Synchronize behavior of `#tables`.
+ ([Pull Request](https://github.com/rails/rails/pull/21601))
+
+* Deprecated `SchemaCache#tables`, `SchemaCache#table_exists?` and
+ `SchemaCache#clear_table_cache!` in favor of their new data source
+ counterparts.
+ ([Pull Request](https://github.com/rails/rails/pull/21715))
+
+* Deprecated `connection.tables` on the SQLite3 and MySQL adapters.
+ ([Pull Request](https://github.com/rails/rails/pull/21601))
+
+* Deprecated passing arguments to `#tables` - the `#tables` method of some
+ adapters (mysql2, sqlite3) would return both tables and views while others
+ (postgresql) just return tables. To make their behavior consistent,
+ `#tables` will return only tables in the future.
+ ([Pull Request](https://github.com/rails/rails/pull/21601))
+
+* Deprecated `table_exists?` - The `#table_exists?` method would check both
+ tables and views. To make their behavior consistent with `#tables`,
+ `#table_exists?` will check only tables in the future.
+ ([Pull Request](https://github.com/rails/rails/pull/21601))
+
+* Deprecate sending the `offset` argument to `find_nth`. Please use the
+ `offset` method on relation instead.
+ ([Pull Request](https://github.com/rails/rails/pull/22053))
+
+### Notable changes
+
+* Added a `foreign_key` option to `references` while creating the table.
+ ([commit](https://github.com/rails/rails/commit/99a6f9e60ea55924b44f894a16f8de0162cf2702))
+
+* New attributes
+ API. ([commit](https://github.com/rails/rails/commit/8c752c7ac739d5a86d4136ab1e9d0142c4041e58))
+
+* Added `:enum_prefix`/`:enum_suffix` option to `enum`
+ definition. ([Pull Request](https://github.com/rails/rails/pull/19813))
+
+* Added `#cache_key` to `ActiveRecord::Relation`.
+ ([Pull Request](https://github.com/rails/rails/pull/20884))
+
+* Added `ActiveRecord::Relation#outer_joins`.
+ ([Pull Request](https://github.com/rails/rails/pull/12071))
+
+* Require `belongs_to` by default.
+ ([Pull Request](https://github.com/rails/rails/pull/18937)) - Deprecate
+ `required` option in favor of `optional` for `belongs_to`
+
+* Changed the default `null` value for `timestamps` to `false`.
+ ([commit](https://github.com/rails/rails/commit/a939506f297b667291480f26fa32a373a18ae06a))
+
+* Added `ActiveRecord::SecureToken` in order to encapsulate generation of
+ unique tokens for attributes in a model using `SecureRandom`.
+ ([Pull Request](https://github.com/rails/rails/pull/18217))
+
+* Added `:if_exists` option for `drop_table`.
+ ([Pull Request](https://github.com/rails/rails/pull/18597))
+
+* Added `ActiveRecord::Base#accessed_fields`, which can be used to quickly
+ discover which fields were read from a model when you are looking to only
+ select the data you need from the database.
+ ([commit](https://github.com/rails/rails/commit/be9b68038e83a617eb38c26147659162e4ac3d2c))
+
+* Added the `#or` method on `ActiveRecord::Relation`, allowing use of the OR
+ operator to combine WHERE or HAVING clauses.
+ ([commit](https://github.com/rails/rails/commit/b0b37942d729b6bdcd2e3178eda7fa1de203b3d0))
+
+* Added `:time` option added for `#touch`.
+ ([Pull Request](https://github.com/rails/rails/pull/18956))
+
+* Added `ActiveRecord::Base.suppress` to prevent the receiver from being saved
+ during the given block.
+ ([Pull Request](https://github.com/rails/rails/pull/18910))
+
+* `belongs_to` will now trigger a validation error by default if the
+ association is not present. You can turn this off on a per-association basis
+ with `optional: true`.
+ ([Pull Request](https://github.com/rails/rails/pull/18937))
+
+* Added `config.active_record.dump_schemas` to configure the behavior of
+ `db:structure:dump`.
+ ([Pull Request](https://github.com/rails/rails/pull/19347))
+
+* Added `config.active_record.warn_on_records_fetched_greater_than` option.
+ ([Pull Request](https://github.com/rails/rails/pull/18846))
+
+* Added a native JSON data type support in MySQL.
+ ([Pull Request](https://github.com/rails/rails/pull/21110))
+
+* Added support for dropping indexes concurrently in PostgreSQL.
+ ([Pull Request](https://github.com/rails/rails/pull/21317))
+
+* Added `#views` and `#view_exists?` methods on connection adapters.
+ ([Pull Request](https://github.com/rails/rails/pull/21609))
+
+* Added `ActiveRecord::Base.ignored_columns` to make some columns
+ invisible from Active Record.
+ ([Pull Request](https://github.com/rails/rails/pull/21720))
+
+* Added `connection.data_sources` and `connection.data_source_exists?`.
+ These methods determine what relations can be used to back Active Record
+ models (usually tables and views).
+ ([Pull Request](https://github.com/rails/rails/pull/21715))
+
+* Allow fixtures files to set the model class in the YAML file itself.
+ ([Pull Request](https://github.com/rails/rails/pull/20574))
+
+* Added ability to default to `uuid` as primary key when generating database
+ migrations. ([Pull Request](https://github.com/rails/rails/pull/21762))
+
+* Added `ActiveRecord::Relation#left_joins` and
+ `ActiveRecord::Relation#left_outer_joins`.
+ ([Pull Request](https://github.com/rails/rails/pull/12071))
+
+* Added `after_{create,update,delete}_commit` callbacks.
+ ([Pull Request](https://github.com/rails/rails/pull/22516))
+
+* Version the API presented to migration classes, so we can change parameter
+ defaults without breaking existing migrations, or forcing them to be
+ rewritten through a deprecation cycle.
+ ([Pull Request](https://github.com/rails/rails/pull/21538))
+
+* `ApplicationRecord` is a new superclass for all app models, analogous to app
+ controllers subclassing `ApplicationController` instead of
+ `ActionController::Base`. This gives apps a single spot to configure app-wide
+ model behavior.
+ ([Pull Request](https://github.com/rails/rails/pull/22567))
+
+
+Active Model
+------------
+
+Please refer to the [Changelog][active-model] for detailed changes.
+
+### Removals
+
+* Removed deprecated `ActiveModel::Dirty#reset_#{attribute}` and
+ `ActiveModel::Dirty#reset_changes`.
+ ([Pull Request](https://github.com/rails/rails/commit/37175a24bd508e2983247ec5d011d57df836c743))
+
+* Removed XML serialization. This feature has been extracted into the
+ [activemodel-serializers-xml](https://github.com/rails/activemodel-serializers-xml) gem.
+ ([Pull Request](https://github.com/rails/rails/pull/21161))
+
+### Deprecations
+
+* Deprecated returning `false` as a way to halt Active Model and
+ `ActiveModel::Validations` callback chains. The recommended way is to
+ `throw(:abort)`. ([Pull Request](https://github.com/rails/rails/pull/17227))
+
+* Deprecated `ActiveModel::Errors#get`, `ActiveModel::Errors#set` and
+ `ActiveModel::Errors#[]=` methods that have inconsistent behavior.
+ ([Pull Request](https://github.com/rails/rails/pull/18634))
+
+* Deprecated the `:tokenizer` option for `validates_length_of`, in favor of
+ plain Ruby.
+ ([Pull Request](https://github.com/rails/rails/pull/19585))
+
+* Deprecated `ActiveModel::Errors#add_on_empty` and `ActiveModel::Errors#add_on_blank`
+ with no replacement.
+ ([Pull Request](https://github.com/rails/rails/pull/18996))
+
+### Notable changes
+
+* Added `ActiveModel::Errors#details` to determine what validator has failed.
+ ([Pull Request](https://github.com/rails/rails/pull/18322))
+
+* Extracted `ActiveRecord::AttributeAssignment` to `ActiveModel::AttributeAssignment`
+ allowing to use it for any object as an includable module.
+ ([Pull Request](https://github.com/rails/rails/pull/10776))
+
+* Added `ActiveModel::Dirty#[attr_name]_previously_changed?` and
+ `ActiveModel::Dirty#[attr_name]_previous_change` to improve access
+ to recorded changes after the model has been saved.
+ ([Pull Request](https://github.com/rails/rails/pull/19847))
+
+* Validate multiple contexts on `valid?` and `invalid?` at once.
+ ([Pull Request](https://github.com/rails/rails/pull/21069))
+
+
+Active Job
+-----------
+
+Please refer to the [Changelog][active-job] for detailed changes.
+
+### Notable changes
+
+* `ActiveJob::Base.deserialize` delegates to the job class. this allows jobs
+ to attach arbitrary metadata when they get serialized and read it back when
+ they get performed.
+ ([Pull Request](https://github.com/rails/rails/pull/18260))
+
+* A generated job now inherits from `app/jobs/application_job.rb` by default.
+ ([Pull Request](https://github.com/rails/rails/pull/19034))
+
+* Allow `DelayedJob`, `Sidekiq`, `qu`, and `que` to report the job id back to
+ `ActiveJob::Base` as `provider_job_id`.
+ ([Pull Request](https://github.com/rails/rails/pull/20064),
+ [Pull Request](https://github.com/rails/rails/pull/20056))
+
+* Implement a simple `AsyncJob` processor and associated `AsyncAdapter` that
+ queue jobs to a `concurrent-ruby` thread pool.
+ ([Pull Request](https://github.com/rails/rails/pull/21257))
+
+
+Active Support
+--------------
+
+Please refer to the [Changelog][active-support] for detailed changes.
+
+### Removals
+
+* Removed deprecated `ActiveSupport::JSON::Encoding::CircularReferenceError`.
+ ([commit](https://github.com/rails/rails/commit/d6e06ea8275cdc3f126f926ed9b5349fde374b10))
+
+* Removed deprecated methods `ActiveSupport::JSON::Encoding.encode_big_decimal_as_string=`
+ and `ActiveSupport::JSON::Encoding.encode_big_decimal_as_string`.
+ ([commit](https://github.com/rails/rails/commit/c8019c0611791b2716c6bed48ef8dcb177b7869c))
+
+* Removed deprecated `ActiveSupport::SafeBuffer#prepend`.
+ ([commit](https://github.com/rails/rails/commit/e1c8b9f688c56aaedac9466a4343df955b4a67ec))
+
+* Removed deprecated methods from `Kernel`. `silence_stderr`, `silence_stream`,
+ `capture` and `quietly`.
+ ([commit](https://github.com/rails/rails/commit/481e49c64f790e46f4aff3ed539ed227d2eb46cb))
+
+* Removed deprecated `active_support/core_ext/big_decimal/yaml_conversions`
+ file.
+ ([commit](https://github.com/rails/rails/commit/98ea19925d6db642731741c3b91bd085fac92241))
+
+* Removed deprecated methods `ActiveSupport::Cache::Store.instrument` and
+ `ActiveSupport::Cache::Store.instrument=`.
+ ([commit](https://github.com/rails/rails/commit/a3ce6ca30ed0e77496c63781af596b149687b6d7))
+
+* Removed deprecated `Class#superclass_delegating_accessor`.
+ Use `Class#class_attribute` instead.
+ ([Pull Request](https://github.com/rails/rails/pull/16938))
+
+* Removed deprecated `ThreadSafe::Cache`. Use `Concurrent::Map` instead.
+ ([Pull Request](https://github.com/rails/rails/pull/21679))
+
+### Deprecations
+
+* Deprecated `MissingSourceFile` in favor of `LoadError`.
+ ([commit](https://github.com/rails/rails/commit/734d97d2))
+
+* Deprecated `alias_method_chain` in favour of `Module#prepend` introduced in
+ Ruby 2.0.
+ ([Pull Request](https://github.com/rails/rails/pull/19434))
+
+* Deprecated `ActiveSupport::Concurrency::Latch` in favor of
+ `Concurrent::CountDownLatch` from concurrent-ruby.
+ ([Pull Request](https://github.com/rails/rails/pull/20866))
+
+* Deprecated `:prefix` option of `number_to_human_size` with no replacement.
+ ([Pull Request](https://github.com/rails/rails/pull/21191))
+
+* Deprecated `Module#qualified_const_` in favour of the builtin
+ `Module#const_` methods.
+ ([Pull Request](https://github.com/rails/rails/pull/17845))
+
+* Deprecated passing string to define callback.
+ ([Pull Request](https://github.com/rails/rails/pull/22598))
+
+* Deprecated `ActiveSupport::Cache::Store#namespaced_key`,
+ `ActiveSupport::Cache::MemCachedStore#escape_key`, and
+ `ActiveSupport::Cache::FileStore#key_file_path`.
+ Use `normalize_key` instead.
+
+ Deprecated `ActiveSupport::Cache::LocaleCache#set_cache_value` in favor of `write_cache_value`.
+ ([Pull Request](https://github.com/rails/rails/pull/22215))
+
+### Notable changes
+
+* Added `#verified` and `#valid_message?` methods to
+ `ActiveSupport::MessageVerifier`.
+ ([Pull Request](https://github.com/rails/rails/pull/17727))
+
+* Changed the way in which callback chains can be halted. The preferred method
+ to halt a callback chain from now on is to explicitly `throw(:abort)`.
+ ([Pull Request](https://github.com/rails/rails/pull/17227))
+
+* New config option
+ `config.active_support.halt_callback_chains_on_return_false` to specify
+ whether ActiveRecord, ActiveModel and ActiveModel::Validations callback
+ chains can be halted by returning `false` in a 'before' callback.
+ ([Pull Request](https://github.com/rails/rails/pull/17227))
+
+* Changed the default test order from `:sorted` to `:random`.
+ ([commit](https://github.com/rails/rails/commit/5f777e4b5ee2e3e8e6fd0e2a208ec2a4d25a960d))
+
+* Added `#on_weekend?`, `#on_weekday?`, `#next_weekday`, `#prev_weekday` methods to `Date`,
+ `Time`, and `DateTime`.
+ ([Pull Request](https://github.com/rails/rails/pull/18335))
+
+* Added `same_time` option to `#next_week` and `#prev_week` for `Date`, `Time`,
+ and `DateTime`.
+ ([Pull Request](https://github.com/rails/rails/pull/18335))
+
+* Added `#prev_day` and `#next_day` counterparts to `#yesterday` and
+ `#tomorrow` for `Date`, `Time`, and `DateTime`.
+ ([Pull Request](httpshttps://github.com/rails/rails/pull/18335))
+
+* Added `SecureRandom.base58` for generation of random base58 strings.
+ ([commit](https://github.com/rails/rails/commit/b1093977110f18ae0cafe56c3d99fc22a7d54d1b))
+
+* Added `file_fixture` to `ActiveSupport::TestCase`.
+ It provides a simple mechanism to access sample files in your test cases.
+ ([Pull Request](https://github.com/rails/rails/pull/18658))
+
+* Added `#without` on `Enumerable` and `Array` to return a copy of an
+ enumerable without the specified elements.
+ ([Pull Request](https://github.com/rails/rails/pull/19157))
+
+* Added `ActiveSupport::ArrayInquirer` and `Array#inquiry`.
+ ([Pull Request](https://github.com/rails/rails/pull/18939))
+
+* Added `ActiveSupport::TimeZone#strptime` to allow parsing times as if
+ from a given timezone.
+ ([commit](https://github.com/rails/rails/commit/a5e507fa0b8180c3d97458a9b86c195e9857d8f6))
+
+* Added `Integer#positive?` and `Integer#negative?` query methods
+ in the vein of `Fixnum#zero?`.
+ ([commit](https://github.com/rails/rails/commit/e54277a45da3c86fecdfa930663d7692fd083daa))
+
+* Added a bang version to `ActiveSupport::OrderedOptions` get methods which will raise
+ an `KeyError` if the value is `.blank?`.
+ ([Pull Request](https://github.com/rails/rails/pull/20208))
+
+* Added `Time.days_in_year` to return the number of days in the given year, or the
+ current year if no argument is provided.
+ ([commit](https://github.com/rails/rails/commit/2f4f4d2cf1e4c5a442459fc250daf66186d110fa))
+
+* Added an evented file watcher to asynchronously detect changes in the
+ application source code, routes, locales, etc.
+ ([Pull Request](https://github.com/rails/rails/pull/22254))
+
+* Added thread_m/cattr_accessor/reader/writer suite of methods for declaring
+ class and module variables that live per-thread.
+ ([Pull Request](https://github.com/rails/rails/pull/22630))
+
+
+Credits
+-------
+
+See the
+[full list of contributors to Rails](http://contributors.rubyonrails.org/) for
+the many people who spent many hours making Rails, the stable and robust
+framework it is. Kudos to all of them.
+
+[railties]: https://github.com/rails/rails/blob/5-0-stable/railties/CHANGELOG.md
+[action-pack]: https://github.com/rails/rails/blob/5-0-stable/actionpack/CHANGELOG.md
+[action-view]: https://github.com/rails/rails/blob/5-0-stable/actionview/CHANGELOG.md
+[action-mailer]: https://github.com/rails/rails/blob/5-0-stable/actionmailer/CHANGELOG.md
+[action-cable]: https://github.com/rails/rails/blob/5-0-stable/actioncable/CHANGELOG.md
+[active-record]: https://github.com/rails/rails/blob/5-0-stable/activerecord/CHANGELOG.md
+[active-model]: https://github.com/rails/rails/blob/5-0-stable/activemodel/CHANGELOG.md
+[active-support]: https://github.com/rails/rails/blob/5-0-stable/activesupport/CHANGELOG.md
+[active-job]: https://github.com/rails/rails/blob/5-0-stable/activejob/CHANGELOG.md
diff --git a/guides/source/action_controller_overview.md b/guides/source/action_controller_overview.md
index d2e2d27737..9ef2c1a441 100644
--- a/guides/source/action_controller_overview.md
+++ b/guides/source/action_controller_overview.md
@@ -995,10 +995,6 @@ you would like in a response object. The `ActionController::Live` module allows
you to create a persistent connection with a browser. Using this module, you will
be able to send arbitrary data to the browser at specific points in time.
-NOTE: The default Rails server (WEBrick) is a buffering web server and does not
-support streaming. In order to use this feature, you'll need to use a non buffering
-server like [Puma](http://puma.io), [Rainbows](http://rainbows.bogomips.org)
-or [Passenger](https://www.phusionpassenger.com).
#### Incorporating Live Streaming
@@ -1118,7 +1114,7 @@ Rails default exception handling displays a "500 Server Error" message for all e
### The Default 500 and 404 Templates
-By default a production application will render either a 404 or a 500 error message. These messages are contained in static HTML files in the `public` folder, in `404.html` and `500.html` respectively. You can customize these files to add some extra information and style, but remember that they are static HTML; i.e. you can't use ERB, SCSS, CoffeeScript, or layouts for them.
+By default a production application will render either a 404 or a 500 error message, in the development environment all unhandled exceptions are raised. These messages are contained in static HTML files in the `public` folder, in `404.html` and `500.html` respectively. You can customize these files to add some extra information and style, but remember that they are static HTML; i.e. you can't use ERB, SCSS, CoffeeScript, or layouts for them.
### `rescue_from`
@@ -1174,7 +1170,11 @@ end
WARNING: You shouldn't do `rescue_from Exception` or `rescue_from StandardError` unless you have a particular reason as it will cause serious side-effects (e.g. you won't be able to see exception details and tracebacks during development).
-NOTE: Certain exceptions are only rescuable from the `ApplicationController` class, as they are raised before the controller gets initialized and the action gets executed.
+NOTE: When running in the production environment, all
+`ActiveRecord::RecordNotFound` errors render the 404 error page. Unless you need
+a custom behavior you don't need to handle this.
+
+NOTE: Certain exceptions are only rescuable from the `ApplicationController` class, as they are raised before the controller gets initialized and the action gets executed.
Force HTTPS protocol
--------------------
diff --git a/guides/source/action_mailer_basics.md b/guides/source/action_mailer_basics.md
index cd2c13e8c1..558c16f5b0 100644
--- a/guides/source/action_mailer_basics.md
+++ b/guides/source/action_mailer_basics.md
@@ -222,7 +222,7 @@ class SendWeeklySummary
end
```
-The method `welcome_email` returns a `ActionMailer::MessageDelivery` object which
+The method `welcome_email` returns an `ActionMailer::MessageDelivery` object which
can then just be told `deliver_now` or `deliver_later` to send itself out. The
`ActionMailer::MessageDelivery` object is just a wrapper around a `Mail::Message`. If
you want to inspect, alter or do anything else with the `Mail::Message` object you can
@@ -278,7 +278,7 @@ different, encode your content and pass in the encoded content and encoding in a
```ruby
encoded_content = SpecialEncode(File.read('/path/to/filename.jpg'))
attachments['filename.jpg'] = {
- mime_type: 'application/x-gzip',
+ mime_type: 'application/gzip',
encoding: 'SpecialEncoding',
content: encoded_content
}
@@ -407,6 +407,22 @@ use the rendered text for the text part. The render command is the same one used
inside of Action Controller, so you can use all the same options, such as
`:text`, `:inline` etc.
+#### Caching mailer view
+
+You can do cache in mailer views like in application views using `cache` method.
+
+```
+<% cache do %>
+ <%= @company.name %>
+<% end %>
+```
+
+And in order to use this feature, you need to configure your application with this:
+
+```
+ config.action_mailer.perform_caching = true
+```
+
### Action Mailer Layouts
Just like controller views, you can also have mailer layouts. The layout name
diff --git a/guides/source/action_view_overview.md b/guides/source/action_view_overview.md
index d9037674ca..29e0943741 100644
--- a/guides/source/action_view_overview.md
+++ b/guides/source/action_view_overview.md
@@ -599,7 +599,7 @@ This would add something like "Process data files (0.34523)" to the log, which y
#### cache
-A method for caching fragments of a view rather than an entire action or page. This technique is useful caching pieces like menus, lists of news topics, static HTML fragments, and so on. This method takes a block that contains the content you wish to cache. See `ActionController::Caching::Fragments` for more information.
+A method for caching fragments of a view rather than an entire action or page. This technique is useful for caching pieces like menus, lists of news topics, static HTML fragments, and so on. This method takes a block that contains the content you wish to cache. See `AbstractController::Caching::Fragments` for more information.
```erb
<% cache do %>
@@ -1524,7 +1524,7 @@ Localized Views
Action View has the ability to render different templates depending on the current locale.
-For example, suppose you have a `ArticlesController` with a show action. By default, calling this action will render `app/views/articles/show.html.erb`. But if you set `I18n.locale = :de`, then `app/views/articles/show.de.html.erb` will be rendered instead. If the localized template isn't present, the undecorated version will be used. This means you're not required to provide localized views for all cases, but they will be preferred and used if available.
+For example, suppose you have an `ArticlesController` with a show action. By default, calling this action will render `app/views/articles/show.html.erb`. But if you set `I18n.locale = :de`, then `app/views/articles/show.de.html.erb` will be rendered instead. If the localized template isn't present, the undecorated version will be used. This means you're not required to provide localized views for all cases, but they will be preferred and used if available.
You can use the same technique to localize the rescue files in your public directory. For example, setting `I18n.locale = :de` and creating `public/500.de.html` and `public/404.de.html` would allow you to have localized rescue pages.
diff --git a/guides/source/active_job_basics.md b/guides/source/active_job_basics.md
index e36c0f899f..d8ea1ee079 100644
--- a/guides/source/active_job_basics.md
+++ b/guides/source/active_job_basics.md
@@ -109,10 +109,12 @@ That's it!
Job Execution
-------------
-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.
+For enqueuing and executing jobs in production 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 only provides an in-process queuing system, which only keeps the jobs in RAM.
+If the process crashes or the machine is reset, then all outstanding jobs are lost with the
+default async back-end. This may be fine for smaller apps or non-critical jobs, but most
+production apps will need to pick a persistent backend.
### Backends
@@ -174,7 +176,7 @@ module YourApp
end
end
-# app/jobs/guests_cleanup.rb
+# app/jobs/guests_cleanup_job.rb
class GuestsCleanupJob < ActiveJob::Base
queue_as :low_priority
#....
@@ -197,7 +199,7 @@ module YourApp
end
end
-# app/jobs/guests_cleanup.rb
+# app/jobs/guests_cleanup_job.rb
class GuestsCleanupJob < ActiveJob::Base
queue_as :low_priority
#....
diff --git a/guides/source/active_model_basics.md b/guides/source/active_model_basics.md
index c05e20aceb..a8199e5d02 100644
--- a/guides/source/active_model_basics.md
+++ b/guides/source/active_model_basics.md
@@ -319,7 +319,7 @@ person.serializable_hash # => {"name"=>"Bob"}
#### ActiveModel::Serializers
-Rails provides a `ActiveModel::Serializers::JSON` serializer.
+Rails provides an `ActiveModel::Serializers::JSON` serializer.
This module automatically include the `ActiveModel::Serialization`.
##### ActiveModel::Serializers::JSON
diff --git a/guides/source/active_record_callbacks.md b/guides/source/active_record_callbacks.md
index d95c6c0e78..fb5d2065d3 100644
--- a/guides/source/active_record_callbacks.md
+++ b/guides/source/active_record_callbacks.md
@@ -258,7 +258,7 @@ As you start registering new callbacks for your models, they will be queued for
The whole callback chain is wrapped in a transaction. If any _before_ callback method returns exactly `false` or raises an exception, the execution chain gets halted and a ROLLBACK is issued; _after_ callbacks can only accomplish that by raising an exception.
-WARNING. Any exception that is not `ActiveRecord::Rollback` will be re-raised by Rails after the callback chain is halted. Raising an exception other than `ActiveRecord::Rollback` may break code that does not expect methods like `save` and `update_attributes` (which normally try to return `true` or `false`) to raise an exception.
+WARNING. Any exception that is not `ActiveRecord::Rollback` or `ActiveRecord::RecordInvalid` will be re-raised by Rails after the callback chain is halted. Raising an exception other than `ActiveRecord::Rollback` or `ActiveRecord::RecordInvalid` may break code that does not expect methods like `save` and `update_attributes` (which normally try to return `true` or `false`) to raise an exception.
Relational Callbacks
--------------------
diff --git a/guides/source/active_record_migrations.md b/guides/source/active_record_migrations.md
index a4a23395fb..bd7dbd0f11 100644
--- a/guides/source/active_record_migrations.md
+++ b/guides/source/active_record_migrations.md
@@ -12,7 +12,7 @@ After reading this guide, you will know:
* The generators you can use to create them.
* The methods Active Record provides to manipulate your database.
-* The Rake tasks that manipulate migrations and your schema.
+* The bin/rails tasks that manipulate migrations and your schema.
* How migrations relate to `schema.rb`.
--------------------------------------------------------------------------------
@@ -717,9 +717,9 @@ you will have to use `structure.sql` as dump method. See
Running Migrations
------------------
-Rails provides a set of Rake tasks to run certain sets of migrations.
+Rails provides a set of bin/rails tasks to run certain sets of migrations.
-The very first migration related Rake task you will use will probably be
+The very first migration related bin/rails task you will use will probably be
`rails db:migrate`. In its most basic form it just runs the `change` or `up`
method for all the migrations that have not yet been run. If there are
no such migrations, it exits. It will run these migrations in order based
@@ -772,7 +772,7 @@ if you need to go more than one version back, for example:
$ bin/rails db:migrate:redo STEP=3
```
-Neither of these Rake tasks do anything you could not do with `db:migrate`. They
+Neither of these bin/rails tasks do anything you could not do with `db:migrate`. They
are simply more convenient, since you do not need to explicitly specify the
version to migrate to.
@@ -784,7 +784,7 @@ it with the seed data.
### Resetting the Database
The `rails db:reset` task will drop the database and set it up again. This is
-functionally equivalent to `rake db:drop db:setup`.
+functionally equivalent to `rails db:drop db:setup`.
NOTE: This is not the same as running all the migrations. It will only use the
contents of the current `db/schema.rb` or `db/structure.sql` file. If a migration can't be rolled back,
@@ -809,7 +809,7 @@ Active Record believes that it has already been run.
### Running Migrations in Different Environments
-By default running `rake db:migrate` will run in the `development` environment.
+By default running `bin/rails db:migrate` will run in the `development` environment.
To run migrations against another environment you can specify it using the
`RAILS_ENV` environment variable while running the command. For example to run
migrations against the `test` environment you could run:
@@ -883,10 +883,10 @@ Changing Existing Migrations
----------------------------
Occasionally you will make a mistake when writing a migration. If you have
-already run the migration then you cannot just edit the migration and run the
+already run the migration, then you cannot just edit the migration and run the
migration again: Rails thinks it has already run the migration and so will do
nothing when you run `rails db:migrate`. You must rollback the migration (for
-example with `rake db:rollback`), edit your migration and then run
+example with `bin/rails db:rollback`), edit your migration and then run
`rails db:migrate` to run the corrected version.
In general, editing existing migrations is not a good idea. You will be
@@ -933,7 +933,7 @@ There are two ways to dump the schema. This is set in `config/application.rb`
by the `config.active_record.schema_format` setting, which may be either `:sql`
or `:ruby`.
-If `:ruby` is selected then the schema is stored in `db/schema.rb`. If you look
+If `:ruby` is selected, then the schema is stored in `db/schema.rb`. If you look
at this file you'll find that it looks an awful lot like one very big
migration:
diff --git a/guides/source/active_record_postgresql.md b/guides/source/active_record_postgresql.md
index b592209d4b..5eb19f5214 100644
--- a/guides/source/active_record_postgresql.md
+++ b/guides/source/active_record_postgresql.md
@@ -14,7 +14,7 @@ After reading this guide, you will know:
--------------------------------------------------------------------------------
-In order to use the PostgreSQL adapter you need to have at least version 8.2
+In order to use the PostgreSQL adapter you need to have at least version 9.1
installed. Older versions are not supported.
To get started with PostgreSQL have a look at the
@@ -84,6 +84,7 @@ Book.where("array_length(ratings, 1) >= 3")
### Hstore
* [type definition](http://www.postgresql.org/docs/current/static/hstore.html)
+* [functions and operators](http://www.postgresql.org/docs/current/static/hstore.html#AEN167712)
NOTE: You need to enable the `hstore` extension to use hstore.
@@ -108,6 +109,9 @@ profile.settings # => {"color"=>"blue", "resolution"=>"800x600"}
profile.settings = {"color" => "yellow", "resolution" => "1280x1024"}
profile.save!
+
+Profile.where("settings->'color' = ?", "yellow")
+#=> #<ActiveRecord::Relation [#<Profile id: 1, settings: {"color"=>"yellow", "resolution"=>"1280x1024"}>]>
```
### JSON
diff --git a/guides/source/active_record_querying.md b/guides/source/active_record_querying.md
index 4606ac4683..af15d4870c 100644
--- a/guides/source/active_record_querying.md
+++ b/guides/source/active_record_querying.md
@@ -11,7 +11,7 @@ After reading this guide, you will know:
* How to specify the order, retrieved attributes, grouping, and other properties of the found records.
* How to use eager loading to reduce the number of database queries needed for data retrieval.
* How to use dynamic finder methods.
-* How to use method chaining to use multiple ActiveRecord methods together.
+* How to use method chaining to use multiple Active Record methods together.
* How to check for the existence of particular records.
* How to perform various calculations on Active Record models.
* How to run EXPLAIN on relations.
@@ -59,7 +59,7 @@ To retrieve objects from the database, Active Record provides several finder met
The methods are:
-* `bind`
+* `find`
* `create_with`
* `distinct`
* `eager_load`
@@ -170,7 +170,7 @@ TIP: The retrieved record may vary depending on the database engine.
#### `first`
-The `first` method finds the first record ordered by the primary key. For example:
+The `first` method finds the first record ordered by primary key (default). For example:
```ruby
client = Client.first
@@ -204,11 +204,24 @@ The SQL equivalent of the above is:
SELECT * FROM clients ORDER BY clients.id ASC LIMIT 3
```
+On a collection that is ordered using `order`, `first` will return the first record ordered by the specified attribute for `order`.
+
+```ruby
+client = Client.order(:first_name).first
+# => #<Client id: 2, first_name: "Fifo">
+```
+
+The SQL equivalent of the above is:
+
+```sql
+SELECT * FROM clients ORDER BY clients.first_name ASC LIMIT 1
+```
+
The `first!` method behaves exactly like `first`, except that it will raise `ActiveRecord::RecordNotFound` if no matching record is found.
#### `last`
-The `last` method finds the last record ordered by the primary key. For example:
+The `last` method finds the last record ordered by primary key (default). For example:
```ruby
client = Client.last
@@ -242,6 +255,19 @@ The SQL equivalent of the above is:
SELECT * FROM clients ORDER BY clients.id DESC LIMIT 3
```
+On a collection that is ordered using `order`, `last` will return the last record ordered by the specified attribute for `order`.
+
+```ruby
+client = Client.order(:first_name).last
+# => #<Client id: 220, first_name: "Sara">
+```
+
+The SQL equivalent of the above is:
+
+```sql
+SELECT * FROM clients ORDER BY clients.first_name DESC LIMIT 1
+```
+
The `last!` method behaves exactly like `last`, except that it will raise `ActiveRecord::RecordNotFound` if no matching record is found.
#### `find_by`
@@ -322,7 +348,7 @@ end
The `find_each` method accepts most of the options allowed by the regular `find` method, except for `:order` and `:limit`, which are reserved for internal use by `find_each`.
-Three additional options, `:batch_size`, `:begin_at` and `:end_at`, are available as well.
+Three additional options, `:batch_size`, `:start` and `:finish`, are available as well.
**`:batch_size`**
@@ -334,34 +360,34 @@ User.find_each(batch_size: 5000) do |user|
end
```
-**`:begin_at`**
+**`:start`**
-By default, records are fetched in ascending order of the primary key, which must be an integer. The `:begin_at` option allows you to configure the first ID of the sequence whenever the lowest ID is not the one you need. This would be useful, for example, if you wanted to resume an interrupted batch process, provided you saved the last processed ID as a checkpoint.
+By default, records are fetched in ascending order of the primary key, which must be an integer. The `:start` option allows you to configure the first ID of the sequence whenever the lowest ID is not the one you need. This would be useful, for example, if you wanted to resume an interrupted batch process, provided you saved the last processed ID as a checkpoint.
For example, to send newsletters only to users with the primary key starting from 2000, and to retrieve them in batches of 5000:
```ruby
-User.find_each(begin_at: 2000, batch_size: 5000) do |user|
+User.find_each(start: 2000, batch_size: 5000) do |user|
NewsMailer.weekly(user).deliver_now
end
```
-**`:end_at`**
+**`:finish`**
-Similar to the `:begin_at` option, `:end_at` allows you to configure the last ID of the sequence whenever the highest ID is not the one you need.
-This would be useful, for example, if you wanted to run a batch process, using a subset of records based on `:begin_at` and `:end_at`
+Similar to the `:start` option, `:finish` allows you to configure the last ID of the sequence whenever the highest ID is not the one you need.
+This would be useful, for example, if you wanted to run a batch process, using a subset of records based on `:start` and `:finish`
For example, to send newsletters only to users with the primary key starting from 2000 up to 10000 and to retrieve them in batches of 5000:
```ruby
-User.find_each(begin_at: 2000, end_at: 10000, batch_size: 5000) do |user|
+User.find_each(start: 2000, finish: 10000, batch_size: 5000) do |user|
NewsMailer.weekly(user).deliver_now
end
```
Another example would be if you wanted multiple workers handling the same
processing queue. You could have each worker handle 10000 records by setting the
-appropriate `:begin_at` and `:end_at` options on each worker.
+appropriate `:start` and `:finish` options on each worker.
#### `find_in_batches`
@@ -376,7 +402,7 @@ end
##### Options for `find_in_batches`
-The `find_in_batches` method accepts the same `:batch_size`, `:begin_at` and `:end_at` options as `find_each`.
+The `find_in_batches` method accepts the same `:batch_size`, `:start` and `:finish` options as `find_each`.
Conditions
----------
@@ -1059,6 +1085,8 @@ SELECT categories.* FROM categories
INNER JOIN tags ON tags.article_id = articles.id
```
+Or, in English: "return all categories that have articles, where those articles have a comment made by a guest, and where those articles also have a tag."
+
#### Specifying Conditions on the Joined Tables
You can specify conditions on the joined tables using the regular [Array](#array-conditions) and [String](#pure-string-conditions) conditions. [Hash conditions](#hash-conditions) provide a special syntax for specifying conditions for the joined tables:
@@ -1268,6 +1296,28 @@ Using a class method is the preferred way to accept arguments for scopes. These
category.articles.created_before(time)
```
+### Using conditionals
+
+Your scope can utilize conditionals:
+
+```ruby
+class Article < ApplicationRecord
+ scope :created_before, ->(time) { where("created_at < ?", time) if time.present? }
+end
+```
+
+Like the other examples, this will behave similarly to a class method.
+
+```ruby
+class Article < ApplicationRecord
+ def self.created_before(time)
+ where("created_at < ?", time) if time.present?
+ end
+end
+```
+
+However, there is one important caveat: A scope will always return an `ActiveRecord::Relation` object, even if the conditional evaluates to `false`, whereas a class method, will return `nil`. This can cause `NoMethodError` when chaining class methods with conditionals, if any of the conditionals return `false`.
+
### Applying a default scope
If we wish for a scope to be applied across all queries to the model we can use the
diff --git a/guides/source/active_record_validations.md b/guides/source/active_record_validations.md
index dd7adf09a2..10bd201145 100644
--- a/guides/source/active_record_validations.md
+++ b/guides/source/active_record_validations.md
@@ -149,7 +149,7 @@ false` as an argument. This technique should be used with caution.
### `valid?` and `invalid?`
-Before saving an ActiveRecord object, Rails runs your validations.
+Before saving an Active Record object, Rails runs your validations.
If these validations produce any errors, Rails does not save the object.
You can also run these validations on your own. `valid?` triggers your validations
diff --git a/guides/source/active_support_core_extensions.md b/guides/source/active_support_core_extensions.md
index 0cb34aa8bc..e66b9a4301 100644
--- a/guides/source/active_support_core_extensions.md
+++ b/guides/source/active_support_core_extensions.md
@@ -2024,12 +2024,14 @@ Produce a string representation of a number rounded to a precision:
Produce a string representation of a number as a human-readable number of bytes:
```ruby
-123.to_s(:human_size) # => 123 Bytes
-1234.to_s(:human_size) # => 1.21 KB
-12345.to_s(:human_size) # => 12.1 KB
-1234567.to_s(:human_size) # => 1.18 MB
-1234567890.to_s(:human_size) # => 1.15 GB
-1234567890123.to_s(:human_size) # => 1.12 TB
+123.to_s(:human_size) # => 123 Bytes
+1234.to_s(:human_size) # => 1.21 KB
+12345.to_s(:human_size) # => 12.1 KB
+1234567.to_s(:human_size) # => 1.18 MB
+1234567890.to_s(:human_size) # => 1.15 GB
+1234567890123.to_s(:human_size) # => 1.12 TB
+1234567890123456.to_s(:human_size) # => 1.1 PB
+1234567890123456789.to_s(:human_size) # => 1.07 EB
```
Produce a string representation of a number in human-readable words:
@@ -2238,7 +2240,7 @@ Similarly, `from` returns the tail from the element at the passed index to the e
[].from(0) # => []
```
-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.
+The methods `second`, `third`, `fourth`, and `fifth` return the corresponding element, as do `second_to_last` and `third_to_last` (`first` and `last` are built-in). Thanks to social wisdom and positive constructiveness all around, `forty_two` is also available.
```ruby
%w(a b c d).third # => "c"
@@ -3076,7 +3078,7 @@ INFO: The following calculation methods have edge cases in October 1582, since d
#### `Date.current`
-Active Support defines `Date.current` to be today in the current time zone. That's like `Date.today`, except that it honors the user time zone, if defined. It also defines `Date.yesterday` and `Date.tomorrow`, and the instance predicates `past?`, `today?`, and `future?`, all of them relative to `Date.current`.
+Active Support defines `Date.current` to be today in the current time zone. That's like `Date.today`, except that it honors the user time zone, if defined. It also defines `Date.yesterday` and `Date.tomorrow`, and the instance predicates `past?`, `today?`, `future?`, `on_weekday?` and `on_weekend?`, all of them relative to `Date.current`.
When making Date comparisons using methods which honor the user time zone, make sure to use `Date.current` and not `Date.today`. There are cases where the user time zone might be in the future compared to the system time zone, which `Date.today` uses by default. This means `Date.today` may equal `Date.yesterday`.
@@ -3465,6 +3467,8 @@ years_ago
years_since
prev_year (last_year)
next_year
+on_weekday?
+on_weekend?
```
The following methods are reimplemented so you do **not** need to load `active_support/core_ext/date/calculations.rb` for these ones:
@@ -3651,6 +3655,8 @@ years_ago
years_since
prev_year (last_year)
next_year
+on_weekday?
+on_weekend?
```
They are analogous. Please refer to their documentation above and take into account the following differences:
diff --git a/guides/source/api_app.md b/guides/source/api_app.md
index 86baa9ee84..8dba914923 100644
--- a/guides/source/api_app.md
+++ b/guides/source/api_app.md
@@ -8,13 +8,13 @@ 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 middleware you will want to include
* How to decide which modules to use in your controller
--------------------------------------------------------------------------------
-What is an API app?
--------------------
+What is an API Application?
+---------------------------
Traditionally, when people said that they used Rails as an "API", they meant
providing a programmatically accessible API alongside their web application.
@@ -28,15 +28,14 @@ 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.
+Instead of using Rails to generate HTML that communicates with the server
+through forms and links, many developers are treating their web application as
+just an API client delivered as HTML with JavaScript that consumes a JSON API.
This guide covers building a Rails application that serves JSON resources to an
-API client **or** a client-side framework.
+API client, including client-side frameworks.
-Why use Rails for JSON APIs?
+Why Use Rails for JSON APIs?
----------------------------
The first question a lot of people have when thinking about building a JSON API
@@ -44,11 +43,11 @@ 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
+applications, most of an application's logic lives 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
+allows developers 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
@@ -75,7 +74,7 @@ Handled at the middleware layer:
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`),
+- 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)
@@ -86,7 +85,7 @@ Handled at the middleware layer:
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,
+While you could obviously build these up in terms of existing Rack middleware,
this list demonstrates that the default Rails middleware stack provides a lot
of value, even if you're "just generating JSON".
@@ -97,28 +96,28 @@ Handled at the Action Pack layer:
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/)
+ 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
+- 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
+- Instrumentation: Rails has an instrumentation API that triggers 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.
+- Generators: It is often handy to generate a resource and get your model,
+ controller, test stubs, and routes created for you in a single command for
+ further tweaking. Same for migrations and others.
- 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).
+ 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
@@ -126,7 +125,7 @@ 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".
+to be most of it.
The Basic Configuration
-----------------------
@@ -135,6 +134,8 @@ 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.
+### Creating a new application
+
You can generate a new api Rails app:
```bash
@@ -143,16 +144,18 @@ $ 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
+- Configure your application to start with a more limited set of middleware
than normal. Specifically, it will not include any middleware primarily useful
for browser applications (like cookies support) by default.
- Make `ApplicationController` inherit from `ActionController::API` instead of
- `ActionController::Base`. As with middlewares, this will leave out any Action
+ `ActionController::Base`. As with middleware, 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.
+### Changing an existing application
+
If you want to take an existing application and make it an API one, read the
following steps.
@@ -163,14 +166,23 @@ class definition:
config.api_only = true
```
-Optionally, in `config/environments/development.rb` add the following line
-to render error responses using the API format (JSON by default) when it
-is a local request:
+In `config/environments/development.rb`, set `config.debug_exception_response_format`
+to configure the format used in responses when errors occur in development mode.
+
+To render an HTML page with debugging information, use the value `:default`.
+
+```ruby
+config.debug_exception_response_format = :default
+```
+
+To render debugging information preserving the response format, use the value `:api`.
```ruby
config.debug_exception_response_format = :api
```
+By default, `config.debug_exception_response_format` is set to `:api`.
+
Finally, inside `app/controllers/application_controller.rb`, instead of:
```ruby
@@ -185,18 +197,18 @@ class ApplicationController < ActionController::API
end
```
-Choosing Middlewares
+Choosing Middleware
--------------------
-An API application comes with the following middlewares by default:
+An API application comes with the following middleware by default:
- `Rack::Sendfile`
- `ActionDispatch::Static`
-- `Rack::Lock`
+- `ActionDispatch::LoadInterlock`
- `ActiveSupport::Cache::Strategy::LocalCache::Middleware`
+- `Rack::Runtime`
- `ActionDispatch::RequestId`
- `Rails::Rack::Logger`
-- `Rack::Runtime`
- `ActionDispatch::ShowExceptions`
- `ActionDispatch::DebugExceptions`
- `ActionDispatch::RemoteIp`
@@ -206,14 +218,14 @@ An API application comes with the following middlewares by default:
- `Rack::ConditionalGet`
- `Rack::ETag`
-See the [internal middlewares](rails_on_rack.html#internal-middleware-stack)
+See the [internal middleware](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
+Other plugins, including Active Record, may add additional middleware. In
+general, these middleware 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:
+You can get a list of all middleware in your application via:
```bash
$ rails middleware
@@ -262,9 +274,6 @@ 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
@@ -296,9 +305,6 @@ config.action_dispatch.x_sendfile_header = "X-Accel-Redirect"
Make sure to configure your server to support these options following the
instructions in the `Rack::Sendfile` documentation.
-NOTE: The `Rack::Sendfile` middleware is always outside of the `Rack::Lock`
-mutex, even in single-threaded applications.
-
### Using ActionDispatch::Request
`ActionDispatch::Request#params` will take parameters from the client in the JSON
@@ -327,9 +333,9 @@ will be:
{ :person => { :firstName => "Yehuda", :lastName => "Katz" } }
```
-### Other Middlewares
+### Other Middleware
-Rails ships with a number of other middlewares that you might want to use in an
+Rails ships with a number of other middleware that you might want to use in an
API application, especially if one of your API clients is the browser:
- `Rack::MethodOverride`
@@ -340,13 +346,13 @@ API application, especially if one of your API clients is the browser:
* `ActionDispatch::Session::CookieStore`
* `ActionDispatch::Session::MemCacheStore`
-Any of these middlewares can be added via:
+Any of these middleware can be added via:
```ruby
config.middleware.use Rack::MethodOverride
```
-### Removing Middlewares
+### Removing Middleware
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:
@@ -355,7 +361,7 @@ middleware set, you can remove it with:
config.middleware.delete ::Rack::Sendfile
```
-Keep in mind that removing these middlewares will remove support for certain
+Keep in mind that removing these middleware will remove support for certain
features in Action Controller.
Choosing Controller Modules
@@ -364,22 +370,24 @@ 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::UrlFor`: Makes `url_for` and similar helpers available.
- `ActionController::Redirecting`: Support for `redirect_to`.
-- `ActionController::Rendering`: Basic support for rendering.
+- `AbstractController::Rendering` and `ActionController::ApiRendering`: Basic support for rendering.
- `ActionController::Renderers::All`: Support for `render :json` and friends.
- `ActionController::ConditionalGet`: Support for `stale?`.
-- `ActionController::ForceSSL`: Support for `force_ssl`.
-- `ActionController::DataStreaming`: Support for `send_file` and `send_data`.
-- `AbstractController::Callbacks`: Support for `before_action` and friends.
-- `ActionController::Instrumentation`: Support for the instrumentation
- hooks defined by Action Controller (see [the instrumentation
- guide](active_support_instrumentation.html#action-controller)).
-- `ActionController::Rescue`: Support for `rescue_from`.
- `ActionController::BasicImplicitRender`: Makes sure to return an empty response
if there's not an explicit one.
- `ActionController::StrongParameters`: Support for parameters white-listing in
combination with Active Model mass assignment.
+- `ActionController::ForceSSL`: Support for `force_ssl`.
+- `ActionController::DataStreaming`: Support for `send_file` and `send_data`.
+- `AbstractController::Callbacks`: Support for `before_action` and
+ similar helpers.
+- `ActionController::Rescue`: Support for `rescue_from`.
+- `ActionController::Instrumentation`: Support for the instrumentation
+ hooks defined by Action Controller (see [the instrumentation
+ guide](active_support_instrumentation.html#action-controller) for
+more information regarding this).
- `ActionController::ParamsWrapper`: Wraps the parameters hash into a nested hash
so you don't have to specify root elements sending POST requests for instance.
@@ -408,5 +416,5 @@ Some common modules you might want to add:
- `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
+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/asset_pipeline.md b/guides/source/asset_pipeline.md
index 0083fc0e6c..b6c612794c 100644
--- a/guides/source/asset_pipeline.md
+++ b/guides/source/asset_pipeline.md
@@ -21,8 +21,11 @@ What is the Asset Pipeline?
The asset pipeline provides a framework to concatenate and minify or compress
JavaScript and CSS assets. It also adds the ability to write these assets in
other languages and pre-processors such as CoffeeScript, Sass and ERB.
+It allows assets in your application to be automatically combined with assets
+from other gems. For example, jquery-rails includes a copy of jquery.js
+and enables AJAX features in Rails.
-The asset pipeline is technically no longer a core feature of Rails 4, it has
+The asset pipeline is technically no longer a core feature from Rails 4 onwards -- it has
been extracted out of the framework into the
[sprockets-rails](https://github.com/rails/sprockets-rails) gem.
@@ -35,7 +38,7 @@ passing the `--skip-sprockets` option.
rails new appname --skip-sprockets
```
-Rails 4 automatically adds the `sass-rails`, `coffee-rails` and `uglifier`
+Rails automatically adds the `sass-rails`, `coffee-rails` and `uglifier`
gems to your Gemfile, which are used by Sprockets for asset compression:
```ruby
@@ -44,8 +47,8 @@ gem 'uglifier'
gem 'coffee-rails'
```
-Using the `--skip-sprockets` option will prevent Rails 4 from adding
-`sass-rails` and `uglifier` to Gemfile, so if you later want to enable
+Using the `--skip-sprockets` option will prevent Rails from adding
+them to your Gemfile, so if you later want to enable
the asset pipeline you will have to add those gems to your Gemfile. Also,
creating an application with the `--skip-sprockets` option will generate
a slightly different `config/application.rb` file, with a require statement
@@ -66,7 +69,7 @@ config.assets.js_compressor = :uglifier
```
NOTE: The `sass-rails` gem is automatically used for CSS compression if included
-in Gemfile and no `config.assets.css_compressor` option is set.
+in the Gemfile and no `config.assets.css_compressor` option is set.
### Main Features
@@ -327,13 +330,13 @@ familiar `javascript_include_tag` and `stylesheet_link_tag`:
<%= javascript_include_tag "application" %>
```
-If using the turbolinks gem, which is included by default in Rails 4, then
+If using the turbolinks gem, which is included by default in Rails, then
include the 'data-turbolinks-track' option which causes turbolinks to check if
an asset has been updated and if so loads it into the page:
```erb
-<%= stylesheet_link_tag "application", media: "all", "data-turbolinks-track" => true %>
-<%= javascript_include_tag "application", "data-turbolinks-track" => true %>
+<%= stylesheet_link_tag "application", media: "all", "data-turbolinks-track" => "reload" %>
+<%= javascript_include_tag "application", "data-turbolinks-track" => "reload" %>
```
In regular views you can access images in the `public/assets/images` directory
@@ -443,7 +446,7 @@ makes fewer requests. Compression also reduces file size, enabling the
browser to download them faster.
-For example, a new Rails 4 application includes a default
+For example, a new Rails application includes a default
`app/assets/javascripts/application.js` file containing the following lines:
```js
@@ -484,7 +487,7 @@ which contains these lines:
*/
```
-Rails 4 creates both `app/assets/javascripts/application.js` and
+Rails creates both `app/assets/javascripts/application.js` and
`app/assets/stylesheets/application.css` regardless of whether the
--skip-sprockets option is used when creating a new rails application. This is
so you can easily add asset pipelining later if you like.
@@ -898,7 +901,7 @@ your CDN server, you need to tell browsers to use your CDN to grab assets
instead of your Rails server directly. You can do this by configuring Rails to
set your CDN as the asset host instead of using a relative path. To set your
asset host in Rails, you need to set `config.action_controller.asset_host` in
-`config/production.rb`:
+`config/environments/production.rb`:
```ruby
config.action_controller.asset_host = 'mycdnsubdomain.fictional-cdn.com'
@@ -1108,7 +1111,7 @@ supported runtime in order to use `uglifier`. If you are using Mac OS X or
Windows you have a JavaScript runtime installed in your operating system.
NOTE: The `config.assets.compress` initialization option is no longer used in
-Rails 4 to enable either CSS or JavaScript compression. Setting it will have no
+Rails to enable either CSS or JavaScript compression. Setting it will have no
effect on the application. Instead, setting `config.assets.css_compressor` and
`config.assets.js_compressor` will control compression of CSS and JavaScript
assets.
@@ -1177,19 +1180,14 @@ TIP: For further details have a look at the docs of your production web server:
Assets Cache Store
------------------
-The default Rails cache store will be used by Sprockets to cache assets in
-development and production. This can be changed by setting
-`config.assets.cache_store`:
-
-```ruby
-config.assets.cache_store = :memory_store
-```
-
-The options accepted by the assets cache store are the same as the application's
-cache store.
+By default, Sprockets caches assets in `tmp/cache/assets` in development
+and production environments. This can be changed as follows:
```ruby
-config.assets.cache_store = :memory_store, { size: 32.megabytes }
+config.assets.configure do |env|
+ env.cache = ActiveSupport::Cache.lookup_store(:memory_store,
+ { size: 32.megabytes })
+end
```
To disable the assets cache store:
@@ -1280,8 +1278,9 @@ config.assets.debug = true
And in `production.rb`:
```ruby
-# Choose the compressors to use (if any) config.assets.js_compressor =
-# :uglifier config.assets.css_compressor = :yui
+# Choose the compressors to use (if any)
+config.assets.js_compressor = :uglifier
+# config.assets.css_compressor = :yui
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false
@@ -1290,15 +1289,16 @@ config.assets.compile = false
config.assets.digest = true
# Precompile additional assets (application.js, application.css, and all
-# non-JS/CSS are already added) config.assets.precompile += %w( search.js )
+# non-JS/CSS are already added)
+# config.assets.precompile += %w( search.js )
```
-Rails 4 no longer sets default config values for Sprockets in `test.rb`, so
+Rails 4 and above no longer set default config values for Sprockets in `test.rb`, so
`test.rb` now requires Sprockets configuration. The old defaults in the test
environment are: `config.assets.compile = true`, `config.assets.compress = false`,
`config.assets.debug = false` and `config.assets.digest = false`.
-The following should also be added to `Gemfile`:
+The following should also be added to your `Gemfile`:
```ruby
gem 'sass-rails', "~> 3.2.3"
diff --git a/guides/source/association_basics.md b/guides/source/association_basics.md
index d83dda7228..09ab64837a 100644
--- a/guides/source/association_basics.md
+++ b/guides/source/association_basics.md
@@ -16,54 +16,54 @@ After reading this guide, you will know:
Why Associations?
-----------------
-In Rails, an _association_ is a connection between two Active Record models. Why do we need associations between models? Because they make common operations simpler and easier in your code. For example, consider a simple Rails application that includes a model for customers and a model for orders. Each customer can have many orders. Without associations, the model declarations would look like this:
+In Rails, an _association_ is a connection between two Active Record models. Why do we need associations between models? Because they make common operations simpler and easier in your code. For example, consider a simple Rails application that includes a model for authors and a model for books. Each author can have many books. Without associations, the model declarations would look like this:
```ruby
-class Customer < ApplicationRecord
+class Author < ApplicationRecord
end
-class Order < ApplicationRecord
+class Book < ApplicationRecord
end
```
-Now, suppose we wanted to add a new order for an existing customer. We'd need to do something like this:
+Now, suppose we wanted to add a new book for an existing author. We'd need to do something like this:
```ruby
-@order = Order.create(order_date: Time.now, customer_id: @customer.id)
+@book = Book.create(published_at: Time.now, author_id: @author.id)
```
-Or consider deleting a customer, and ensuring that all of its orders get deleted as well:
+Or consider deleting an author, and ensuring that all of its books get deleted as well:
```ruby
-@orders = Order.where(customer_id: @customer.id)
-@orders.each do |order|
- order.destroy
+@books = Book.where(author_id: @author.id)
+@books.each do |book|
+ book.destroy
end
-@customer.destroy
+@author.destroy
```
-With Active Record associations, we can streamline these - and other - operations by declaratively telling Rails that there is a connection between the two models. Here's the revised code for setting up customers and orders:
+With Active Record associations, we can streamline these - and other - operations by declaratively telling Rails that there is a connection between the two models. Here's the revised code for setting up authors and books:
```ruby
-class Customer < ApplicationRecord
- has_many :orders, dependent: :destroy
+class Author < ApplicationRecord
+ has_many :books, dependent: :destroy
end
-class Order < ApplicationRecord
- belongs_to :customer
+class Book < ApplicationRecord
+ belongs_to :author
end
```
-With this change, creating a new order for a particular customer is easier:
+With this change, creating a new book for a particular author is easier:
```ruby
-@order = @customer.orders.create(order_date: Time.now)
+@book = @author.books.create(published_at: Time.now)
```
-Deleting a customer and all of its orders is *much* easier:
+Deleting an author and all of its books is *much* easier:
```ruby
-@customer.destroy
+@author.destroy
```
To learn more about the different types of associations, read the next section of this guide. That's followed by some tips and tricks for working with associations, and then by a complete reference to the methods and options for associations in Rails.
@@ -86,31 +86,31 @@ In the remainder of this guide, you'll learn how to declare and use the various
### The `belongs_to` Association
-A `belongs_to` association sets up a one-to-one connection with another model, such that each instance of the declaring model "belongs to" one instance of the other model. For example, if your application includes customers and orders, and each order can be assigned to exactly one customer, you'd declare the order model this way:
+A `belongs_to` association sets up a one-to-one connection with another model, such that each instance of the declaring model "belongs to" one instance of the other model. For example, if your application includes authors and books, and each book can be assigned to exactly one author, you'd declare the book model this way:
```ruby
-class Order < ApplicationRecord
- belongs_to :customer
+class Book < ApplicationRecord
+ belongs_to :author
end
```
![belongs_to Association Diagram](images/belongs_to.png)
-NOTE: `belongs_to` associations _must_ use the singular term. If you used the pluralized form in the above example for the `customer` association in the `Order` model, you would be told that there was an "uninitialized constant Order::Customers". This is because Rails automatically infers the class name from the association name. If the association name is wrongly pluralized, then the inferred class will be wrongly pluralized too.
+NOTE: `belongs_to` associations _must_ use the singular term. If you used the pluralized form in the above example for the `author` association in the `Book` model, you would be told that there was an "uninitialized constant Book::Authors". This is because Rails automatically infers the class name from the association name. If the association name is wrongly pluralized, then the inferred class will be wrongly pluralized too.
The corresponding migration might look like this:
```ruby
-class CreateOrders < ActiveRecord::Migration[5.0]
+class CreateBooks < ActiveRecord::Migration[5.0]
def change
- create_table :customers do |t|
+ create_table :authors do |t|
t.string :name
t.timestamps null: false
end
- create_table :orders do |t|
- t.belongs_to :customer, index: true
- t.datetime :order_date
+ create_table :books do |t|
+ t.belongs_to :author, index: true
+ t.datetime :published_at
t.timestamps null: false
end
end
@@ -161,11 +161,11 @@ end
### The `has_many` Association
-A `has_many` association indicates a one-to-many connection with another model. You'll often find this association on the "other side" of a `belongs_to` association. This association indicates that each instance of the model has zero or more instances of another model. For example, in an application containing customers and orders, the customer model could be declared like this:
+A `has_many` association indicates a one-to-many connection with another model. You'll often find this association on the "other side" of a `belongs_to` association. This association indicates that each instance of the model has zero or more instances of another model. For example, in an application containing authors and books, the author model could be declared like this:
```ruby
-class Customer < ApplicationRecord
- has_many :orders
+class Author < ApplicationRecord
+ has_many :books
end
```
@@ -176,16 +176,16 @@ NOTE: The name of the other model is pluralized when declaring a `has_many` asso
The corresponding migration might look like this:
```ruby
-class CreateCustomers < ActiveRecord::Migration[5.0]
+class CreateAuthors < ActiveRecord::Migration[5.0]
def change
- create_table :customers do |t|
+ create_table :authors do |t|
t.string :name
t.timestamps null: false
end
- create_table :orders do |t|
- t.belongs_to :customer, index: true
- t.datetime :order_date
+ create_table :books do |t|
+ t.belongs_to :author, index: true
+ t.datetime :published_at
t.timestamps null: false
end
end
@@ -540,17 +540,17 @@ Here are a few things you should know to make efficient use of Active Record ass
All of the association methods are built around caching, which keeps the result of the most recent query available for further operations. The cache is even shared across methods. For example:
```ruby
-customer.orders # retrieves orders from the database
-customer.orders.size # uses the cached copy of orders
-customer.orders.empty? # uses the cached copy of orders
+author.books # retrieves books from the database
+author.books.size # uses the cached copy of books
+author.books.empty? # uses the cached copy of books
```
But what if you want to reload the cache, because data might have been changed by some other part of the application? Just pass `true` to the association call:
```ruby
-customer.orders # retrieves orders from the database
-customer.orders.size # uses the cached copy of orders
-customer.orders(true).empty? # discards the cached copy of orders
+author.books # retrieves books from the database
+author.books.size # uses the cached copy of books
+author.books(true).empty? # discards the cached copy of books
# and goes back to the database
```
@@ -567,23 +567,23 @@ Associations are extremely useful, but they are not magic. You are responsible f
When you declare a `belongs_to` association, you need to create foreign keys as appropriate. For example, consider this model:
```ruby
-class Order < ApplicationRecord
- belongs_to :customer
+class Book < ApplicationRecord
+ belongs_to :author
end
```
-This declaration needs to be backed up by the proper foreign key declaration on the orders table:
+This declaration needs to be backed up by the proper foreign key declaration on the books table:
```ruby
-class CreateOrders < ActiveRecord::Migration[5.0]
+class CreateBooks < ActiveRecord::Migration[5.0]
def change
- create_table :orders do |t|
- t.datetime :order_date
- t.string :order_number
- t.integer :customer_id
+ create_table :books do |t|
+ t.datetime :published_at
+ t.string :book_number
+ t.integer :author_id
end
- add_index :orders, :customer_id
+ add_index :books, :author_id
end
end
```
@@ -592,7 +592,7 @@ If you create an association some time after you build the underlying model, you
#### Creating Join Tables for `has_and_belongs_to_many` Associations
-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.
+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 book of the class names. So a join between author and book models will give the default join table name of "authors_books" because "a" outranks "b" 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).
@@ -700,45 +700,45 @@ end
It's normal for associations to work in two directions, requiring declaration on two different models:
```ruby
-class Customer < ApplicationRecord
- has_many :orders
+class Author < ApplicationRecord
+ has_many :books
end
-class Order < ApplicationRecord
- belongs_to :customer
+class Book < ApplicationRecord
+ belongs_to :author
end
```
By default, Active Record doesn't know about the connection between these associations. This can lead to two copies of an object getting out of sync:
```ruby
-c = Customer.first
-o = c.orders.first
-c.first_name == o.customer.first_name # => true
-c.first_name = 'Manny'
-c.first_name == o.customer.first_name # => false
+a = Author.first
+b = a.books.first
+a.first_name == b.author.first_name # => true
+a.first_name = 'Manny'
+a.first_name == b.author.first_name # => false
```
-This happens because `c` and `o.customer` are two different in-memory representations of the same data, and neither one is automatically refreshed from changes to the other. Active Record provides the `:inverse_of` option so that you can inform it of these relations:
+This happens because `a` and `b.author` are two different in-memory representations of the same data, and neither one is automatically refreshed from changes to the other. Active Record provides the `:inverse_of` option so that you can inform it of these relations:
```ruby
-class Customer < ApplicationRecord
- has_many :orders, inverse_of: :customer
+class Author < ApplicationRecord
+ has_many :books, inverse_of: :author
end
-class Order < ApplicationRecord
- belongs_to :customer, inverse_of: :orders
+class Book < ApplicationRecord
+ belongs_to :author, inverse_of: :books
end
```
-With these changes, Active Record will only load one copy of the customer object, preventing inconsistencies and making your application more efficient:
+With these changes, Active Record will only load one copy of the author object, preventing inconsistencies and making your application more efficient:
```ruby
-c = Customer.first
-o = c.orders.first
-c.first_name == o.customer.first_name # => true
-c.first_name = 'Manny'
-c.first_name == o.customer.first_name # => true
+a = author.first
+b = a.books.first
+a.first_name == b.author.first_name # => true
+a.first_name = 'Manny'
+a.first_name == b.author.first_name # => true
```
There are a few limitations to `inverse_of` support:
@@ -781,19 +781,19 @@ When you declare a `belongs_to` association, the declaring class automatically g
In all of these methods, `association` is replaced with the symbol passed as the first argument to `belongs_to`. For example, given the declaration:
```ruby
-class Order < ApplicationRecord
- belongs_to :customer
+class Book < ApplicationRecord
+ belongs_to :author
end
```
-Each instance of the `Order` model will have these methods:
+Each instance of the `Book` model will have these methods:
```ruby
-customer
-customer=
-build_customer
-create_customer
-create_customer!
+author
+author=
+build_author
+create_author
+create_author!
```
NOTE: When initializing a new `has_one` or `belongs_to` association you must use the `build_` prefix to build the association, rather than the `association.build` method that would be used for `has_many` or `has_and_belongs_to_many` associations. To create one, use the `create_` prefix.
@@ -803,13 +803,13 @@ NOTE: When initializing a new `has_one` or `belongs_to` association you must use
The `association` method returns the associated object, if any. If no associated object is found, it returns `nil`.
```ruby
-@customer = @order.customer
+@author = @book.author
```
If the associated object has already been retrieved from the database for this object, the cached version will be returned. To override this behavior (and force a database read), call `#reload` on the parent object.
```ruby
-@customer = @order.reload.customer
+@author = @book.reload.author
```
##### `association=(associate)`
@@ -817,7 +817,7 @@ If the associated object has already been retrieved from the database for this o
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
+@book.author = @author
```
##### `build_association(attributes = {})`
@@ -825,8 +825,8 @@ The `association=` method assigns an associated object to this object. Behind th
The `build_association` method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through this object's foreign key will be set, but the associated object will _not_ yet be saved.
```ruby
-@customer = @order.build_customer(customer_number: 123,
- customer_name: "John Doe")
+@author = @book.build_author(author_number: 123,
+ author_name: "John Doe")
```
##### `create_association(attributes = {})`
@@ -834,8 +834,8 @@ The `build_association` method returns a new object of the associated type. This
The `create_association` method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through this object's foreign key will be set, and, once it passes all of the validations specified on the associated model, the associated object _will_ be saved.
```ruby
-@customer = @order.create_customer(customer_number: 123,
- customer_name: "John Doe")
+@author = @book.create_author(author_number: 123,
+ author_name: "John Doe")
```
##### `create_association!(attributes = {})`
@@ -848,8 +848,8 @@ Does the same as `create_association` above, but raises `ActiveRecord::RecordInv
While Rails uses intelligent defaults that will work well in most situations, there may be times when you want to customize the behavior of the `belongs_to` association reference. Such customizations can easily be accomplished by passing options and scope blocks when you create the association. For example, this association uses two such options:
```ruby
-class Order < ApplicationRecord
- belongs_to :customer, dependent: :destroy,
+class Book < ApplicationRecord
+ belongs_to :author, dependent: :destroy,
counter_cache: true
end
```
@@ -874,11 +874,11 @@ If you set the `:autosave` option to `true`, Rails will save any loaded members
##### `:class_name`
-If the name of the other model cannot be derived from the association name, you can use the `:class_name` option to supply the model name. For example, if an order belongs to a customer, but the actual name of the model containing customers is `Patron`, you'd set things up this way:
+If the name of the other model cannot be derived from the association name, you can use the `:class_name` option to supply the model name. For example, if a book belongs to an author, but the actual name of the model containing authors is `Patron`, you'd set things up this way:
```ruby
-class Order < ApplicationRecord
- belongs_to :customer, class_name: "Patron"
+class Book < ApplicationRecord
+ belongs_to :author, class_name: "Patron"
end
```
@@ -887,22 +887,22 @@ end
The `:counter_cache` option can be used to make finding the number of belonging objects more efficient. Consider these models:
```ruby
-class Order < ApplicationRecord
- belongs_to :customer
+class Book < ApplicationRecord
+ belongs_to :author
end
-class Customer < ApplicationRecord
- has_many :orders
+class Author < ApplicationRecord
+ has_many :books
end
```
-With these declarations, asking for the value of `@customer.orders.size` requires making a call to the database to perform a `COUNT(*)` query. To avoid this call, you can add a counter cache to the _belonging_ model:
+With these declarations, asking for the value of `@author.books.size` requires making a call to the database to perform a `COUNT(*)` query. To avoid this call, you can add a counter cache to the _belonging_ model:
```ruby
-class Order < ApplicationRecord
- belongs_to :customer, counter_cache: true
+class Book < ApplicationRecord
+ belongs_to :author, counter_cache: true
end
-class Customer < ApplicationRecord
- has_many :orders
+class Author < ApplicationRecord
+ has_many :books
end
```
@@ -911,18 +911,18 @@ With this declaration, Rails will keep the cache value up to date, and then retu
Although the `:counter_cache` option is specified on the model that includes
the `belongs_to` declaration, the actual column must be added to the
_associated_ (`has_many`) model. In the case above, you would need to add a
-column named `orders_count` to the `Customer` model.
+column named `books_count` to the `Author` model.
You can override the default column name by specifying a custom column name in
the `counter_cache` declaration instead of `true`. For example, to use
-`count_of_orders` instead of `orders_count`:
+`count_of_books` instead of `books_count`:
```ruby
-class Order < ApplicationRecord
- belongs_to :customer, counter_cache: :count_of_orders
+class Book < ApplicationRecord
+ belongs_to :author, counter_cache: :count_of_books
end
-class Customer < ApplicationRecord
- has_many :orders
+class Author < ApplicationRecord
+ has_many :books
end
```
@@ -949,8 +949,8 @@ WARNING: You should not specify this option on a `belongs_to` association that i
By convention, Rails assumes that the column used to hold the foreign key on this model is the name of the association with the suffix `_id` added. The `:foreign_key` option lets you set the name of the foreign key directly:
```ruby
-class Order < ApplicationRecord
- belongs_to :customer, class_name: "Patron",
+class Book < ApplicationRecord
+ belongs_to :author, class_name: "Patron",
foreign_key: "patron_id"
end
```
@@ -982,12 +982,12 @@ When we execute `@user.todos.create` then the `@todo` record will have its
The `:inverse_of` option specifies the name of the `has_many` or `has_one` association that is the inverse of this association. Does not work in combination with the `:polymorphic` options.
```ruby
-class Customer < ApplicationRecord
- has_many :orders, inverse_of: :customer
+class Author < ApplicationRecord
+ has_many :books, inverse_of: :author
end
-class Order < ApplicationRecord
- belongs_to :customer, inverse_of: :orders
+class Book < ApplicationRecord
+ belongs_to :author, inverse_of: :books
end
```
@@ -1000,20 +1000,20 @@ Passing `true` to the `:polymorphic` option indicates that this is a polymorphic
If you set the `:touch` option to `true`, then the `updated_at` or `updated_on` timestamp on the associated object will be set to the current time whenever this object is saved or destroyed:
```ruby
-class Order < ApplicationRecord
- belongs_to :customer, touch: true
+class Book < ApplicationRecord
+ belongs_to :author, touch: true
end
-class Customer < ApplicationRecord
- has_many :orders
+class Author < ApplicationRecord
+ has_many :books
end
```
-In this case, saving or destroying an order will update the timestamp on the associated customer. You can also specify a particular timestamp attribute to update:
+In this case, saving or destroying an book will update the timestamp on the associated author. You can also specify a particular timestamp attribute to update:
```ruby
-class Order < ApplicationRecord
- belongs_to :customer, touch: :orders_updated_at
+class Book < ApplicationRecord
+ belongs_to :author, touch: :books_updated_at
end
```
@@ -1031,8 +1031,8 @@ object won't be validated. By default, this option is set to `false`.
There may be times when you wish to customize the query used by `belongs_to`. Such customizations can be achieved via a scope block. For example:
```ruby
-class Order < ApplicationRecord
- belongs_to :customer, -> { where active: true },
+class Book < ApplicationRecord
+ belongs_to :author, -> { where active: true },
dependent: :destroy
end
```
@@ -1049,8 +1049,8 @@ You can use any of the standard [querying methods](active_record_querying.html)
The `where` method lets you specify the conditions that the associated object must meet.
```ruby
-class Order < ApplicationRecord
- belongs_to :customer, -> { where active: true }
+class book < ApplicationRecord
+ belongs_to :author, -> { where active: true }
end
```
@@ -1060,37 +1060,37 @@ You can use the `includes` method to specify second-order associations that shou
```ruby
class LineItem < ApplicationRecord
- belongs_to :order
+ belongs_to :book
end
-class Order < ApplicationRecord
- belongs_to :customer
+class Book < ApplicationRecord
+ belongs_to :author
has_many :line_items
end
-class Customer < ApplicationRecord
- has_many :orders
+class Author < ApplicationRecord
+ has_many :books
end
```
-If you frequently retrieve customers directly from line items (`@line_item.order.customer`), then you can make your code somewhat more efficient by including customers in the association from line items to orders:
+If you frequently retrieve authors directly from line items (`@line_item.book.author`), then you can make your code somewhat more efficient by including authors in the association from line items to books:
```ruby
class LineItem < ApplicationRecord
- belongs_to :order, -> { includes :customer }
+ belongs_to :book, -> { includes :author }
end
-class Order < ApplicationRecord
- belongs_to :customer
+class Book < ApplicationRecord
+ belongs_to :author
has_many :line_items
end
-class Customer < ApplicationRecord
- has_many :orders
+class Author < ApplicationRecord
+ has_many :books
end
```
-NOTE: There's no need to use `includes` for immediate associations - that is, if you have `Order belongs_to :customer`, then the customer is eager-loaded automatically when it's needed.
+NOTE: There's no need to use `includes` for immediate associations - that is, if you have `Book belongs_to :author`, then the author is eager-loaded automatically when it's needed.
##### `readonly`
@@ -1107,8 +1107,8 @@ TIP: If you use the `select` method on a `belongs_to` association, you should al
You can see if any associated objects exist by using the `association.nil?` method:
```ruby
-if @order.customer.nil?
- @msg = "No customer found for this order"
+if @book.author.nil?
+ @msg = "No author found for this book"
end
```
@@ -1415,30 +1415,30 @@ When you declare a `has_many` association, the declaring class automatically gai
In all of these methods, `collection` is replaced with the symbol passed as the first argument to `has_many`, and `collection_singular` is replaced with the singularized version of that symbol. For example, given the declaration:
```ruby
-class Customer < ApplicationRecord
- has_many :orders
+class Author < ApplicationRecord
+ has_many :books
end
```
-Each instance of the `Customer` model will have these methods:
+Each instance of the `Author` model will have these methods:
```ruby
-orders
-orders<<(object, ...)
-orders.delete(object, ...)
-orders.destroy(object, ...)
-orders=(objects)
-order_ids
-order_ids=(ids)
-orders.clear
-orders.empty?
-orders.size
-orders.find(...)
-orders.where(...)
-orders.exists?(...)
-orders.build(attributes = {}, ...)
-orders.create(attributes = {})
-orders.create!(attributes = {})
+books
+books<<(object, ...)
+books.delete(object, ...)
+books.destroy(object, ...)
+books=(objects)
+book_ids
+book_ids=(ids)
+books.clear
+books.empty?
+books.size
+books.find(...)
+books.where(...)
+books.exists?(...)
+books.build(attributes = {}, ...)
+books.create(attributes = {})
+books.create!(attributes = {})
```
##### `collection`
@@ -1446,7 +1446,7 @@ orders.create!(attributes = {})
The `collection` method returns an array of all of the associated objects. If there are no associated objects, it returns an empty array.
```ruby
-@orders = @customer.orders
+@books = @author.books
```
##### `collection<<(object, ...)`
@@ -1454,7 +1454,7 @@ The `collection` method returns an array of all of the associated objects. If th
The `collection<<` method adds one or more objects to the collection by setting their foreign keys to the primary key of the calling model.
```ruby
-@customer.orders << @order1
+@author.books << @book1
```
##### `collection.delete(object, ...)`
@@ -1462,7 +1462,7 @@ The `collection<<` method adds one or more objects to the collection by setting
The `collection.delete` method removes one or more objects from the collection by setting their foreign keys to `NULL`.
```ruby
-@customer.orders.delete(@order1)
+@author.books.delete(@book1)
```
WARNING: Additionally, objects will be destroyed if they're associated with `dependent: :destroy`, and deleted if they're associated with `dependent: :delete_all`.
@@ -1472,7 +1472,7 @@ WARNING: Additionally, objects will be destroyed if they're associated with `dep
The `collection.destroy` method removes one or more objects from the collection by running `destroy` on each object.
```ruby
-@customer.orders.destroy(@order1)
+@author.books.destroy(@book1)
```
WARNING: Objects will _always_ be removed from the database, ignoring the `:dependent` option.
@@ -1486,7 +1486,7 @@ The `collection=` method makes the collection contain only the supplied objects,
The `collection_singular_ids` method returns an array of the ids of the objects in the collection.
```ruby
-@order_ids = @customer.order_ids
+@book_ids = @author.book_ids
```
##### `collection_singular_ids=(ids)`
@@ -1498,7 +1498,7 @@ The `collection_singular_ids=` method makes the collection contain only the obje
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
+@author.books.clear
```
WARNING: Objects will be deleted if they're associated with `dependent: :destroy`,
@@ -1509,8 +1509,8 @@ just like `dependent: :delete_all`.
The `collection.empty?` method returns `true` if the collection does not contain any associated objects.
```erb
-<% if @customer.orders.empty? %>
- No Orders Found
+<% if @author.books.empty? %>
+ No Books Found
<% end %>
```
@@ -1519,7 +1519,7 @@ The `collection.empty?` method returns `true` if the collection does not contain
The `collection.size` method returns the number of objects in the collection.
```ruby
-@order_count = @customer.orders.size
+@book_count = @author.books.size
```
##### `collection.find(...)`
@@ -1527,7 +1527,7 @@ The `collection.size` method returns the number of objects in the collection.
The `collection.find` method finds objects within the collection. It uses the same syntax and options as `ActiveRecord::Base.find`.
```ruby
-@open_orders = @customer.orders.find(1)
+@available_books = @author.books.find(1)
```
##### `collection.where(...)`
@@ -1535,8 +1535,8 @@ The `collection.find` method finds objects within the collection. It uses the sa
The `collection.where` method finds objects within the collection based on the conditions supplied but the objects are loaded lazily meaning that the database is queried only when the object(s) are accessed.
```ruby
-@open_orders = @customer.orders.where(open: true) # No query yet
-@open_order = @open_orders.first # Now the database will be queried
+@available_books = @author.books.where(available: true) # No query yet
+@available_book = @available_books.first # Now the database will be queried
```
##### `collection.exists?(...)`
@@ -1550,12 +1550,12 @@ conditions exists in the collection. It uses the same syntax and options as
The `collection.build` method returns a single or array of new objects of the associated type. The object(s) will be instantiated from the passed attributes, and the link through their foreign key will be created, but the associated objects will _not_ yet be saved.
```ruby
-@order = @customer.orders.build(order_date: Time.now,
- order_number: "A12345")
+@book = @author.books.build(published_at: Time.now,
+ book_number: "A12345")
-@orders = @customer.orders.build([
- { order_date: Time.now, order_number: "A12346" },
- { order_date: Time.now, order_number: "A12347" }
+@books = @author.books.build([
+ { published_at: Time.now, book_number: "A12346" },
+ { published_at: Time.now, book_number: "A12347" }
])
```
@@ -1564,12 +1564,12 @@ The `collection.build` method returns a single or array of new objects of the as
The `collection.create` method returns a single or array of new objects of the associated type. The object(s) will be instantiated from the passed attributes, the link through its foreign key will be created, and, once it passes all of the validations specified on the associated model, the associated object _will_ be saved.
```ruby
-@order = @customer.orders.create(order_date: Time.now,
- order_number: "A12345")
+@book = @author.books.create(published_at: Time.now,
+ book_number: "A12345")
-@orders = @customer.orders.create([
- { order_date: Time.now, order_number: "A12346" },
- { order_date: Time.now, order_number: "A12347" }
+@books = @author.books.create([
+ { published_at: Time.now, book_number: "A12346" },
+ { published_at: Time.now, book_number: "A12347" }
])
```
@@ -1582,8 +1582,8 @@ Does the same as `collection.create` above, but raises `ActiveRecord::RecordInva
While Rails uses intelligent defaults that will work well in most situations, there may be times when you want to customize the behavior of the `has_many` association reference. Such customizations can easily be accomplished by passing options when you create the association. For example, this association uses two such options:
```ruby
-class Customer < ApplicationRecord
- has_many :orders, dependent: :delete_all, validate: false
+class Author < ApplicationRecord
+ has_many :books, dependent: :delete_all, validate: false
end
```
@@ -1612,11 +1612,11 @@ If you set the `:autosave` option to `true`, Rails will save any loaded members
##### `:class_name`
-If the name of the other model cannot be derived from the association name, you can use the `:class_name` option to supply the model name. For example, if a customer has many orders, but the actual name of the model containing orders is `Transaction`, you'd set things up this way:
+If the name of the other model cannot be derived from the association name, you can use the `:class_name` option to supply the model name. For example, if an author has many books, but the actual name of the model containing books is `Transaction`, you'd set things up this way:
```ruby
-class Customer < ApplicationRecord
- has_many :orders, class_name: "Transaction"
+class Author < ApplicationRecord
+ has_many :books, class_name: "Transaction"
end
```
@@ -1639,8 +1639,8 @@ Controls what happens to the associated objects when their owner is destroyed:
By convention, Rails assumes that the column used to hold the foreign key on the other model is the name of this model with the suffix `_id` added. The `:foreign_key` option lets you set the name of the foreign key directly:
```ruby
-class Customer < ApplicationRecord
- has_many :orders, foreign_key: "cust_id"
+class Author < ApplicationRecord
+ has_many :books, foreign_key: "cust_id"
end
```
@@ -1651,12 +1651,12 @@ TIP: In any case, Rails will not create foreign key columns for you. You need to
The `:inverse_of` option specifies the name of the `belongs_to` association that is the inverse of this association. Does not work in combination with the `:through` or `:as` options.
```ruby
-class Customer < ApplicationRecord
- has_many :orders, inverse_of: :customer
+class Author < ApplicationRecord
+ has_many :books, inverse_of: :author
end
-class Order < ApplicationRecord
- belongs_to :customer, inverse_of: :orders
+class Book < ApplicationRecord
+ belongs_to :author, inverse_of: :books
end
```
@@ -1700,8 +1700,8 @@ If you set the `:validate` option to `false`, then associated objects will not b
There may be times when you wish to customize the query used by `has_many`. Such customizations can be achieved via a scope block. For example:
```ruby
-class Customer < ApplicationRecord
- has_many :orders, -> { where processed: true }
+class Author < ApplicationRecord
+ has_many :books, -> { where processed: true }
end
```
@@ -1723,22 +1723,22 @@ You can use any of the standard [querying methods](active_record_querying.html)
The `where` method lets you specify the conditions that the associated object must meet.
```ruby
-class Customer < ApplicationRecord
- has_many :confirmed_orders, -> { where "confirmed = 1" },
- class_name: "Order"
+class Author < ApplicationRecord
+ has_many :confirmed_books, -> { where "confirmed = 1" },
+ class_name: "Book"
end
```
You can also set conditions via a hash:
```ruby
-class Customer < ApplicationRecord
- has_many :confirmed_orders, -> { where confirmed: true },
- class_name: "Order"
+class Author < ApplicationRecord
+ has_many :confirmed_books, -> { where confirmed: true },
+ class_name: "Book"
end
```
-If you use a hash-style `where` option, then record creation via this association will be automatically scoped using the hash. In this case, using `@customer.confirmed_orders.create` or `@customer.confirmed_orders.build` will create orders where the confirmed column has the value `true`.
+If you use a hash-style `where` option, then record creation via this association will be automatically scoped using the hash. In this case, using `@author.confirmed_books.create` or `@author.confirmed_books.build` will create books where the confirmed column has the value `true`.
##### `extending`
@@ -1749,9 +1749,9 @@ The `extending` method specifies a named module to extend the association proxy.
The `group` method supplies an attribute name to group the result set by, using a `GROUP BY` clause in the finder SQL.
```ruby
-class Customer < ApplicationRecord
- has_many :line_items, -> { group 'orders.id' },
- through: :orders
+class Author < ApplicationRecord
+ has_many :line_items, -> { group 'books.id' },
+ through: :books
end
```
@@ -1760,34 +1760,34 @@ end
You can use the `includes` method to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:
```ruby
-class Customer < ApplicationRecord
- has_many :orders
+class Author < ApplicationRecord
+ has_many :books
end
-class Order < ApplicationRecord
- belongs_to :customer
+class Book < ApplicationRecord
+ belongs_to :author
has_many :line_items
end
class LineItem < ApplicationRecord
- belongs_to :order
+ belongs_to :book
end
```
-If you frequently retrieve line items directly from customers (`@customer.orders.line_items`), then you can make your code somewhat more efficient by including line items in the association from customers to orders:
+If you frequently retrieve line items directly from authors (`@author.books.line_items`), then you can make your code somewhat more efficient by including line items in the association from authors to books:
```ruby
-class Customer < ApplicationRecord
- has_many :orders, -> { includes :line_items }
+class Author < ApplicationRecord
+ has_many :books, -> { includes :line_items }
end
-class Order < ApplicationRecord
- belongs_to :customer
+class Book < ApplicationRecord
+ belongs_to :author
has_many :line_items
end
class LineItem < ApplicationRecord
- belongs_to :order
+ belongs_to :book
end
```
@@ -1796,10 +1796,10 @@ end
The `limit` method lets you restrict the total number of objects that will be fetched through an association.
```ruby
-class Customer < ApplicationRecord
- has_many :recent_orders,
- -> { order('order_date desc').limit(100) },
- class_name: "Order",
+class Author < ApplicationRecord
+ has_many :recent_books,
+ -> { order('published_at desc').limit(100) },
+ class_name: "Book",
end
```
@@ -1812,8 +1812,8 @@ The `offset` method lets you specify the starting offset for fetching objects vi
The `order` method dictates the order in which associated objects will be received (in the syntax used by an SQL `ORDER BY` clause).
```ruby
-class Customer < ApplicationRecord
- has_many :orders, -> { order "date_confirmed DESC" }
+class Author < ApplicationRecord
+ has_many :books, -> { order "date_confirmed DESC" }
end
```
@@ -1872,11 +1872,21 @@ If you want to make sure that, upon insertion, all of the records in the
persisted association are distinct (so that you can be sure that when you
inspect the association that you will never find duplicate records), you should
add a unique index on the table itself. For example, if you have a table named
-`person_articles` and you want to make sure all the articles are unique, you could
-add the following in a migration:
+`readings` and you want to make sure the articles can only be added to a person once,
+you could add the following in a migration:
```ruby
-add_index :person_articles, :article, unique: true
+add_index :readings, [:person_id, :article_id], unique: true
+```
+
+Once you have this unique index, attempting to add the article to a person twice
+will raise an `ActiveRecord::RecordNotUnique` error:
+
+```ruby
+person = Person.create(name: 'Honda')
+article = Article.create(name: 'a1')
+person.articles << article
+person.articles << article # => ActiveRecord::RecordNotUnique
```
Note that checking for uniqueness using something like `include?` is subject
@@ -2271,10 +2281,10 @@ Association callbacks are similar to normal callbacks, but they are triggered by
You define association callbacks by adding options to the association declaration. For example:
```ruby
-class Customer < ApplicationRecord
- has_many :orders, before_add: :check_credit_limit
+class Author < ApplicationRecord
+ has_many :books, before_add: :check_credit_limit
- def check_credit_limit(order)
+ def check_credit_limit(book)
...
end
end
@@ -2285,15 +2295,15 @@ Rails passes the object being added or removed to the callback.
You can stack callbacks on a single event by passing them as an array:
```ruby
-class Customer < ApplicationRecord
- has_many :orders,
+class Author < ApplicationRecord
+ has_many :books,
before_add: [:check_credit_limit, :calculate_shipping_charges]
- def check_credit_limit(order)
+ def check_credit_limit(book)
...
end
- def calculate_shipping_charges(order)
+ def calculate_shipping_charges(book)
...
end
end
@@ -2306,10 +2316,10 @@ If a `before_add` callback throws an exception, the object does not get added to
You're not limited to the functionality that Rails automatically builds into association proxy objects. You can also extend these objects through anonymous modules, adding new finders, creators, or other methods. For example:
```ruby
-class Customer < ApplicationRecord
- has_many :orders do
- def find_by_order_prefix(order_number)
- find_by(region_id: order_number[0..2])
+class Author < ApplicationRecord
+ has_many :books do
+ def find_by_book_prefix(book_number)
+ find_by(category_id: book_number[0..2])
end
end
end
@@ -2324,8 +2334,8 @@ module FindRecentExtension
end
end
-class Customer < ApplicationRecord
- has_many :orders, -> { extending FindRecentExtension }
+class Author < ApplicationRecord
+ has_many :books, -> { extending FindRecentExtension }
end
class Supplier < ApplicationRecord
diff --git a/guides/source/caching_with_rails.md b/guides/source/caching_with_rails.md
index 3a1a1ccfe6..f26019c72e 100644
--- a/guides/source/caching_with_rails.md
+++ b/guides/source/caching_with_rails.md
@@ -521,6 +521,14 @@ class ProductsController < ApplicationController
end
```
+### A note on weak ETags
+
+Etags generated by Rails are weak by default. Weak etags allow symantically equivalent responses to have the same etags, even if their bodies do not match exactly. This is useful when we don't want the page to be regenerated for minor changes in response body. If you absolutely need to generate a strong etag, it can be assigned to the header directly.
+
+```ruby
+ response.add_header "ETag", Digest::MD5.hexdigest(response.body)
+```
+
References
----------
diff --git a/guides/source/command_line.md b/guides/source/command_line.md
index e85f9fc9c6..e865a02cbd 100644
--- a/guides/source/command_line.md
+++ b/guides/source/command_line.md
@@ -21,7 +21,7 @@ There are a few commands that are absolutely critical to your everyday usage of
* `rails console`
* `rails server`
-* `rake`
+* `bin/rails`
* `rails generate`
* `rails dbconsole`
* `rails new app_name`
@@ -39,7 +39,7 @@ INFO: You can install the rails gem by typing `gem install rails`, if you don't
```bash
$ rails new commandsapp
create
- create README.rdoc
+ create README.md
create Rakefile
create config.ru
create .gitignore
@@ -55,20 +55,21 @@ Rails will set you up with what seems like a huge amount of stuff for such a tin
### `rails server`
-The `rails server` command launches a small web server named WEBrick which comes bundled with Ruby. You'll use this any time you want to access your application through a web browser.
+The `rails server` command launches a web server named Puma which comes bundled with Rails. You'll use this any time you want to access your application through a web browser.
With no further work, `rails server` will run our new shiny Rails app:
```bash
$ cd commandsapp
$ bin/rails server
-=> Booting WEBrick
-=> Rails 5.0.0 application starting in development on http://localhost:3000
+=> Booting Puma
+=> Rails 5.0.0 application starting in development on http://0.0.0.0:3000
=> 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.2.2 (2015-06-27) [x86_64-darwin11.2.0]
-[2013-08-07 02:00:01] INFO WEBrick::HTTPServer#start: pid=69680 port=3000
+Puma 2.15.3 starting...
+* Min threads: 0, max threads: 16
+* Environment: development
+* Listening on tcp://localhost:3000
```
With just three commands we whipped up a Rails server listening on port 3000. Go to your browser and open [http://localhost:3000](http://localhost:3000), you will see a basic Rails app running.
@@ -181,7 +182,7 @@ Fire up your server using `rails server`.
```bash
$ bin/rails server
-=> Booting WEBrick...
+=> Booting Puma...
```
The URL will be [http://localhost:3000/greetings/hello](http://localhost:3000/greetings/hello).
@@ -250,10 +251,10 @@ $ bin/rails generate scaffold HighScore game:string score:integer
The generator checks that there exist the directories for models, controllers, helpers, layouts, functional and unit tests, stylesheets, creates the views, controller, model and database migration for HighScore (creating the `high_scores` table and fields), takes care of the route for the **resource**, and new tests for everything.
-The migration requires that we **migrate**, that is, run some Ruby code (living in that `20130717151933_create_high_scores.rb`) to modify the schema of our database. Which database? The SQLite3 database that Rails will create for you when we run the `rake db:migrate` command. We'll talk more about Rake in-depth in a little while.
+The migration requires that we **migrate**, that is, run some Ruby code (living in that `20130717151933_create_high_scores.rb`) to modify the schema of our database. Which database? The SQLite3 database that Rails will create for you when we run the `bin/rails db:migrate` command. We'll talk more about bin/rails in-depth in a little while.
```bash
-$ bin/rake db:migrate
+$ bin/rails db:migrate
== CreateHighScores: migrating ===============================================
-- create_table(:high_scores)
-> 0.0017s
@@ -324,7 +325,7 @@ With the `helper` method it is possible to access Rails and your application's h
### `rails dbconsole`
-`rails dbconsole` figures out which database you're using and drops you into whichever command line interface you would use with it (and figures out the command line parameters to give to it, too!). It supports MySQL, PostgreSQL, SQLite and SQLite3.
+`rails dbconsole` figures out which database you're using and drops you into whichever command line interface you would use with it (and figures out the command line parameters to give to it, too!). It supports MySQL, PostgreSQL and SQLite3.
INFO: You can also use the alias "db" to invoke the dbconsole: `rails db`.
@@ -375,44 +376,63 @@ $ bin/rails destroy model Oops
remove test/fixtures/oops.yml
```
-Rake
-----
+bin/rails
+---------
-Rake is Ruby Make, a standalone Ruby utility that replaces the Unix utility 'make', and uses a 'Rakefile' and `.rake` files to build up a list of tasks. In Rails, Rake is used for common administration tasks, especially sophisticated ones that build off of each other.
+Since Rails 5.0+ has rake commands built into the rails executable, `bin/rails` is the new default for running commands.
-You can get a list of Rake tasks available to you, which will often depend on your current directory, by typing `rake --tasks`. Each task has a description, and should help you find the thing you need.
-
-To get the full backtrace for running rake task you can pass the option `--trace` to command line, for example `rake db:create --trace`.
+You can get a list of bin/rails tasks available to you, which will often depend on your current directory, by typing `bin/rails --help`. Each task has a description, and should help you find the thing you need.
```bash
-$ bin/rake --tasks
-rake about # List versions of all Rails frameworks and the environment
-rake assets:clean # Remove old compiled assets
-rake assets:clobber # Remove compiled assets
-rake assets:precompile # Compile all the assets named in config.assets.precompile
-rake db:create # Create the database from config/database.yml for the current Rails.env
+$ bin/rails --help
+Usage: rails COMMAND [ARGS]
+
+The most common rails commands are:
+generate Generate new code (short-cut alias: "g")
+console Start the Rails console (short-cut alias: "c")
+server Start the Rails server (short-cut alias: "s")
+...
+
+All commands can be run with -h (or --help) for more information.
+
+In addition to those commands, there are:
+about List versions of all Rails ...
+assets:clean[keep] Remove old compiled assets
+assets:clobber Remove compiled assets
+assets:environment Load asset compile environment
+assets:precompile Compile all the assets ...
...
-rake log:clear # Truncates all *.log files in log/ to zero bytes (specify which logs with LOGS=test,development)
-rake middleware # Prints out your Rack middleware stack
+db:fixtures:load Loads fixtures into the ...
+db:migrate Migrate the database ...
+db:migrate:status Display status of migrations
+db:rollback Rolls the schema back to ...
+db:schema:cache:clear Clears a db/schema_cache.dump file
+db:schema:cache:dump Creates a db/schema_cache.dump file
+db:schema:dump Creates a db/schema.rb file ...
+db:schema:load Loads a schema.rb file ...
+db:seed Loads the seed data ...
+db:structure:dump Dumps the database structure ...
+db:structure:load Recreates the databases ...
+db:version Retrieves the current schema ...
...
-rake tmp:clear # Clear cache and socket files from tmp/ (narrow w/ tmp:cache:clear, tmp:sockets:clear)
-rake tmp:create # Creates tmp directories for cache, sockets, and pids
+restart Restart app by touching ...
+tmp:create Creates tmp directories ...
```
-INFO: You can also use `rake -T` to get the list of tasks.
+INFO: You can also use `bin/rails -T` to get the list of tasks.
### `about`
-`rake about` gives information about version numbers for Ruby, RubyGems, Rails, the Rails subcomponents, your application's folder, the current Rails environment name, your app's database adapter, and schema version. It is useful when you need to ask for help, check if a security patch might affect you, or when you need some stats for an existing Rails installation.
+`bin/rails about` gives information about version numbers for Ruby, RubyGems, Rails, the Rails subcomponents, your application's folder, the current Rails environment name, your app's database adapter, and schema version. It is useful when you need to ask for help, check if a security patch might affect you, or when you need some stats for an existing Rails installation.
```bash
-$ bin/rake about
+$ bin/rails about
About your application's environment
Rails version 5.0.0
Ruby version 2.2.2 (x86_64-linux)
RubyGems version 2.4.6
Rack version 1.6
JavaScript Runtime Node.js (V8)
-Middleware Rack::Sendfile, ActionDispatch::Static, Rack::Lock, #<ActiveSupport::Cache::Strategy::LocalCache::Middleware:0x007ffd131a7c88>, Rack::Runtime, Rack::MethodOverride, ActionDispatch::RequestId, Rails::Rack::Logger, ActionDispatch::ShowExceptions, ActionDispatch::DebugExceptions, ActionDispatch::RemoteIp, ActionDispatch::Reloader, ActionDispatch::Callbacks, ActiveRecord::Migration::CheckPending, ActiveRecord::ConnectionAdapters::ConnectionManagement, ActiveRecord::QueryCache, ActionDispatch::Cookies, ActionDispatch::Session::CookieStore, ActionDispatch::Flash, Rack::Head, Rack::ConditionalGet, Rack::ETag
+Middleware Rack::Sendfile, ActionDispatch::Static, ActionDispatch::LoadInterlock, #<ActiveSupport::Cache::Strategy::LocalCache::Middleware:0x007ffd131a7c88>, Rack::Runtime, Rack::MethodOverride, ActionDispatch::RequestId, Rails::Rack::Logger, ActionDispatch::ShowExceptions, ActionDispatch::DebugExceptions, ActionDispatch::RemoteIp, ActionDispatch::Reloader, ActionDispatch::Callbacks, ActiveRecord::Migration::CheckPending, ActiveRecord::ConnectionAdapters::ConnectionManagement, ActiveRecord::QueryCache, ActionDispatch::Cookies, ActionDispatch::Session::CookieStore, ActionDispatch::Flash, Rack::Head, Rack::ConditionalGet, Rack::ETag
Application root /home/foobar/commandsapp
Environment development
Database adapter sqlite3
@@ -421,22 +441,22 @@ Database schema version 20110805173523
### `assets`
-You can precompile the assets in `app/assets` using `rake assets:precompile`, and remove older compiled assets using `rake assets:clean`. The `assets:clean` task allows for rolling deploys that may still be linking to an old asset while the new assets are being built.
+You can precompile the assets in `app/assets` using `bin/rails assets:precompile`, and remove older compiled assets using `bin/rails assets:clean`. The `assets:clean` task allows for rolling deploys that may still be linking to an old asset while the new assets are being built.
-If you want to clear `public/assets` completely, you can use `rake assets:clobber`.
+If you want to clear `public/assets` completely, you can use `bin/rails assets:clobber`.
### `db`
-The most common tasks of the `db:` Rake namespace are `migrate` and `create`, and it will pay off to try out all of the migration rake tasks (`up`, `down`, `redo`, `reset`). `rake db:version` is useful when troubleshooting, telling you the current version of the database.
+The most common tasks of the `db:` bin/rails namespace are `migrate` and `create`, and it will pay off to try out all of the migration bin/rails tasks (`up`, `down`, `redo`, `reset`). `bin/rails db:version` is useful when troubleshooting, telling you the current version of the database.
More information about migrations can be found in the [Migrations](active_record_migrations.html) guide.
### `notes`
-`rake notes` will search through your code for comments beginning with FIXME, OPTIMIZE or TODO. The search is done in files with extension `.builder`, `.rb`, `.rake`, `.yml`, `.yaml`, `.ruby`, `.css`, `.js` and `.erb` for both default and custom annotations.
+`bin/rails notes` will search through your code for comments beginning with FIXME, OPTIMIZE or TODO. The search is done in files with extension `.builder`, `.rb`, `.rake`, `.yml`, `.yaml`, `.ruby`, `.css`, `.js` and `.erb` for both default and custom annotations.
```bash
-$ bin/rake notes
+$ bin/rails notes
(in /home/foobar/commandsapp)
app/controllers/admin/users_controller.rb:
* [ 20] [TODO] any other way to do this?
@@ -453,10 +473,10 @@ You can add support for new file extensions using `config.annotations.register_e
config.annotations.register_extensions("scss", "sass", "less") { |annotation| /\/\/\s*(#{annotation}):?\s*(.*)$/ }
```
-If you are looking for a specific annotation, say FIXME, you can use `rake notes:fixme`. Note that you have to lower case the annotation's name.
+If you are looking for a specific annotation, say FIXME, you can use `bin/rails notes:fixme`. Note that you have to lower case the annotation's name.
```bash
-$ bin/rake notes:fixme
+$ bin/rails notes:fixme
(in /home/foobar/commandsapp)
app/controllers/admin/users_controller.rb:
* [132] high priority for next deploy
@@ -465,10 +485,10 @@ app/models/school.rb:
* [ 17]
```
-You can also use custom annotations in your code and list them using `rake notes:custom` by specifying the annotation using an environment variable `ANNOTATION`.
+You can also use custom annotations in your code and list them using `bin/rails notes:custom` by specifying the annotation using an environment variable `ANNOTATION`.
```bash
-$ bin/rake notes:custom ANNOTATION=BUG
+$ bin/rails notes:custom ANNOTATION=BUG
(in /home/foobar/commandsapp)
app/models/article.rb:
* [ 23] Have to fix this one before pushing!
@@ -476,11 +496,11 @@ app/models/article.rb:
NOTE. When using specific annotations and custom annotations, the annotation name (FIXME, BUG etc) is not displayed in the output lines.
-By default, `rake notes` will look in the `app`, `config`, `db`, `lib` and `test` directories. If you would like to search other directories, you can provide them as a comma separated list in an environment variable `SOURCE_ANNOTATION_DIRECTORIES`.
+By default, `rails notes` will look in the `app`, `config`, `db`, `lib` and `test` directories. If you would like to search other directories, you can provide them as a comma separated list in an environment variable `SOURCE_ANNOTATION_DIRECTORIES`.
```bash
$ export SOURCE_ANNOTATION_DIRECTORIES='spec,vendor'
-$ bin/rake notes
+$ bin/rails notes
(in /home/foobar/commandsapp)
app/models/user.rb:
* [ 35] [FIXME] User should have a subscription at this point
@@ -490,7 +510,7 @@ spec/models/user_spec.rb:
### `routes`
-`rake routes` will list all of your defined routes, which is useful for tracking down routing problems in your app, or giving you a good overview of the URLs in an app you're trying to get familiar with.
+`rails routes` will list all of your defined routes, which is useful for tracking down routing problems in your app, or giving you a good overview of the URLs in an app you're trying to get familiar with.
### `test`
@@ -504,16 +524,16 @@ The `Rails.root/tmp` directory is, like the *nix /tmp directory, the holding pla
The `tmp:` namespaced tasks will help you clear and create the `Rails.root/tmp` directory:
-* `rake tmp:cache:clear` clears `tmp/cache`.
-* `rake tmp:sockets:clear` clears `tmp/sockets`.
-* `rake tmp:clear` clears all cache and sockets files.
-* `rake tmp:create` creates tmp directories for cache, sockets and pids.
+* `rails tmp:cache:clear` clears `tmp/cache`.
+* `rails tmp:sockets:clear` clears `tmp/sockets`.
+* `rails tmp:clear` clears all cache and sockets files.
+* `rails tmp:create` creates tmp directories for cache, sockets and pids.
### Miscellaneous
-* `rake stats` is great for looking at statistics on your code, displaying things like KLOCs (thousands of lines of code) and your code to test ratio.
-* `rake secret` will give you a pseudo-random key to use for your session secret.
-* `rake time:zones:all` lists all the timezones Rails knows about.
+* `rails stats` is great for looking at statistics on your code, displaying things like KLOCs (thousands of lines of code) and your code to test ratio.
+* `rails secret` will give you a pseudo-random key to use for your session secret.
+* `rails time:zones:all` lists all the timezones Rails knows about.
### Custom Rake Tasks
@@ -551,9 +571,9 @@ end
Invocation of the tasks will look like:
```bash
-$ bin/rake task_name
-$ bin/rake "task_name[value 1]" # entire argument string should be quoted
-$ bin/rake db:nothing
+$ bin/rails task_name
+$ bin/rails "task_name[value 1]" # entire argument string should be quoted
+$ bin/rails db:nothing
```
NOTE: If your need to interact with your application models, perform database queries and so on, your task should depend on the `environment` task, which will load your application code.
@@ -584,8 +604,8 @@ $ rails new . --git --database=postgresql
create tmp/pids
create Rakefile
add 'Rakefile'
- create README.rdoc
-add 'README.rdoc'
+ create README.md
+add 'README.md'
create app/controllers/application_controller.rb
add 'app/controllers/application_controller.rb'
create app/helpers/application_helper.rb
@@ -598,7 +618,7 @@ We had to create the **gitapp** directory and initialize an empty git repository
```bash
$ cat config/database.yml
-# PostgreSQL. Versions 8.2 and up are supported.
+# PostgreSQL. Versions 9.1 and up are supported.
#
# Install the pg driver:
# gem install pg
diff --git a/guides/source/configuring.md b/guides/source/configuring.md
index ba2fb4c1cf..41985c3661 100644
--- a/guides/source/configuring.md
+++ b/guides/source/configuring.md
@@ -98,13 +98,15 @@ application. Accepts a valid week day symbol (e.g. `:monday`).
* `config.exceptions_app` sets the exceptions application invoked by the ShowException middleware when an exception happens. Defaults to `ActionDispatch::PublicExceptions.new(Rails.public_path)`.
+* `config.debug_exception_response_format` sets the format used in responses when errors occur in development mode.
+
* `config.file_watcher` is the class used to detect file updates in the file system when `config.reload_classes_only_on_change` is true. Rails ships with `ActiveSupport::FileUpdateChecker`, the default, and `ActiveSupport::EventedFileUpdateChecker` (this one depends on the [listen](https://github.com/guard/listen) gem). Custom classes must conform to the `ActiveSupport::FileUpdateChecker` API.
* `config.filter_parameters` used for filtering out the parameters that
you don't want shown in the logs, such as passwords or credit card
numbers. New applications filter out passwords by adding the following `config.filter_parameters+=[:password]` in `config/initializers/filter_parameter_logging.rb`.
-* `config.force_ssl` forces all requests to be under HTTPS protocol by using `ActionDispatch::SSL` middleware.
+* `config.force_ssl` forces all requests to be served over HTTPS by using the `ActionDispatch::SSL` middleware, and sets `config.action_mailer.default_url_options` to be `{ protocol: 'https' }`. This can be configured by setting `config.ssl_options` - see the [ActionDispatch::SSL documentation](http://edgeapi.rubyonrails.org/classes/ActionDispatch/SSL.html) for details.
* `config.log_formatter` defines the formatter of the Rails logger. This option defaults to an instance of `ActiveSupport::Logger::SimpleFormatter` for all modes except production, where it defaults to `Logger::Formatter`.
@@ -159,8 +161,6 @@ pipeline is enabled. It is set to true by default.
* `config.assets.debug` disables the concatenation and compression of assets. Set to `true` by default in `development.rb`.
-* `config.assets.cache_store` defines the cache store that Sprockets will use. The default is the Rails file store.
-
* `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.
@@ -198,9 +198,9 @@ 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::SSL` forces every request to be served using HTTPS. Enabled if `config.force_ssl` is set to `true`. Options passed to this can be configured by setting `config.ssl_options`.
* `ActionDispatch::Static` is used to serve static assets. Disabled if `config.public_file_server.enabled` is `false`. Set `config.public_file_server.index_name` 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.public_file_server.index_name` 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`.
+* `ActionDispatch::LoadInterlock` allows thread safe code reloading. Disabled if `config.allow_concurrency` is `false`, which causes `Rack::Lock` to be loaded. `Rack::Lock` wraps the app in mutex so it can only be called by a single thread at a time.
* `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.
* `Rails::Rack::Logger` notifies the logs that the request has begun. After request is complete, flushes all the logs.
@@ -319,7 +319,7 @@ All these configuration options are delegated to the `I18n` library.
The MySQL adapter adds one additional configuration option:
-* `ActiveRecord::ConnectionAdapters::MysqlAdapter.emulate_booleans` controls whether Active Record will consider all `tinyint(1)` columns in a MySQL database to be booleans and is true by default.
+* `ActiveRecord::ConnectionAdapters::Mysql2Adapter.emulate_booleans` controls whether Active Record will consider all `tinyint(1)` columns in a MySQL database to be booleans and is true by default.
The schema dumper adds one additional configuration option:
@@ -335,8 +335,6 @@ The schema dumper adds one additional configuration option:
* `config.action_controller.default_static_extension` configures the extension used for cached pages. Defaults to `.html`.
-* `config.action_controller.default_charset` specifies the default character set for all renders. The default is "utf-8".
-
* `config.action_controller.include_all_helpers` configures whether all view helpers are available everywhere or are scoped to the corresponding controller. If set to `false`, `UsersHelper` methods are only available for views rendered as part of `UsersController`. If `true`, `UsersHelper` methods are available everywhere. The default is `true`.
* `config.action_controller.logger` accepts a logger conforming to the interface of Log4r or the default Ruby Logger class, which is then used to log information from Action Controller. Set to `nil` to disable logging.
@@ -347,6 +345,8 @@ The schema dumper adds one additional configuration option:
* `config.action_controller.forgery_protection_origin_check` configures whether the HTTP `Origin` header should be checked against the site's origin as an additional CSRF defense.
+* `config.action_controller.per_form_csrf_tokens` configures whether CSRF tokens are only valid for the method/action they were generated for.
+
* `config.action_controller.relative_url_root` can be used to tell Rails that you are [deploying to a subdirectory](configuring.html#deploy-to-a-subdirectory-relative-url-root). The default is `ENV['RAILS_RELATIVE_URL_ROOT']`.
* `config.action_controller.permit_all_parameters` sets all the parameters for mass assignment to be permitted by default. The default value is `false`.
@@ -369,6 +369,8 @@ The schema dumper adds one additional configuration option:
}
```
+* `config.action_dispatch.default_charset` specifies the default character set for all renders. Defaults to `nil`.
+
* `config.action_dispatch.tld_length` sets the TLD (top-level domain) length for the application. Defaults to `1`.
* `config.action_dispatch.http_auth_salt` sets the HTTP Auth salt value. Defaults
@@ -461,6 +463,8 @@ encrypted cookies salt value. Defaults to `'signed encrypted cookie'`.
* `config.action_view.automatically_disable_submit_tag` determines whether
submit_tag should automatically disable on click, this defaults to true.
+* `config.action_view.debug_missing_translation` determins whether to wrap the missing translations key in a `<span>` tag or not. This defaults to true.
+
### Configuring Action Mailer
There are a number of settings available on `config.action_mailer`:
@@ -481,7 +485,7 @@ There are a number of settings available on `config.action_mailer`:
* `config.action_mailer.raise_delivery_errors` specifies whether to raise an error if email delivery cannot be completed. It defaults to true.
-* `config.action_mailer.delivery_method` defines the delivery method and defaults to `:smtp`. See the [configuration section in the Action Mailer guide](http://guides.rubyonrails.org/action_mailer_basics.html#action-mailer-configuration) for more info.
+* `config.action_mailer.delivery_method` defines the delivery method and defaults to `:smtp`. See the [configuration section in the Action Mailer guide](action_mailer_basics.html#action-mailer-configuration) for more info.
* `config.action_mailer.perform_deliveries` specifies whether mail will actually be delivered and is true by default. It can be convenient to set it to false for testing.
@@ -529,6 +533,9 @@ There are a number of settings available on `config.action_mailer`:
* `config.action_mailer.deliver_later_queue_name` specifies the queue name for
mailers. By default this is `mailers`.
+* `config.action_mailer.perform_caching` specifies whether the mailer templates should perform fragment caching or not. By default this is false in all environments.
+
+
### Configuring Active Support
There are a few configuration options available in Active Support:
@@ -543,7 +550,7 @@ There are a few configuration options available in Active Support:
* `config.active_support.time_precision` sets the precision of JSON encoded time values. Defaults to `3`.
-* `ActiveSupport.halt_callback_chains_on_return_false` specifies whether Active Record and Active Model callback chains can be halted by returning `false` in a 'before' callback. Defaults to `true`.
+* `ActiveSupport.halt_callback_chains_on_return_false` specifies whether Active Record and Active Model callback chains can be halted by returning `false` in a 'before' callback. When set to `false`, callback chains are halted only when explicitly done so with `throw(:abort)`. When set to `true`, callback chains are halted when a callback returns false (the previous behavior before Rails 5) and a deprecation warning is given. Defaults to `true` during the deprecation period. New Rails 5 apps generate an initializer file called `callback_terminator.rb` which sets the value to `false`. This file is *not* added when running `rails app:update`, so returning `false` will still work on older apps ported to Rails 5 and display a deprecation warning to prompt users to update their code.
* `ActiveSupport::Logger.silencer` is set to `false` to disable the ability to silence logging in a block. The default is `true`.
@@ -608,6 +615,17 @@ There are a few configuration options available in Active Support:
* `config.active_job.logger` accepts a logger conforming to the interface of Log4r or the default Ruby Logger class, which is then used to log information from Active Job. You can retrieve this logger by calling `logger` on either an Active Job class or an Active Job instance. Set to `nil` to disable logging.
+### Configuring Action Cable
+
+* `config.action_cable.url` accepts a string for the URL for where
+ you are hosting your Action Cable server. You would use this option
+if you are running Action Cable servers that are separated from your
+main application.
+* `config.action_cable.mount_path` accepts a string for where to mount Action
+ Cable, as part of the main server process. Defaults to `/cable`.
+You can set this as nil to not mount Action Cable as part of your
+normal Rails server.
+
### Configuring a Database
Just about every Rails application will interact with a database. You can connect to the database by setting an environment variable `ENV['DATABASE_URL']` or by using a configuration file called `config/database.yml`.
@@ -996,7 +1014,7 @@ Below is a comprehensive list of all the initializers found in Rails in the orde
* `initialize_cache` If `Rails.cache` isn't set yet, initializes the cache by referencing the value in `config.cache_store` and stores the outcome as `Rails.cache`. If this object responds to the `middleware` method, its middleware is inserted before `Rack::Runtime` in the middleware stack.
-* `set_clear_dependencies_hook` Provides a hook for `active_record.set_dispatch_hooks` to use, which will run before this initializer. This initializer - which runs only if `cache_classes` is set to `false` - uses `ActionDispatch::Callbacks.after` to remove the constants which have been referenced during the request from the object space so that they will be reloaded during the following request.
+* `set_clear_dependencies_hook` This initializer - which runs only if `cache_classes` is set to `false` - uses `ActionDispatch::Callbacks.after` to remove the constants which have been referenced during the request from the object space so that they will be reloaded during the following request.
* `initialize_dependency_mechanism` If `config.cache_classes` is true, configures `ActiveSupport::Dependencies.mechanism` to `require` dependencies rather than `load` them.
@@ -1010,13 +1028,17 @@ Below is a comprehensive list of all the initializers found in Rails in the orde
* `active_support.initialize_beginning_of_week` Sets the default beginning of week for the application based on `config.beginning_of_week` setting, which defaults to `:monday`.
+* `active_support.set_configs` Sets up Active Support by using the settings in `config.active_support` by `send`'ing the method names as setters to `ActiveSupport` and passing the values through.
+
* `action_dispatch.configure` Configures the `ActionDispatch::Http::URL.tld_length` to be set to the value of `config.action_dispatch.tld_length`.
* `action_view.set_configs` Sets up Action View by using the settings in `config.action_view` by `send`'ing the method names as setters to `ActionView::Base` and passing the values through.
-* `action_controller.logger` Sets `ActionController::Base.logger` - if it's not already set - to `Rails.logger`.
+* `action_controller.assets_config` Initializes the `config.actions_controller.assets_dir` to the app's public directory if not explicitly configured
+
+* `action_controller.set_helpers_path` Sets Action Controller's helpers_path to the application's helpers_path
-* `action_controller.initialize_framework_caches` Sets `ActionController::Base.cache_store` - if it's not already set - to `Rails.cache`.
+* `action_controller.parameters_config` Configures strong parameters options for `ActionController::Parameters`
* `action_controller.set_configs` Sets up Action Controller by using the settings in `config.action_controller` by `send`'ing the method names as setters to `ActionController::Base` and passing the values through.
@@ -1026,13 +1048,21 @@ Below is a comprehensive list of all the initializers found in Rails in the orde
* `active_record.logger` Sets `ActiveRecord::Base.logger` - if it's not already set - to `Rails.logger`.
+* `active_record.migration_error` Configures middleware to check for pending migrations
+
+* `active_record.check_schema_cache_dump` Loads the schema cache dump if configured and available
+
+* `active_record.warn_on_records_fetched_greater_than` Enables warnings when queries return large numbers of records
+
* `active_record.set_configs` Sets up Active Record by using the settings in `config.active_record` by `send`'ing the method names as setters to `ActiveRecord::Base` and passing the values through.
* `active_record.initialize_database` Loads the database configuration (by default) from `config/database.yml` and establishes a connection for the current environment.
* `active_record.log_runtime` Includes `ActiveRecord::Railties::ControllerRuntime` which is responsible for reporting the time taken by Active Record calls for the request back to the logger.
-* `active_record.set_dispatch_hooks` Resets all reloadable connections to the database if `config.cache_classes` is set to `false`.
+* `active_record.set_reloader_hooks` Resets all reloadable connections to the database if `config.cache_classes` is set to `false`.
+
+* `active_record.add_watchable_files` Adds `schema.rb` and `structure.sql` files to watchable files
* `active_job.logger` Sets `ActiveJob::Base.logger` - if it's not already set -
to `Rails.logger`.
@@ -1115,21 +1145,48 @@ NOTE. If you are running in a multi-threaded environment, there could be a chanc
Custom configuration
--------------------
-You can configure your own code through the Rails configuration object with custom configuration under the `config.x` property. It works like this:
+You can configure your own code through the Rails configuration object with custom configuration. It works like this:
```ruby
- config.x.payment_processing.schedule = :daily
- config.x.payment_processing.retries = 3
- config.x.super_debugger = true
+ config.payment_processing.schedule = :daily
+ config.payment_processing.retries = 3
+ config.super_debugger = true
```
These configuration points are then available through the configuration object:
```ruby
- Rails.configuration.x.payment_processing.schedule # => :daily
- Rails.configuration.x.payment_processing.retries # => 3
- Rails.configuration.x.super_debugger # => true
- Rails.configuration.x.super_debugger.not_set # => nil
+ Rails.configuration.payment_processing.schedule # => :daily
+ Rails.configuration.payment_processing.retries # => 3
+ Rails.configuration.super_debugger # => true
+ Rails.configuration.super_debugger.not_set # => nil
+ ```
+
+You can also use `Rails::Application.config_for` to load whole configuration files:
+
+ ```ruby
+ # config/payment.yml:
+ production:
+ environment: production
+ merchant_id: production_merchant_id
+ public_key: production_public_key
+ private_key: production_private_key
+ development:
+ environment: sandbox
+ merchant_id: development_merchant_id
+ public_key: development_public_key
+ private_key: development_private_key
+
+ # config/application.rb
+ module MyApp
+ class Application < Rails::Application
+ config.payment = config_for(:payment)
+ end
+ end
+ ```
+
+ ```ruby
+ Rails.configuration.payment['merchant_id'] # => production_merchant_id or development_merchant_id
```
Search Engines Indexing
diff --git a/guides/source/contributing_to_ruby_on_rails.md b/guides/source/contributing_to_ruby_on_rails.md
index ed88ecf6ac..0f98d12217 100644
--- a/guides/source/contributing_to_ruby_on_rails.md
+++ b/guides/source/contributing_to_ruby_on_rails.md
@@ -105,7 +105,7 @@ $ git checkout -b testing_branch
Then you can use their remote branch to update your codebase. For example, let's say the GitHub user JohnSmith has forked and pushed to a topic branch "orange" located at https://github.com/JohnSmith/rails.
```bash
-$ git remote add JohnSmith git://github.com/JohnSmith/rails.git
+$ git remote add JohnSmith https://github.com/JohnSmith/rails.git
$ git pull JohnSmith orange
```
@@ -159,7 +159,7 @@ If you want to translate the Rails guides in your own language, follows these st
* Copy the contents of *guides/source* into your own language directory and translate them.
* Do NOT translate the HTML files, as they are automatically generated.
-To generate the guides in HTML format cd into the *guides* direcotry then run (eg. for it-IT):
+To generate the guides in HTML format cd into the *guides* directory then run (eg. for it-IT):
```bash
$ bundle install
@@ -204,7 +204,7 @@ In case you can't use the Rails development box, see [this other guide](developm
To be able to contribute code, you need to clone the Rails repository:
```bash
-$ git clone git://github.com/rails/rails.git
+$ git clone https://github.com/rails/rails.git
```
and create a dedicated branch:
@@ -357,7 +357,6 @@ $ bundle exec rake test:sqlite3
You can now run the tests as you did for `sqlite3`. The tasks are respectively:
```bash
-test:mysql
test:mysql2
test:postgresql
```
@@ -507,7 +506,7 @@ Navigate to the Rails [GitHub repository](https://github.com/rails/rails) and pr
Add the new remote to your local repository on your local machine:
```bash
-$ git remote add mine git@github.com:<your user name>/rails.git
+$ git remote add mine https://github.com:<your user name>/rails.git
```
Push to your remote:
@@ -521,7 +520,7 @@ You might have cloned your forked repository into your machine and might want to
In the directory you cloned your fork:
```bash
-$ git remote add rails git://github.com/rails/rails.git
+$ git remote add rails https://github.com/rails/rails.git
```
Download new commits and branches from the official repository:
diff --git a/guides/source/debugging_rails_applications.md b/guides/source/debugging_rails_applications.md
index 0046ff7b4e..faf475c294 100644
--- a/guides/source/debugging_rails_applications.md
+++ b/guides/source/debugging_rails_applications.md
@@ -109,18 +109,18 @@ It can also be useful to save information to log files at runtime. Rails maintai
Rails makes use of the `ActiveSupport::Logger` class to write log information. Other loggers, such as `Log4r`, may also be substituted.
-You can specify an alternative logger in `environment.rb` or any other environment file, for example:
+You can specify an alternative logger in `config/application.rb` or any other environment file, for example:
```ruby
-Rails.logger = Logger.new(STDOUT)
-Rails.logger = Log4r::Logger.new("Application Log")
+config.logger = Logger.new(STDOUT)
+config.logger = Log4r::Logger.new("Application Log")
```
Or in the `Initializer` section, add _any_ of the following
```ruby
-config.logger = Logger.new(STDOUT)
-config.logger = Log4r::Logger.new("Application Log")
+Rails.logger = Logger.new(STDOUT)
+Rails.logger = Log4r::Logger.new("Application Log")
```
TIP: By default, each log is created under `Rails.root/log/` and the log file is named after the environment in which the application is running.
@@ -311,14 +311,14 @@ processing the entire request.
For example:
```bash
-=> Booting WEBrick
+=> Booting Puma
=> Rails 5.0.0 application starting in development on http://0.0.0.0:3000
=> Run `rails server -h` for more startup options
-=> 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.2.2 (2015-04-13) [i686-linux]
-[2014-04-11 13:11:47] INFO WEBrick::HTTPServer#start: pid=6370 port=3000
+Puma 2.15.3 starting...
+* Min threads: 0, max threads: 16
+* Environment: development
+* Listening on tcp://localhost:3000
Started GET "/" for 127.0.0.1 at 2014-04-11 13:11:48 +0200
diff --git a/guides/source/development_dependencies_install.md b/guides/source/development_dependencies_install.md
index 4322f03d05..7beb8f72a9 100644
--- a/guides/source/development_dependencies_install.md
+++ b/guides/source/development_dependencies_install.md
@@ -165,7 +165,7 @@ $ bundle exec ruby -Itest path/to/test.rb -n test_name
### Active Record Setup
-The test suite of Active Record attempts to run four times: once for SQLite3, once for each of the two MySQL gems (`mysql` and `mysql2`), and once for PostgreSQL. We are going to see now how to set up the environment for them.
+Active Record's test suite runs three times: once for SQLite3, once for MySQL, and once for PostgreSQL. We are going to see now how to set up the environment for them.
WARNING: If you're working with Active Record code, you _must_ ensure that the tests pass for at least MySQL, PostgreSQL, and SQLite3. Subtle differences between the various adapters have been behind the rejection of many patches that looked OK when tested only against MySQL.
diff --git a/guides/source/documents.yaml b/guides/source/documents.yaml
index 4473eba478..2cf613f47f 100644
--- a/guides/source/documents.yaml
+++ b/guides/source/documents.yaml
@@ -135,6 +135,10 @@
work_in_progress: true
url: profiling.html
description: This guide explains how to profile your Rails applications to improve performance.
+ -
+ name: Using Rails for API-only Applications
+ url: api_app.html
+ description: This guide explains how to effectively use Rails to develop a JSON API application.
-
name: Extending Rails
diff --git a/guides/source/engines.md b/guides/source/engines.md
index 8382bde4d3..c5fc2f73b4 100644
--- a/guides/source/engines.md
+++ b/guides/source/engines.md
@@ -402,8 +402,8 @@ module Blorgh
end
```
-NOTE: The `ApplicationController` class being inherited from here is the
-`Blorgh::ApplicationController`, not an application's `ApplicationController`.
+NOTE: The `ArticlesController` class inherits from
+`Blorgh::ApplicationController`, not the application's `ApplicationController`.
The helper inside `app/helpers/blorgh/articles_helper.rb` is also namespaced:
@@ -423,7 +423,7 @@ Finally, the assets for this resource are generated in two files:
`app/assets/stylesheets/blorgh/articles.css`. You'll see how to use these a little
later.
-You can see what the engine has so far by running `rake db:migrate` at the root
+You can see what the engine has so far by running `bin/rails db:migrate` at the root
of our engine to run the migration generated by the scaffold generator, and then
running `rails server` in `test/dummy`. When you open
`http://localhost:3000/blorgh/articles` you will see the default scaffold that has
@@ -461,7 +461,7 @@ model, a comment controller and then modify the articles scaffold to display
comments and allow people to create new ones.
From the application root, run the model generator. Tell it to generate a
-`Comment` model, with the related table having two columns: a `article_id` integer
+`Comment` model, with the related table having two columns: an `article_id` integer
and `text` text column.
```bash
@@ -485,7 +485,7 @@ called `Blorgh::Comment`. Now run the migration to create our blorgh_comments
table:
```bash
-$ rake db:migrate
+$ bin/rails db:migrate
```
To show the comments on an article, edit `app/views/blorgh/articles/show.html.erb` and
@@ -694,14 +694,14 @@ engine's models can query them correctly. To copy these migrations into the
application run the following command from the `test/dummy` directory of your Rails engine:
```bash
-$ rake blorgh:install:migrations
+$ bin/rails blorgh:install:migrations
```
If you have multiple engines that need migrations copied over, use
`railties:install:migrations` instead:
```bash
-$ rake railties:install:migrations
+$ bin/rails railties:install:migrations
```
This command, when run for the first time, will copy over all the migrations
@@ -719,7 +719,7 @@ timestamp (`[timestamp_2]`) will be the current time plus a second. The reason
for this is so that the migrations for the engine are run after any existing
migrations in the application.
-To run these migrations within the context of the application, simply run `rake
+To run these migrations within the context of the application, simply run `bin/rails
db:migrate`. When accessing the engine through `http://localhost:3000/blog`, the
articles will be empty. This is because the table created inside the application is
different from the one created within the engine. Go ahead, play around with the
@@ -730,14 +730,14 @@ If you would like to run migrations only from one engine, you can do it by
specifying `SCOPE`:
```bash
-rake db:migrate SCOPE=blorgh
+bin/rails db:migrate SCOPE=blorgh
```
This may be useful if you want to revert engine's migrations before removing it.
To revert all migrations from blorgh engine you can run code such as:
```bash
-rake db:migrate SCOPE=blorgh VERSION=0
+bin/rails db:migrate SCOPE=blorgh VERSION=0
```
### Using a Class Provided by the Application
@@ -764,7 +764,7 @@ application:
rails g model user name:string
```
-The `rake db:migrate` command needs to be run here to ensure that our
+The `bin/rails db:migrate` command needs to be run here to ensure that our
application has the `users` table for future use.
Also, to keep it simple, the articles form will have a new text field called
@@ -836,7 +836,7 @@ This migration will need to be run on the application. To do that, it must first
be copied using this command:
```bash
-$ rake blorgh:install:migrations
+$ bin/rails blorgh:install:migrations
```
Notice that only _one_ migration was copied over here. This is because the first
@@ -851,7 +851,7 @@ Copied migration [timestamp]_add_author_id_to_blorgh_articles.blorgh.rb from blo
Run the migration using:
```bash
-$ rake db:migrate
+$ bin/rails db:migrate
```
Now with all the pieces in place, an action will take place that will associate
@@ -1034,6 +1034,8 @@ typical `GET` to a controller in a controller's functional test like this:
```ruby
module Blorgh
class FooControllerTest < ActionDispatch::IntegrationTest
+ include Engine.routes.url_helpers
+
def test_index
get foos_url
...
@@ -1050,6 +1052,8 @@ in your setup code:
```ruby
module Blorgh
class FooControllerTest < ActionDispatch::IntegrationTest
+ include Engine.routes.url_helpers
+
setup do
@routes = Engine.routes
end
@@ -1354,7 +1358,7 @@ need to require `admin.css` or `admin.js`. Only the gem's admin layout needs
these assets. It doesn't make sense for the host app to include
`"blorgh/admin.css"` in its stylesheets. In this situation, you should
explicitly define these assets for precompilation. This tells sprockets to add
-your engine assets when `rake assets:precompile` is triggered.
+your engine assets when `bin/rails assets:precompile` is triggered.
You can define assets for precompilation in `engine.rb`:
diff --git a/guides/source/form_helpers.md b/guides/source/form_helpers.md
index 2a289dd33a..422bc647ef 100644
--- a/guides/source/form_helpers.md
+++ b/guides/source/form_helpers.md
@@ -317,7 +317,7 @@ The Article model is directly available to users of the application, so - follow
resources :articles
```
-TIP: Declaring a resource has a number of side-affects. See [Rails Routing From the Outside In](routing.html#resource-routing-the-rails-default) for more information on setting up and using resources.
+TIP: Declaring a resource has a number of side effects. See [Rails Routing From the Outside In](routing.html#resource-routing-the-rails-default) for more information on setting up and using resources.
When dealing with RESTful resources, calls to `form_for` can get significantly easier if you rely on **record identification**. In short, you can just pass the model instance and have Rails figure out model name and the rest:
diff --git a/guides/source/getting_started.md b/guides/source/getting_started.md
index d8b590dba1..4431512eda 100644
--- a/guides/source/getting_started.md
+++ b/guides/source/getting_started.md
@@ -37,6 +37,7 @@ curve diving straight into Rails. There are several curated lists of online reso
for learning Ruby:
* [Official Ruby Programming Language website](https://www.ruby-lang.org/en/documentation/)
+* [List of Free Programming Books](https://github.com/vhf/free-programming-books/blob/master/free-programming-books.md#ruby)
Be aware that some resources, while still excellent, cover versions of Ruby as old as
1.6, and commonly 1.8, and will not include some syntax that you will see in day-to-day
@@ -92,7 +93,7 @@ current version of Ruby installed:
```bash
$ ruby -v
-ruby 2.2.2p95
+ruby 2.3.0p0
```
TIP: A number of tools exist to help you quickly install Ruby and Ruby
@@ -173,7 +174,7 @@ of the files and folders that Rails created by default:
|log/|Application log files.|
|public/|The only folder seen by the world as-is. Contains static files and compiled assets.|
|Rakefile|This file locates and loads tasks that can be run from the command line. The task definitions are defined throughout the components of Rails. Rather than changing Rakefile, you should add your own tasks by adding files to the lib/tasks directory of your application.|
-|README.rdoc|This is a brief instruction manual for your application. You should edit this file to tell others what your application does, how to set it up, and so on.|
+|README.md|This is a brief instruction manual for your application. You should edit this file to tell others what your application does, how to set it up, and so on.|
|test/|Unit tests, fixtures, and other test apparatus. These are covered in [Testing Rails Applications](testing.html).|
|tmp/|Temporary files (like cache and pid files).|
|vendor/|A place for all third-party code. In a typical Rails application this includes vendored gems.|
@@ -207,7 +208,7 @@ commented line for new apps and you can uncomment if you need it.
default to the `Gemfile` in apps generated under JRuby. You can investigate
all the supported runtimes at [ExecJS](https://github.com/rails/execjs#readme).
-This will fire up WEBrick, a web server distributed with Ruby by default. To see
+This will fire up Puma, a web server distributed with Rails by default. To see
your application in action, open a browser window and navigate to
<http://localhost:3000>. You should see the Rails default information page:
@@ -297,26 +298,30 @@ Open the file `config/routes.rb` in your editor.
Rails.application.routes.draw do
get 'welcome/index'
- # The priority is based upon order of creation:
- # first created -> highest priority.
- # See how all your routes lay out with "rake routes".
- #
- # You can have the root of your site routed with "root"
- # root 'welcome#index'
- #
- # ...
+ # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
+
+ # Serve websocket cable requests in-process
+ # mount ActionCable.server => '/cable'
+end
```
This is your application's _routing file_ which holds entries in a special
[DSL (domain-specific language)](http://en.wikipedia.org/wiki/Domain-specific_language)
that tells Rails how to connect incoming requests to
-controllers and actions. This file contains many sample routes on commented
-lines, and one of them actually shows you how to connect the root of your site
-to a specific controller and action. Find the line beginning with `root` and
-uncomment it. It should look something like the following:
+controllers and actions.
+Edit this file by adding the line of code `root 'welcome#index'`.
+It should look something like the following:
```ruby
-root 'welcome#index'
+Rails.application.routes.draw do
+ get 'welcome/index'
+
+ # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
+
+ # Serve websocket cable requests in-process
+ # mount ActionCable.server => '/cable'
+ root 'welcome#index'
+end
```
`root 'welcome#index'` tells Rails to map requests to the root of the
@@ -347,7 +352,7 @@ operations are referred to as _CRUD_ operations.
Rails provides a `resources` method which can be used to declare a standard REST
resource. You need to add the _article resource_ to the
-`config/routes.rb` as follows:
+`config/routes.rb` so the file will look as follows:
```ruby
Rails.application.routes.draw do
@@ -358,13 +363,13 @@ Rails.application.routes.draw do
end
```
-If you run `bin/rake routes`, you'll see that it has defined routes for all the
+If you run `bin/rails routes`, you'll see that it has defined routes for all the
standard RESTful actions. The meaning of the prefix column (and other columns)
will be seen later, but for now notice that Rails has inferred the
singular form `article` and makes meaningful use of the distinction.
```bash
-$ bin/rake routes
+$ bin/rails routes
Prefix Verb URI Pattern Controller#Action
articles GET /articles(.:format) articles#index
POST /articles(.:format) articles#create
@@ -558,10 +563,10 @@ this:
In this example, the `articles_path` helper is passed to the `:url` option.
To see what Rails will do with this, we look back at the output of
-`bin/rake routes`:
+`bin/rails routes`:
```bash
-$ bin/rake routes
+$ bin/rails routes
Prefix Verb URI Pattern Controller#Action
articles GET /articles(.:format) articles#index
POST /articles(.:format) articles#create
@@ -624,7 +629,7 @@ end
The `render` method here is taking a very simple hash with a key of `:plain` and
value of `params[:article].inspect`. The `params` method is the object which
represents the parameters (or fields) coming in from the form. The `params`
-method returns an `ActiveSupport::HashWithIndifferentAccess` object, which
+method returns an `ActionController::Parameters` object, which
allows you to access the keys of the hash using either strings or symbols. In
this situation, the only parameters that matter are the ones from the form.
@@ -634,7 +639,7 @@ If you re-submit the form one more time you'll now no longer get the missing
template error. Instead, you'll see something that looks like the following:
```ruby
-{"title"=>"First article!", "text"=>"This is my first article."}
+<ActionController::Parameters {"title"=>"First Article!", "text"=>"This is my first article."} permitted: false>
```
This action is now displaying the parameters for the article that are coming in
@@ -652,7 +657,7 @@ run this command in your terminal:
$ bin/rails generate model Article title:string text:text
```
-With that command we told Rails that we want a `Article` model, together
+With that command we told Rails that we want an `Article` model, together
with a _title_ attribute of type string, and a _text_ attribute
of type text. Those attributes are automatically added to the `articles`
table in the database and mapped to the `Article` model.
@@ -701,10 +706,10 @@ two timestamp fields to allow Rails to track article creation and update times.
TIP: For more information about migrations, refer to [Rails Database Migrations]
(migrations.html).
-At this point, you can use a rake command to run the migration:
+At this point, you can use a bin/rails command to run the migration:
```bash
-$ bin/rake db:migrate
+$ bin/rails db:migrate
```
Rails will execute this migration command and tell you it created the Articles
@@ -721,7 +726,7 @@ NOTE. Because you're working in the development environment by default, this
command will apply to the database defined in the `development` section of your
`config/database.yml` file. If you would like to execute migrations in another
environment, for instance in production, you must explicitly pass it when
-invoking the command: `bin/rake db:migrate RAILS_ENV=production`.
+invoking the command: `bin/rails db:migrate RAILS_ENV=production`.
### Saving data in the controller
@@ -766,7 +771,7 @@ Why do you have to bother? The ability to grab and automatically assign all
controller parameters to your model in one shot makes the programmer's job
easier, but this convenience also allows malicious use. What if a request to
the server was crafted to look like a new article form submit but also included
-extra fields with values that violated your applications integrity? They would
+extra fields with values that violated your application's integrity? They would
be 'mass assigned' into your model and then into the database along with the
good stuff - potentially breaking your application or worse.
@@ -808,7 +813,7 @@ If you submit the form again now, Rails will complain about not finding the
`show` action. That's not very useful though, so let's add the `show` action
before proceeding.
-As we have seen in the output of `bin/rake routes`, the route for `show` action is
+As we have seen in the output of `bin/rails routes`, the route for `show` action is
as follows:
```
@@ -870,7 +875,7 @@ Visit <http://localhost:3000/articles/new> and give it a try!
### Listing all articles
We still need a way to list all our articles, so let's do that.
-The route for this as per output of `bin/rake routes` is:
+The route for this as per output of `bin/rails routes` is:
```
articles GET /articles(.:format) articles#index
@@ -1365,7 +1370,7 @@ Then do the same for the `app/views/articles/edit.html.erb` view:
We're now ready to cover the "D" part of CRUD, deleting articles from the
database. Following the REST convention, the route for
-deleting articles as per output of `bin/rake routes` is:
+deleting articles as per output of `bin/rails routes` is:
```ruby
DELETE /articles/:id(.:format) articles#destroy
@@ -1539,6 +1544,11 @@ This is very similar to the `Article` model that you saw earlier. The difference
is the line `belongs_to :article`, which sets up an Active Record _association_.
You'll learn a little about associations in the next section of this guide.
+The (`:references`) keyword used in the bash command is a special data type for models.
+It creates a new column on your database table with the provided model name appended with an `_id`
+that can hold integer values. You can get a better understanding after analyzing the
+`db/schema.rb` file below.
+
In addition to the model, Rails has also made a migration to create the
corresponding database table:
@@ -1561,7 +1571,7 @@ for it, and a foreign key constraint that points to the `id` column of the `arti
table. Go ahead and run the migration:
```bash
-$ bin/rake db:migrate
+$ bin/rails db:migrate
```
Rails is smart enough to only execute the migrations that have not already been
diff --git a/guides/source/i18n.md b/guides/source/i18n.md
index 42589110b1..56b0c6c812 100644
--- a/guides/source/i18n.md
+++ b/guides/source/i18n.md
@@ -25,7 +25,7 @@ After reading this guide, you will know:
* How I18n works in Ruby on Rails
* How to correctly use I18n into a RESTful application in various ways
-* How to use I18n to translate ActiveRecord errors or ActionMailer E-mail subjects
+* How to use I18n to translate Active Record errors or Action Mailer E-mail subjects
* Some other tools to go further with the translation process of your application
--------------------------------------------------------------------------------
@@ -470,7 +470,7 @@ OK! Now let's add a timestamp to the view, so we can demo the **date/time locali
```erb
# app/views/home/index.html.erb
<h1><%=t :hello_world %></h1>
-<p><%= flash[:notice] %></p
+<p><%= flash[:notice] %></p>
<p><%= l Time.now, format: :short %></p>
```
diff --git a/guides/source/initialization.md b/guides/source/initialization.md
index 7bf7eebb62..156f9c92b4 100644
--- a/guides/source/initialization.md
+++ b/guides/source/initialization.md
@@ -157,7 +157,7 @@ snippet.
If we had used `s` rather than `server`, Rails would have used the `aliases`
defined here to find the matching command.
-### `rails/commands/command_tasks.rb`
+### `rails/commands/commands_tasks.rb`
When one types a valid Rails command, `run_command!` a method of the same name
is called. If Rails doesn't recognize the command, it tries to run a Rake task
@@ -530,16 +530,17 @@ This file is responsible for requiring all the individual frameworks of Rails:
require "rails"
%w(
- active_record
- action_controller
- action_view
- action_mailer
- active_job
- rails/test_unit
- sprockets
-).each do |framework|
+ active_record/railtie
+ action_controller/railtie
+ action_view/railtie
+ action_mailer/railtie
+ active_job/railtie
+ action_cable/engine
+ rails/test_unit/railtie
+ sprockets/railtie
+).each do |railtie|
begin
- require "#{framework}/railtie"
+ require "#{railtie}"
rescue LoadError
end
end
diff --git a/guides/source/layout.html.erb b/guides/source/layout.html.erb
index 1005057ca9..6db76b528e 100644
--- a/guides/source/layout.html.erb
+++ b/guides/source/layout.html.erb
@@ -29,14 +29,11 @@
More Ruby on Rails
</span>
<ul class="more-info-links s-hidden">
- <li class="more-info"><a href="http://rubyonrails.org/">Overview</a></li>
- <li class="more-info"><a href="http://rubyonrails.org/download">Download</a></li>
- <li class="more-info"><a href="http://rubyonrails.org/deploy">Deploy</a></li>
- <li class="more-info"><a href="https://github.com/rails/rails">Code</a></li>
- <li class="more-info"><a href="http://rubyonrails.org/screencasts">Screencasts</a></li>
- <li class="more-info"><a href="http://rubyonrails.org/documentation">Documentation</a></li>
- <li class="more-info"><a href="http://rubyonrails.org/community">Community</a></li>
<li class="more-info"><a href="http://weblog.rubyonrails.org/">Blog</a></li>
+ <li class="more-info"><a href="http://guides.rubyonrails.org/">Guides</a></li>
+ <li class="more-info"><a href="http://api.rubyonrails.org/">API</a></li>
+ <li class="more-info"><a href="http://stackoverflow.com/questions/tagged/ruby-on-rails">Ask for help</a></li>
+ <li class="more-info"><a href="https://github.com/rails/rails">Contribute on GitHub</a></li>
</ul>
</div>
</div>
diff --git a/guides/source/layouts_and_rendering.md b/guides/source/layouts_and_rendering.md
index 4bb364c0f8..83173e8d75 100644
--- a/guides/source/layouts_and_rendering.md
+++ b/guides/source/layouts_and_rendering.md
@@ -238,7 +238,7 @@ TIP: This is useful when you're rendering a small snippet of HTML code.
However, you might want to consider moving it to a template file if the markup
is complex.
-NOTE: This option will escape HTML entities if the string is not HTML safe.
+NOTE: When using `html:` option, HTML entities will be escaped if the string is not marked as HTML safe by using `html_safe` method.
#### Rendering JSON
@@ -555,7 +555,7 @@ class Admin::ProductsController < AdminController
end
```
-The lookup order for a `admin/products#index` action will be:
+The lookup order for an `admin/products#index` action will be:
* `app/views/admin/products/`
* `app/views/admin/`
@@ -700,7 +700,7 @@ This would detect that there are no books with the specified ID, populate the `@
### Using `head` To Build Header-Only Responses
-The `head` method can be used to send responses with only headers to the browser. It provides a more obvious alternative to calling `render :nothing`. The `head` method accepts a number or symbol (see [reference table](#the-status-option)) representing a HTTP status code. The options argument is interpreted as a hash of header names and values. For example, you can return only an error header:
+The `head` method can be used to send responses with only headers to the browser. The `head` method accepts a number or symbol (see [reference table](#the-status-option)) representing a HTTP status code. The options argument is interpreted as a hash of header names and values. For example, you can return only an error header:
```ruby
head :bad_request
@@ -1157,14 +1157,12 @@ To pass a local variable to a partial in only specific cases use the `local_assi
* `_articles.html.erb`
```erb
- <%= content_tag_for :article, article do |article| %>
- <h2><%= article.title %></h2>
+ <h2><%= article.title %></h2>
- <% if local_assigns[:full] %>
- <%= simple_format article.body %>
- <% else %>
- <%= truncate article.body %>
- <% end %>
+ <% if local_assigns[:full] %>
+ <%= simple_format article.body %>
+ <% else %>
+ <%= truncate article.body %>
<% end %>
```
diff --git a/guides/source/maintenance_policy.md b/guides/source/maintenance_policy.md
index 50308f505a..f99b6ebd31 100644
--- a/guides/source/maintenance_policy.md
+++ b/guides/source/maintenance_policy.md
@@ -44,7 +44,7 @@ from.
In special situations, where someone from the Core Team agrees to support more series,
they are included in the list of supported series.
-**Currently included series:** `4.2.Z`, `4.1.Z` (Supported by Rafael França).
+**Currently included series:** `5.0.Z`.
Security Issues
---------------
@@ -59,7 +59,7 @@ be built from 1.2.2, and then added to the end of 1-2-stable. This means that
security releases are easy to upgrade to if you're running the latest version
of Rails.
-**Currently included series:** `4.2.Z`, `4.1.Z`.
+**Currently included series:** `5.0.Z`, `4.2.Z`.
Severe Security Issues
----------------------
@@ -68,7 +68,7 @@ For severe security issues we will provide new versions as above, and also the
last major release series will receive patches and new versions. The
classification of the security issue is judged by the core team.
-**Currently included series:** `4.2.Z`, `4.1.Z`, `3.2.Z`.
+**Currently included series:** `5.0.Z`, `4.2.Z`.
Unsupported Release Series
--------------------------
diff --git a/guides/source/plugins.md b/guides/source/plugins.md
index ae8c30515a..8f055f8fe3 100644
--- a/guides/source/plugins.md
+++ b/guides/source/plugins.md
@@ -37,7 +37,7 @@ different rails applications using RubyGems and Bundler if desired.
Rails ships with a `rails plugin new` command which creates a
skeleton for developing any kind of Rails extension with the ability
-to run integration tests using a dummy Rails application. Create your
+to run integration tests using a dummy Rails application. Create your
plugin with the command:
```bash
@@ -54,7 +54,7 @@ Testing Your Newly Generated Plugin
-----------------------------------
You can navigate to the directory that contains the plugin, run the `bundle install` command
- and run the one generated test using the `rake` command.
+ and run the one generated test using the `bin/test` command.
You should see:
@@ -83,13 +83,23 @@ class CoreExtTest < ActiveSupport::TestCase
end
```
-Run `rake` to run the test. This test should fail because we haven't implemented the `to_squawk` method:
+Run `bin/test` to run the test. This test should fail because we haven't implemented the `to_squawk` method:
```bash
- 1) Error:
- CoreExtTest#test_to_squawk_prepends_the_word_squawk:
- NoMethodError: undefined method `to_squawk' for "Hello World":String
- /path/to/yaffle/test/core_ext_test.rb:5:in `test_to_squawk_prepends_the_word_squawk'
+E
+
+Error:
+CoreExtTest#test_to_squawk_prepends_the_word_squawk:
+NoMethodError: undefined method `to_squawk' for "Hello World":String
+
+
+bin/test /path/to/yaffle/test/core_ext_test.rb:4
+
+.
+
+Finished in 0.003358s, 595.6483 runs/s, 297.8242 assertions/s.
+
+2 runs, 1 assertions, 0 failures, 1 errors, 0 skips
```
Great - now you are ready to start development.
@@ -117,7 +127,7 @@ String.class_eval do
end
```
-To test that your method does what it says it does, run the unit tests with `rake` from your plugin directory.
+To test that your method does what it says it does, run the unit tests with `bin/test` from your plugin directory.
```bash
2 runs, 2 assertions, 0 failures, 0 errors, 0 skips
@@ -192,20 +202,34 @@ class ActsAsYaffleTest < ActiveSupport::TestCase
end
```
-When you run `rake`, you should see the following:
+When you run `bin/test`, you should see the following:
```
- 1) Error:
- ActsAsYaffleTest#test_a_hickwalls_yaffle_text_field_should_be_last_squawk:
- NameError: uninitialized constant ActsAsYaffleTest::Hickwall
- /path/to/yaffle/test/acts_as_yaffle_test.rb:6:in `test_a_hickwalls_yaffle_text_field_should_be_last_squawk'
+# Running:
+
+..E
+
+Error:
+ActsAsYaffleTest#test_a_wickwalls_yaffle_text_field_should_be_last_tweet:
+NameError: uninitialized constant ActsAsYaffleTest::Wickwall
+
+
+bin/test /path/to/yaffle/test/acts_as_yaffle_test.rb:8
+
+E
+
+Error:
+ActsAsYaffleTest#test_a_hickwalls_yaffle_text_field_should_be_last_squawk:
+NameError: uninitialized constant ActsAsYaffleTest::Hickwall
- 2) Error:
- ActsAsYaffleTest#test_a_wickwalls_yaffle_text_field_should_be_last_tweet:
- NameError: uninitialized constant ActsAsYaffleTest::Wickwall
- /path/to/yaffle/test/acts_as_yaffle_test.rb:10:in `test_a_wickwalls_yaffle_text_field_should_be_last_tweet'
- 4 runs, 2 assertions, 0 failures, 2 errors, 0 skips
+bin/test /path/to/yaffle/test/acts_as_yaffle_test.rb:4
+
+
+
+Finished in 0.004812s, 831.2949 runs/s, 415.6475 assertions/s.
+
+4 runs, 2 assertions, 0 failures, 2 errors, 0 skips
```
This tells us that we don't have the necessary models (Hickwall and Wickwall) that we are trying to test.
@@ -223,7 +247,7 @@ and migrating the database. First, run:
```bash
$ cd test/dummy
-$ bin/rake db:migrate
+$ bin/rails db:migrate
```
While you are here, change the Hickwall and Wickwall models so that they know that they are supposed to act
@@ -272,23 +296,34 @@ class ApplicationRecord < ActiveRecord::Base
end
```
-You can then return to the root directory (`cd ../..`) of your plugin and rerun the tests using `rake`.
+You can then return to the root directory (`cd ../..`) of your plugin and rerun the tests using `bin/test`.
```
- 1) Error:
- ActsAsYaffleTest#test_a_hickwalls_yaffle_text_field_should_be_last_squawk:
- NoMethodError: undefined method `yaffle_text_field' for #<Class:0x007fd105e3b218>
- activerecord (4.1.5) lib/active_record/dynamic_matchers.rb:26:in `method_missing'
- /path/to/yaffle/test/acts_as_yaffle_test.rb:6:in `test_a_hickwalls_yaffle_text_field_should_be_last_squawk'
+# Running:
+
+.E
+
+Error:
+ActsAsYaffleTest#test_a_hickwalls_yaffle_text_field_should_be_last_squawk:
+NoMethodError: undefined method `yaffle_text_field' for #<Class:0x0055974ebbe9d8>
+
+
+bin/test /path/to/yaffle/test/acts_as_yaffle_test.rb:4
+
+E
+
+Error:
+ActsAsYaffleTest#test_a_wickwalls_yaffle_text_field_should_be_last_tweet:
+NoMethodError: undefined method `yaffle_text_field' for #<Class:0x0055974eb8cfc8>
+
+
+bin/test /path/to/yaffle/test/acts_as_yaffle_test.rb:8
- 2) Error:
- ActsAsYaffleTest#test_a_wickwalls_yaffle_text_field_should_be_last_tweet:
- NoMethodError: undefined method `yaffle_text_field' for #<Class:0x007fd105e409c0>
- activerecord (4.1.5) lib/active_record/dynamic_matchers.rb:26:in `method_missing'
- /path/to/yaffle/test/acts_as_yaffle_test.rb:10:in `test_a_wickwalls_yaffle_text_field_should_be_last_tweet'
+.
- 4 runs, 2 assertions, 0 failures, 2 errors, 0 skips
+Finished in 0.008263s, 484.0999 runs/s, 242.0500 assertions/s.
+4 runs, 2 assertions, 0 failures, 2 errors, 0 skips
```
Getting closer... Now we will implement the code of the `acts_as_yaffle` method to make the tests pass.
@@ -321,7 +356,7 @@ class ApplicationRecord < ActiveRecord::Base
end
```
-When you run `rake`, you should see the tests all pass:
+When you run `bin/test`, you should see the tests all pass:
```bash
4 runs, 4 assertions, 0 failures, 0 errors, 0 skips
@@ -400,7 +435,7 @@ class ApplicationRecord < ActiveRecord::Base
end
```
-Run `rake` one final time and you should see:
+Run `bin/test` one final time and you should see:
```
6 runs, 6 assertions, 0 failures, 0 errors, 0 skips
diff --git a/guides/source/rails_application_templates.md b/guides/source/rails_application_templates.md
index edd54826cf..3b773d84f8 100644
--- a/guides/source/rails_application_templates.md
+++ b/guides/source/rails_application_templates.md
@@ -22,11 +22,11 @@ $ rails new blog -m ~/template.rb
$ rails new blog -m http://example.com/template.rb
```
-You can use the rake task `rails:template` to apply templates to an existing Rails application. The location of the template needs to be passed in to an environment variable named LOCATION. Again, this can either be path to a file or a URL.
+You can use the task `app:template` to apply templates to an existing Rails application. The location of the template needs to be passed in to an environment variable named LOCATION. Again, this can either be path to a file or a URL.
```bash
-$ bin/rake rails:template LOCATION=~/template.rb
-$ bin/rake rails:template LOCATION=http://example.com/template.rb
+$ bin/rails app:template LOCATION=~/template.rb
+$ bin/rails app:template LOCATION=http://example.com/template.rb
```
Template API
@@ -38,7 +38,7 @@ The Rails templates API is easy to understand. Here's an example of a typical Ra
# template.rb
generate(:scaffold, "person name:string")
route "root to: 'people#index'"
-rake("db:migrate")
+rails_command("db:migrate")
after_bundle do
git :init
@@ -175,18 +175,24 @@ Executes an arbitrary command. Just like the backticks. Let's say you want to re
run "rm README.rdoc"
```
-### rake(command, options = {})
+### rails_command(command, options = {})
-Runs the supplied rake tasks in the Rails application. Let's say you want to migrate the database:
+Runs the supplied task in the Rails application. Let's say you want to migrate the database:
```ruby
-rake "db:migrate"
+rails_command "db:migrate"
```
-You can also run rake tasks with a different Rails environment:
+You can also run tasks with a different Rails environment:
```ruby
-rake "db:migrate", env: 'production'
+rails_command "db:migrate", env: 'production'
+```
+
+You can also run tasks as a super-user:
+
+```ruby
+rails_command "log:clear", sudo: true
```
### route(routing_code)
@@ -226,7 +232,7 @@ CODE
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?")
+rails_command("rails:freeze:gems") if yes?("Freeze rails gems?")
# no?(question) acts just the opposite.
```
diff --git a/guides/source/rails_on_rack.md b/guides/source/rails_on_rack.md
index 273fbc08e2..3b61d65df5 100644
--- a/guides/source/rails_on_rack.md
+++ b/guides/source/rails_on_rack.md
@@ -96,7 +96,7 @@ NOTE: `ActionDispatch::MiddlewareStack` is Rails equivalent of `Rack::Builder`,
Rails has a handy rake task for inspecting the middleware stack in use:
```bash
-$ bin/rake middleware
+$ bin/rails middleware
```
For a freshly generated Rails application, this might produce something like:
@@ -104,7 +104,7 @@ For a freshly generated Rails application, this might produce something like:
```ruby
use Rack::Sendfile
use ActionDispatch::Static
-use Rack::Lock
+use ActionDispatch::LoadInterlock
use #<ActiveSupport::Cache::Strategy::LocalCache::Middleware:0x000000029a0838>
use Rack::Runtime
use Rack::MethodOverride
@@ -171,14 +171,14 @@ Add the following lines to your application configuration:
```ruby
# config/application.rb
-config.middleware.delete Rack::Lock
+config.middleware.delete Rack::Runtime
```
-And now if you inspect the middleware stack, you'll find that `Rack::Lock` is
+And now if you inspect the middleware stack, you'll find that `Rack::Runtime` is
not a part of it.
```bash
-$ bin/rake middleware
+$ bin/rails middleware
(in /Users/lifo/Rails/blog)
use ActionDispatch::Static
use #<ActiveSupport::Cache::Strategy::LocalCache::Middleware:0x00000001c304c8>
@@ -219,6 +219,10 @@ Much of Action Controller's functionality is implemented as Middlewares. The fol
* Sets `env["rack.multithread"]` flag to `false` and wraps the application within a Mutex.
+**`ActionDispatch::LoadInterlock`**
+
+* Used for thread safe code reloading during development.
+
**`ActiveSupport::Cache::Strategy::LocalCache::Middleware`**
* Used for memory caching. This cache is not thread safe.
diff --git a/guides/source/routing.md b/guides/source/routing.md
index 2b1254f7a0..bd3e236a2b 100644
--- a/guides/source/routing.md
+++ b/guides/source/routing.md
@@ -392,7 +392,7 @@ The comments resource here will have the following routes generated for it:
### Routing concerns
-Routing Concerns allows you to declare common routes that can be reused inside other resources and routes. To define a concern:
+Routing concerns allow you to declare common routes that can be reused inside other resources and routes. To define a concern:
```ruby
concern :commentable do
@@ -706,6 +706,8 @@ end
NOTE: Request constraints work by calling a method on the [Request object](action_controller_overview.html#the-request-object) with the same name as the hash key and then compare the return value with the hash value. Therefore, constraint values should match the corresponding Request object method return type. For example: `constraints: { subdomain: 'api' }` will match an `api` subdomain as expected, however using a symbol `constraints: { subdomain: :api }` will not, because `request.subdomain` returns `'api'` as a String.
+NOTE: There is an exception for the `format` constraint: while it's a method on the Request object, it's also an implicit optional parameter on every path. Segment constraints take precedence and the `format` constraint is only applied as such when enforced through a hash. For example, `get 'foo', constraints: { format: 'json' }` will match `GET /foo` because the format is optional by default. However, you can [use a lambda](#advanced-constraints) like in `get 'foo', constraints: lambda { |req| req.format == :json }` and the route will only match explicit JSON requests.
+
### Advanced Constraints
If you have a more advanced constraint, you can provide an object that responds to `matches?` that Rails should use. Let's say you wanted to route all users on a blacklist to the `BlacklistController`. You could do:
@@ -1116,7 +1118,7 @@ Rails offers facilities for inspecting and testing your routes.
### Listing Existing Routes
-To get a complete list of the available routes in your application, visit `http://localhost:3000/rails/info/routes` in your browser while your server is running in the **development** environment. You can also execute the `rake routes` command in your terminal to produce the same output.
+To get a complete list of the available routes in your application, visit `http://localhost:3000/rails/info/routes` in your browser while your server is running in the **development** environment. You can also execute the `rails routes` command in your terminal to produce the same output.
Both methods will list all of your routes, in the same order that they appear in `config/routes.rb`. For each route, you'll see:
@@ -1125,7 +1127,7 @@ Both methods will list all of your routes, in the same order that they appear in
* The URL pattern to match
* The routing parameters for the route
-For example, here's a small section of the `rake routes` output for a RESTful route:
+For example, here's a small section of the `rails routes` output for a RESTful route:
```
users GET /users(.:format) users#index
@@ -1134,13 +1136,24 @@ For example, here's a small section of the `rake routes` output for a RESTful ro
edit_user GET /users/:id/edit(.:format) users#edit
```
-You may restrict the listing to the routes that map to a particular controller setting the `CONTROLLER` environment variable:
+You can search through your routes with the grep option: -g. This outputs any routes that partially match the URL helper method name, the HTTP verb, or the URL path.
+
+```
+$ bin/rails routes -g new_comment
+$ bin/rails routes -g POST
+$ bin/rails routes -g admin
+```
+
+If you only want to see the routes that map to a specific controller, there's the -c option.
-```bash
-$ CONTROLLER=users bin/rake routes
+```
+$ bin/rails routes -c users
+$ bin/rails routes -c admin/users
+$ bin/rails routes -c Comments
+$ bin/rails routes -c Articles::CommentsController
```
-TIP: You'll find that the output from `rake routes` is much more readable if you widen your terminal window until the output lines don't wrap.
+TIP: You'll find that the output from `rails routes` is much more readable if you widen your terminal window until the output lines don't wrap.
### Testing Routes
diff --git a/guides/source/security.md b/guides/source/security.md
index 1d0e87d831..98324141cc 100644
--- a/guides/source/security.md
+++ b/guides/source/security.md
@@ -23,7 +23,7 @@ Web application frameworks are made to help developers build web applications. S
In general there is no such thing as plug-n-play security. Security depends on the people using the framework, and sometimes on the development method. And it depends on all layers of a web application environment: The back-end storage, the web server and the web application itself (and possibly other layers or applications).
-The Gartner Group however estimates that 75% of attacks are at the web application layer, and found out "that out of 300 audited sites, 97% are vulnerable to attack". This is because web applications are relatively easy to attack, as they are simple to understand and manipulate, even by the lay person.
+The Gartner Group, however, estimates that 75% of attacks are at the web application layer, and found out "that out of 300 audited sites, 97% are vulnerable to attack". This is because web applications are relatively easy to attack, as they are simple to understand and manipulate, even by the lay person.
The threats against web applications include user account hijacking, bypass of access control, reading or modifying sensitive data, or presenting fraudulent content. Or an attacker might be able to install a Trojan horse program or unsolicited e-mail sending software, aim at financial enrichment or cause brand name damage by modifying company resources. In order to prevent attacks, minimize their impact and remove points of attack, first of all, you have to fully understand the attack methods in order to find the correct countermeasures. That is what this guide aims at.
@@ -62,7 +62,7 @@ Many web applications have an authentication system: a user provides a user name
Hence, the cookie serves as temporary authentication for the web application. Anyone who seizes a cookie from someone else, may use the web application as this user - with possibly severe consequences. Here are some ways to hijack a session, and their countermeasures:
-* Sniff the cookie in an insecure network. A wireless LAN can be an example of such a network. In an unencrypted wireless LAN it is especially easy to listen to the traffic of all connected clients. For the web application builder this means to _provide a secure connection over SSL_. In Rails 3.1 and later, this could be accomplished by always forcing SSL connection in your application config file:
+* Sniff the cookie in an insecure network. A wireless LAN can be an example of such a network. In an unencrypted wireless LAN, it is especially easy to listen to the traffic of all connected clients. For the web application builder this means to _provide a secure connection over SSL_. In Rails 3.1 and later, this could be accomplished by always forcing SSL connection in your application config file:
```ruby
config.force_ssl = true
@@ -102,7 +102,7 @@ Thus the session becomes a more secure place to store data. The encryption is
done using a server-side secret key `secrets.secret_key_base` stored in
`config/secrets.yml`.
-That means the security of this storage depends on this secret (and on the digest algorithm, which defaults to SHA1, for compatibility). So _don't use a trivial secret, i.e. a word from a dictionary, or one which is shorter than 30 characters, use `rake secret` instead_.
+That means the security of this storage depends on this secret (and on the digest algorithm, which defaults to SHA1, for compatibility). So _don't use a trivial secret, i.e. a word from a dictionary, or one which is shorter than 30 characters, use `rails secret` instead_.
`secrets.secret_key_base` is used for specifying a key which allows sessions for the application to be verified against a known secure key to prevent tampering. Applications get `secrets.secret_key_base` initialized to a random key present in `config/secrets.yml`, e.g.:
@@ -787,7 +787,7 @@ The following is an excerpt from the [Js.Yamanner@m](http://www.symantec.com/sec
var IDList = ''; var CRumb = ''; function makeRequest(url, Func, Method,Param) { ...
```
-The worms exploits a hole in Yahoo's HTML/JavaScript filter, which usually filters all target and onload attributes from tags (because there can be JavaScript). The filter is applied only once, however, so the onload attribute with the worm code stays in place. This is a good example why blacklist filters are never complete and why it is hard to allow HTML/JavaScript in a web application.
+The worms exploit a hole in Yahoo's HTML/JavaScript filter, which usually filters all targets and onload attributes from tags (because there can be JavaScript). The filter is applied only once, however, so the onload attribute with the worm code stays in place. This is a good example why blacklist filters are never complete and why it is hard to allow HTML/JavaScript in a web application.
Another proof-of-concept webmail worm is Nduja, a cross-domain worm for four Italian webmail services. Find more details on [Rosario Valotta's paper](http://www.xssed.com/news/37/Nduja_Connection_A_cross_webmail_worm_XWW/). Both webmail worms have the goal to harvest email addresses, something a criminal hacker could make money with.
diff --git a/guides/source/testing.md b/guides/source/testing.md
index a4b62955c5..09eec7a64c 100644
--- a/guides/source/testing.md
+++ b/guides/source/testing.md
@@ -54,9 +54,9 @@ NOTE: Your tests are run under `RAILS_ENV=test`.
### Rails meets Minitest
-If you remember when you used the `rails generate model` command from the
+If you remember, we used the `rails generate model` command in the
[Getting Started with Rails](getting_started.html) guide. We created our first
-model among other things it created test stubs in the `test` directory:
+model, and among other things it created test stubs in the `test` directory:
```bash
$ bin/rails generate model article title:string body:text
@@ -85,13 +85,13 @@ A line by line examination of this file will help get you oriented to Rails test
require 'test_helper'
```
-By requiring this file, `test_helper.rb` the default configuration to run our tests is loaded. We will include this with all the tests we write, so any methods added to this file are available to all your tests.
+By requiring this file, `test_helper.rb` the default configuration to run our tests is loaded. We will include this with all the tests we write, so any methods added to this file are available to all our tests.
```ruby
class ArticleTest < ActiveSupport::TestCase
```
-The `ArticleTest` class defines a _test case_ because it inherits from `ActiveSupport::TestCase`. `ArticleTest` thus has all the methods available from `ActiveSupport::TestCase`. Later in this guide, you'll see some of the methods it gives you.
+The `ArticleTest` class defines a _test case_ because it inherits from `ActiveSupport::TestCase`. `ArticleTest` thus has all the methods available from `ActiveSupport::TestCase`. Later in this guide, we'll see some of the methods it gives us.
Any method defined within a class inherited from `Minitest::Test`
(which is the superclass of `ActiveSupport::TestCase`) that begins with `test_` (case sensitive) is simply called a test. So, methods defined as `test_password` and `test_valid_password` are legal test names and are run automatically when the test case is run.
@@ -129,7 +129,7 @@ An assertion is a line of code that evaluates an object (or expression) for expe
* does this line of code throw an exception?
* is the user's password greater than 5 characters?
-Every test must contain at least one assertion, with no restriction as to how many assertions are allowed. Only when all the assertions are successful will the test pass.
+Every test may contain one or more assertions, with no restriction as to how many assertions are allowed. Only when all the assertions are successful will the test pass.
#### Your first failing test
@@ -265,7 +265,7 @@ By now you've caught a glimpse of some of the assertions that are available. Ass
Here's an extract of the assertions you can use with
[`Minitest`](https://github.com/seattlerb/minitest), the default testing library
used by Rails. The `[msg]` parameter is an optional string message you can
-specify to make your test failure messages clearer. It's not required.
+specify to make your test failure messages clearer.
| Assertion | Purpose |
| ---------------------------------------------------------------- | ------- |
@@ -287,7 +287,7 @@ specify to make your test failure messages clearer. It's not required.
| `assert_not_in_delta( expected, actual, [delta], [msg] )` | Ensures that the numbers `expected` and `actual` are not within `delta` of each other.|
| `assert_throws( symbol, [msg] ) { block }` | Ensures that the given block throws the symbol.|
| `assert_raises( exception1, exception2, ... ) { block }` | Ensures that the given block raises one of the given exceptions.|
-| `assert_nothing_raised( exception1, exception2, ... ) { block }` | Ensures that the given block doesn't raise one of the given exceptions.|
+| `assert_nothing_raised { block }` | Ensures that the given block doesn't raise any 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 an instance of `class` or is descending from it.|
@@ -298,7 +298,7 @@ specify to make your test failure messages clearer. It's not required.
| `assert_not_operator( obj1, operator, [obj2], [msg] )` | Ensures that `obj1.operator(obj2)` is false.|
| `assert_predicate ( obj, predicate, [msg] )` | Ensures that `obj.predicate` is true, e.g. `assert_predicate str, :empty?`|
| `assert_not_predicate ( obj, predicate, [msg] )` | Ensures that `obj.predicate` is false, e.g. `assert_not_predicate str, :empty?`|
-| `assert_send( array, [msg] )` | Ensures that executing the method listed in `array[1]` on the object in `array[0]` with the parameters of `array[2 and up]` is true. This one is weird eh?|
+| `assert_send( array, [msg] )` | Ensures that executing the method listed in `array[1]` on the object in `array[0]` with the parameters of `array[2 and up]` is true, e.g. assert_send [@user, :full_name, 'Sam Smith']. This one is weird eh?|
| `flunk( [msg] )` | Ensures failure. This is useful to explicitly mark a test that isn't finished yet.|
The above are a subset of assertions that minitest supports. For an exhaustive &
@@ -316,12 +316,12 @@ 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, &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)` | Asserts 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_difference(expressions, difference = 1, message = nil) {...}`](http://api.rubyonrails.org/classes/ActiveSupport/Testing/Assertions.html#method-i-assert_difference) | 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, &block)`](http://api.rubyonrails.org/classes/ActiveSupport/Testing/Assertions.html#method-i-assert_no_difference) | 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)`](http://api.rubyonrails.org/classes/ActionDispatch/Assertions/RoutingAssertions.html#method-i-assert_recognizes) | 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)`](http://api.rubyonrails.org/classes/ActionDispatch/Assertions/RoutingAssertions.html#method-i-assert_generates) | 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)`](http://api.rubyonrails.org/classes/ActionDispatch/Assertions/ResponseAssertions.html#method-i-assert_response) | 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)`](http://api.rubyonrails.org/classes/ActionDispatch/Assertions/ResponseAssertions.html#method-i-assert_redirected_to) | Asserts 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`.|
You'll see the usage of some of these assertions in the next chapter.
@@ -329,11 +329,11 @@ You'll see the usage of some of these assertions in the next chapter.
All the basic assertions such as `assert_equal` defined in `Minitest::Assertions` are also available in the classes we use in our own test cases. In fact, Rails provides the following classes for you to inherit from:
-* `ActiveSupport::TestCase`
-* `ActionMailer::TestCase`
-* `ActionView::TestCase`
-* `ActionDispatch::IntegrationTest`
-* `ActiveJob::TestCase`
+* [`ActiveSupport::TestCase`](http://api.rubyonrails.org/classes/ActiveSupport/TestCase.html)
+* [`ActionMailer::TestCase`](http://api.rubyonrails.org/classes/ActionMailer/TestCase.html)
+* [`ActionView::TestCase`](http://api.rubyonrails.org/classes/ActionView/TestCase.html)
+* [`ActionDispatch::IntegrationTest`](http://api.rubyonrails.org/classes/ActionDispatch/IntegrationTest.html)
+* [`ActiveJob::TestCase`](http://api.rubyonrails.org/classes/ActiveJob/TestCase.html)
Each of these classes include `Minitest::Assertions`, allowing us to use all of the basic assertions in our tests.
@@ -396,14 +396,14 @@ A dedicated test database allows you to set up and interact with test data in is
In order to run your tests, your test database will need to have the current
structure. The test helper checks whether your test database has any pending
-migrations. If so, it will try to load your `db/schema.rb` or `db/structure.sql`
+migrations. It will try to load your `db/schema.rb` or `db/structure.sql`
into the test database. If migrations are still pending, an error will be
raised. Usually this indicates that your schema is not fully migrated. Running
-the migrations against the development database (`bin/rake db:migrate`) will
+the migrations against the development database (`bin/rails db:migrate`) will
bring the schema up to date.
-NOTE: If existing migrations required modifications, the test database needs to
-be rebuilt. This can be done by executing `bin/rake db:test:prepare`.
+NOTE: If there were modifications to existing migrations, the test database needs to
+be rebuilt. This can be done by executing `bin/rails db:test:prepare`.
### The Low-Down on Fixtures
@@ -415,6 +415,8 @@ You can find comprehensive documentation in the [Fixtures API documentation](htt
_Fixtures_ is a fancy word for sample data. Fixtures allow you to populate your testing database with predefined data before your tests run. Fixtures are database independent and written in YAML. There is one file per model.
+NOTE: Fixtures are not designed to create every object that your tests need, and are best managed when only used for default data that can be applied to the common case.
+
You'll find fixtures under your `test/fixtures` directory. When you run `rails generate model` to create a new model, Rails automatically creates fixture stubs in this directory.
#### YAML
@@ -448,15 +450,15 @@ about:
name: About
# In fixtures/articles.yml
-one:
+first:
title: Welcome to Rails!
body: Hello world!
category: about
```
-Notice the `category` key of the `one` article found in `fixtures/articles.yml` has a value of `about`. This tells Rails to load the category `about` found in `fixtures/categories.yml`.
+Notice the `category` key of the `first` article found in `fixtures/articles.yml` has a value of `about`. This tells Rails to load the category `about` found in `fixtures/categories.yml`.
-NOTE: For associations to reference one another by name, you cannot specify the `id:` attribute on the associated fixtures. Rails will auto assign a primary key to be consistent between runs. For more information on this association behavior please read the [Fixtures API documentation](http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html).
+NOTE: For associations to reference one another by name, you can use the fixture name instead of specifying the `id:` attribute on the associated fixtures. Rails will auto assign a primary key to be consistent between runs. For more information on this association behavior please read the [Fixtures API documentation](http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html).
#### ERB'in It Up
@@ -518,15 +520,15 @@ create test/models/article_test.rb
create test/fixtures/articles.yml
```
-Model tests don't have their own superclass like `ActionMailer::TestCase` instead they inherit from `ActiveSupport::TestCase`.
+Model tests don't have their own superclass like `ActionMailer::TestCase` instead they inherit from [`ActiveSupport::TestCase`](http://api.rubyonrails.org/classes/ActiveSupport/TestCase.html).
Integration Testing
-------------------
-Integration tests are used to test how various parts of your application interact. They are generally used to test important workflows within your application.
+Integration tests are used to test how various parts of your application interact. They are generally used to test important workflows within our application.
-For creating Rails integration tests, we use the 'test/integration' directory for your application. Rails provides a generator to create an integration test skeleton for you.
+For creating Rails integration tests, we use the 'test/integration' directory for our application. Rails provides a generator to create an integration test skeleton for us.
```bash
$ bin/rails generate integration_test user_flows
@@ -546,17 +548,17 @@ class UserFlowsTest < ActionDispatch::IntegrationTest
end
```
-Inheriting from `ActionDispatch::IntegrationTest` comes with some advantages. This makes available some additional helpers to use in your integration tests.
+Here the test is inheriting from `ActionDispatch::IntegrationTest`. This makes some additional helpers available for us to use in our integration tests.
### Helpers Available for Integration Tests
-In addition to the standard testing helpers, inheriting `ActionDispatch::IntegrationTest` comes with some additional helpers available when writing integration tests. Let's briefly introduce you to the three categories of helpers you get to choose from.
+In addition to the standard testing helpers, inheriting from `ActionDispatch::IntegrationTest` comes with some additional helpers available when writing integration tests. Let's get briefly introduced to the three categories of helpers we get to choose from.
For dealing with the integration test runner, see [`ActionDispatch::Integration::Runner`](http://api.rubyonrails.org/classes/ActionDispatch/Integration/Runner.html).
-When performing requests, you will have [`ActionDispatch::Integration::RequestHelpers`](http://api.rubyonrails.org/classes/ActionDispatch/Integration/RequestHelpers.html) available for your use.
+When performing requests, we will have [`ActionDispatch::Integration::RequestHelpers`](http://api.rubyonrails.org/classes/ActionDispatch/Integration/RequestHelpers.html) available for our use.
-If you'd like to modify the session, or state of your integration test you should look for [`ActionDispatch::Integration::Session`](http://api.rubyonrails.org/classes/ActionDispatch/Integration/Session.html) to help.
+If we need to modify the session, or state of our integration test, take a look at [`ActionDispatch::Integration::Session`](http://api.rubyonrails.org/classes/ActionDispatch/Integration/Session.html) to help.
### Implementing an integration test
@@ -569,7 +571,7 @@ $ bin/rails generate integration_test blog_flow
```
It should have created a test file placeholder for us. With the output of the
-previous command you should see:
+previous command we should see:
```bash
invoke test_unit
@@ -589,9 +591,9 @@ class BlogFlowTest < ActionDispatch::IntegrationTest
end
```
-If you remember from earlier in the "Testing Views" section we covered `assert_select` to query the resulting HTML of a request.
+We will take a look at `assert_select` to query the resulting HTML of a request in the "Testing Views" section below. It is used for testing the response of our request by asserting the presence of key HTML elements and their content.
-When visit our root path, we should see `welcome/index.html.erb` rendered for the view. So this assertion should pass.
+When we visit our root path, we should see `welcome/index.html.erb` rendered for the view. So this assertion should pass.
#### Creating articles integration
@@ -638,9 +640,9 @@ We were able to successfully test a very small workflow for visiting our blog an
Functional Tests for Your Controllers
-------------------------------------
-In Rails, testing the various actions of a controller is a form of writing functional tests. Remember your controllers handle the incoming web requests to your application and eventually respond with a rendered view. When writing functional tests, you're testing how your actions handle the requests and the expected result, or response in some cases an HTML view.
+In Rails, testing the various actions of a controller is a form of writing functional tests. Remember your controllers handle the incoming web requests to your application and eventually respond with a rendered view. When writing functional tests, you are testing how your actions handle the requests and the expected result or response, in some cases an HTML view.
-### What to Include in your Functional Tests
+### What to include in your Functional Tests
You should test for things such as:
@@ -650,11 +652,10 @@ You should test for things such as:
* was the correct object stored in the response template?
* was the appropriate message displayed to the user in the view?
-The easiest way to see functional tests in action is to generate a controller
-scaffold:
+The easiest way to see functional tests in action is to generate a controller using the scaffold generator:
```bash
-$ bin/rails generate scaffold_controller article title:string body:test
+$ bin/rails generate scaffold_controller article title:string body:text
...
create app/controllers/articles_controller.rb
...
@@ -664,7 +665,7 @@ create test/controllers/articles_controller_test.rb
```
This will generate the controller code and tests for an `Article` resource.
-You can take look at the file `articles_controller_test.rb` in the `test/controllers` directory.
+You can take a look at the file `articles_controller_test.rb` in the `test/controllers` directory.
If you already have a controller and just want to generate the test scaffold code for
each of the seven default actions, you can use the following command:
@@ -677,7 +678,7 @@ create test/controllers/articles_controller_test.rb
...
```
-Let me take you through one such test, `test_should_get_index` from the file `articles_controller_test.rb`.
+Let's take a look at one such test, `test_should_get_index` from the file `articles_controller_test.rb`.
```ruby
# articles_controller_test.rb
@@ -693,7 +694,7 @@ 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 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:
+The `get` method kicks off the web request and populates the results into the `@response`. It accepts 4 arguments:
* The action of the controller you are requesting.
This can be in the form of a string or a route (i.e. `articles_url`).
@@ -705,7 +706,7 @@ The `get` method kicks off the web request and populates the results into the re
* `flash`: option with a hash of flash values.
-All the keyword arguments are optional.
+All of these keyword arguments are optional.
Example: Calling the `:show` action, passing an `id` of 12 as the `params` and setting a `user_id` of 5 in the session:
@@ -753,7 +754,7 @@ NOTE: Functional tests do not verify whether the specified request type is accep
### Testing XHR (AJAX) requests
To test AJAX requests, you can specify the `xhr: true` option to `get`, `post`,
-`patch`, `put`, and `delete` methods:
+`patch`, `put`, and `delete` methods. For example:
```ruby
test "ajax request" do
@@ -808,7 +809,7 @@ post article_url # simulate the request with custom env variable
### Testing `flash` notices
-If you remember from earlier one of the Three Hashes of the Apocalypse was `flash`.
+If you remember from earlier, one of the Three Hashes of the Apocalypse was `flash`.
We want to add a `flash` message to our blog application whenever someone
successfully creates a new Article.
@@ -829,7 +830,7 @@ end
If we run our test now, we should see a failure:
```bash
-$ bin/rails test test/controllers/articles_controller_test.rb test_should_create_article
+$ bin/rails test test/controllers/articles_controller_test.rb -n test_should_create_article
Run options: -n test_should_create_article --seed 32266
# Running:
@@ -867,7 +868,7 @@ end
Now if we run our tests, we should see it pass:
```bash
-$ bin/rails test test/controllers/articles_controller_test.rb test_should_create_article
+$ bin/rails test test/controllers/articles_controller_test.rb -n test_should_create_article
Run options: -n test_should_create_article --seed 18981
# Running:
@@ -893,7 +894,7 @@ test "should show article" do
end
```
-Remember from our discussion earlier on fixtures the `articles()` method will give us access to our Articles fixtures.
+Remember from our discussion earlier on fixtures, the `articles()` method will give us access to our Articles fixtures.
How about deleting an existing Article?
@@ -913,14 +914,19 @@ We can also add a test for updating an existing Article.
```ruby
test "should update article" do
article = articles(:one)
+
patch '/article', params: { id: article.id, article: { title: "updated" } }
+
assert_redirected_to article_path(article)
+ # Reload association to fetch updated data and assert that title is updated.
+ article.reload
+ assert_equal "updated", article.title
end
```
Notice we're starting to see some duplication in these three tests, they both access the same Article fixture data. We can D.R.Y. this up by using the `setup` and `teardown` methods provided by `ActiveSupport::Callbacks`.
-Our test should now look something like this, disregard the other tests we're leaving them out for brevity.
+Our test should now look something as what follows. Disregard the other tests for now, we're leaving them out for brevity.
```ruby
require 'test_helper'
@@ -952,8 +958,12 @@ class ArticlesControllerTest < ActionDispatch::IntegrationTest
end
test "should update article" do
- patch article_url(@article), params: { article: { title: "updated" } }
+ patch '/article', params: { id: @article.id, article: { title: "updated" } }
+
assert_redirected_to article_path(@article)
+ # Reload association to fetch updated data and assert that title is updated.
+ @article.reload
+ assert_equal "updated", @article.title
end
end
```
@@ -966,7 +976,7 @@ To avoid code duplication, you can add your own test helpers.
Sign in helper can be a good example:
```ruby
-test/test_helper.rb
+#test/test_helper.rb
module SignInHelper
def sign_in(user)
@@ -999,6 +1009,8 @@ Testing Routes
Like everything else in your Rails application, you can test your routes.
+NOTE: If your application has complex routes, Rails provides a number of useful helpers to test them.
+
For more information on routing assertions available in Rails, see the API documentation for [`ActionDispatch::Assertions::RoutingAssertions`](http://api.rubyonrails.org/classes/ActionDispatch/Assertions/RoutingAssertions.html).
Testing Views
@@ -1045,7 +1057,7 @@ assert_select "ol" do
end
```
-This assertion is quite powerful. For more advanced usage, refer to its [documentation](http://www.rubydoc.info/github/rails/rails-dom-testing).
+This assertion is quite powerful. For more advanced usage, refer to its [documentation](https://github.com/rails/rails-dom-testing/blob/master/lib/rails/dom/testing/assertions/selector_assertions.rb).
#### Additional View-Based Assertions
@@ -1068,27 +1080,31 @@ end
Testing Helpers
---------------
+A helper is just a simple module where you can define methods which are
+available into your views.
+
In order to test helpers, all you need to do is check that the output of the
helper method matches what you'd expect. Tests related to the helpers are
located under the `test/helpers` directory.
-A helper test looks like so:
+Given we have the following helper:
```ruby
-require 'test_helper'
-
-class UserHelperTest < ActionView::TestCase
+module UserHelper
+ def link_to_user(user)
+ link_to "#{user.first_name} #{user.last_name}", user
+ end
end
```
-A helper is just a simple module where you can define methods which are
-available into your views. To test the output of the helper's methods, you just
-have to use a mixin like this:
+We can test the output of this method like this:
```ruby
class UserHelperTest < ActionView::TestCase
- test "should return the user name" do
- # ...
+ test "should return the user's full name" do
+ user = users(:david)
+
+ assert_dom_equal %{<a href="/user/#{user.id}">David Heinemeier Hansson</a>}, link_to_user(user)
end
end
```
@@ -1123,7 +1139,7 @@ In order to test that your mailer is working as expected, you can use unit tests
For the purposes of unit testing a mailer, fixtures are used to provide an example of how the output _should_ look. Because these are example emails, and not Active Record data like the other fixtures, they are kept in their own subdirectory apart from the other fixtures. The name of the directory within `test/fixtures` directly corresponds to the name of the mailer. So, for a mailer named `UserMailer`, the fixtures should reside in `test/fixtures/user_mailer` directory.
-When you generated your mailer, the generator creates stub fixtures for each of the mailers actions. If you didn't use the generator you'll have to make those files yourself.
+When you generated your mailer, the generator creates stub fixtures for each of the mailers actions. If you didn't use the generator, you'll have to create those files yourself.
#### The Basic Test Case
@@ -1175,9 +1191,9 @@ testing) but instead it will be appended to an array
(`ActionMailer::Base.deliveries`).
NOTE: The `ActionMailer::Base.deliveries` array is only reset automatically in
-`ActionMailer::TestCase` tests. If you want to have a clean slate outside Action
-Mailer tests, you can reset it manually with:
-`ActionMailer::Base.deliveries.clear`
+`ActionMailer::TestCase` and `ActionDispatch::IntegrationTest` tests.
+If you want to have a clean slate outside these test cases, you can reset it
+manually with: `ActionMailer::Base.deliveries.clear`
### Functional Testing
@@ -1204,7 +1220,7 @@ Testing Jobs
------------
Since your custom jobs can be queued at different levels inside your application,
-you'll need to test both jobs themselves (their behavior when they get enqueued)
+you'll need to test both, the jobs themselves (their behavior when they get enqueued)
and that other entities correctly enqueue them.
### A Basic Test Case
@@ -1252,10 +1268,12 @@ class ProductTest < ActiveJob::TestCase
end
```
-Testing Time-Dependent Code
----------------------------
+Additional Testing Resources
+----------------------------
+
+### Testing Time-Dependent Code
-Rails provides inbuilt helper methods that enable you to assert that your time-sensitve code works as expected.
+Rails provides built-in helper methods that enable you to assert that your time-sensitive code works as expected.
Here is an example using the [`travel_to`](http://api.rubyonrails.org/classes/ActiveSupport/Testing/TimeHelpers.html#method-i-travel_to) helper:
diff --git a/guides/source/upgrading_ruby_on_rails.md b/guides/source/upgrading_ruby_on_rails.md
index 148890bf77..9d0fec5ab1 100644
--- a/guides/source/upgrading_ruby_on_rails.md
+++ b/guides/source/upgrading_ruby_on_rails.md
@@ -16,6 +16,21 @@ Before attempting to upgrade an existing application, you should be sure you hav
The best way to be sure that your application still works after upgrading is to have good test coverage before you start the process. If you don't have automated tests that exercise the bulk of your application, you'll need to spend time manually exercising all the parts that have changed. In the case of a Rails upgrade, that will mean every single piece of functionality in the application. Do yourself a favor and make sure your test coverage is good _before_ you start an upgrade.
+### The Upgrade Process
+
+When changing Rails versions, it's best to move slowly, one minor version at a time, in order to make good use of the deprecation warnings. Rails version numbers are in the form Major.Minor.Patch. Major and Minor versions are allowed to make changes to the public API, so this may cause errors in your application. Patch versions only include bug fixes, and don't change any public API.
+
+The process should go as follows:
+
+1. Write tests and make sure they pass
+2. Move to the latest patch version after your current version
+3. Fix tests and deprecated features
+4. Move to the latest patch version of the next minor version
+
+Repeat this process until you reach your target Rails version. Each time you move versions, you will need to change the Rails version number in the Gemfile (and possibly other gem versions) and run `bundle update`. Then run the Update rake task mentioned below to update configuration files, then run your tests.
+
+You can find a list of all released Rails versions [here](https://rubygems.org/gems/rails/versions).
+
### Ruby Versions
Rails generally stays close to the latest released Ruby version when it's released:
@@ -27,15 +42,15 @@ Rails generally stays close to the latest released Ruby version when it's releas
TIP: Ruby 1.8.7 p248 and p249 have marshaling bugs that crash Rails. Ruby Enterprise Edition has these fixed since the release of 1.8.7-2010.02. On the 1.9 front, Ruby 1.9.1 is not usable because it outright segfaults, so if you want to use 1.9.x, jump straight to 1.9.3 for smooth sailing.
-### The Rake Task
+### The Task
-Rails provides the `rails:update` rake task. After updating the Rails version
+Rails provides the `app:update` rake task. After updating the Rails version
in the Gemfile, run this rake task.
This will help you with the creation of new files and changes of old files in an
interactive session.
```bash
-$ rake rails:update
+$ rails app:update
identical config/boot.rb
exist config
conflict config/routes.rb
@@ -53,6 +68,10 @@ Don't forget to review the difference, to see if there were any unexpected chang
Upgrading from Rails 4.2 to Rails 5.0
-------------------------------------
+### Ruby 2.2.2+
+
+ToDo...
+
### Active Record models now inherit from ApplicationRecord by default
In Rails 4.2 an Active Record model inherits from `ActiveRecord::Base`. In Rails 5.0,
@@ -61,7 +80,7 @@ all models inherit from `ApplicationRecord`.
`ApplicationRecord` is a new superclass for all app models, analogous to app
controllers subclassing `ApplicationController` instead of
`ActionController::Base`. This gives apps a single spot to configure app-wide
-model behavior
+model behavior.
When upgrading from Rails 4.2 to Rails 5.0 you need to create an
`application_record.rb` file in `app/models/` and add the following content:
@@ -164,7 +183,7 @@ the logs. In the next version, these errors will no longer be suppressed.
Instead, the errors will propagate normally just like in other Active
Record callbacks.
-When you define a `after_rollback` or `after_commit` callback, you
+When you define an `after_rollback` or `after_commit` callback, you
will receive a deprecation warning about this upcoming change. When
you are ready, you can opt into the new behavior and remove the
deprecation warning by adding following configuration to your
@@ -398,7 +417,7 @@ secrets, you need to:
3. Remove the `secret_token.rb` initializer.
-4. Use `rake secret` to generate new keys for the `development` and `test` sections.
+4. Use `rails secret` to generate new keys for the `development` and `test` sections.
5. Restart your server.
@@ -963,7 +982,7 @@ 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 `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`.
diff --git a/guides/source/working_with_javascript_in_rails.md b/guides/source/working_with_javascript_in_rails.md
index 48fc6bc9c0..c58aee96db 100644
--- a/guides/source/working_with_javascript_in_rails.md
+++ b/guides/source/working_with_javascript_in_rails.md
@@ -148,10 +148,10 @@ and Rails has got your back in those cases.
Because of Unobtrusive JavaScript, the Rails "Ajax helpers" are actually in two
parts: the JavaScript half and the Ruby half.
+Unless you have disabled the Asset Pipeline,
[rails.js](https://github.com/rails/jquery-ujs/blob/master/src/rails.js)
provides the JavaScript half, and the regular Ruby view helpers add appropriate
-tags to your DOM. The CoffeeScript in rails.js then listens for these
-attributes, and attaches appropriate handlers.
+tags to your DOM.
### form_for
@@ -350,8 +350,8 @@ $("<%= escape_javascript(render @user) %>").appendTo("#users");
Turbolinks
----------
-Rails 4 ships with the [Turbolinks gem](https://github.com/rails/turbolinks).
-This gem uses Ajax to speed up page rendering in most applications.
+Rails ships with the [Turbolinks library](https://github.com/turbolinks/turbolinks),
+which uses Ajax to speed up page rendering in most applications.
### How Turbolinks Works
@@ -364,14 +364,14 @@ will then use PushState to change the URL to the correct one, preserving
refresh semantics and giving you pretty URLs.
The only thing you have to do to enable Turbolinks is have it in your Gemfile,
-and put `//= require turbolinks` in your CoffeeScript manifest, which is usually
+and put `//= require turbolinks` in your JavaScript manifest, which is usually
`app/assets/javascripts/application.js`.
-If you want to disable Turbolinks for certain links, add a `data-no-turbolink`
+If you want to disable Turbolinks for certain links, add a `data-turbolinks="false"`
attribute to the tag:
```html
-<a href="..." data-no-turbolink>No turbolinks here</a>.
+<a href="..." data-turbolinks="false">No turbolinks here</a>.
```
### Page Change Events
@@ -389,13 +389,13 @@ event that this relies on will not be fired. If you have code that looks like
this, you must change your code to do this instead:
```coffeescript
-$(document).on "page:change", ->
+$(document).on "turbolinks:load", ->
alert "page has loaded!"
```
For more details, including other events you can bind to, check out [the
Turbolinks
-README](https://github.com/rails/turbolinks/blob/master/README.md).
+README](https://github.com/turbolinks/turbolinks/blob/master/README.md).
Other Resources
---------------