aboutsummaryrefslogtreecommitdiffstats
path: root/guides/source
diff options
context:
space:
mode:
Diffstat (limited to 'guides/source')
-rw-r--r--guides/source/4_2_release_notes.md2
-rw-r--r--guides/source/5_0_release_notes.md21
-rw-r--r--guides/source/action_cable_overview.md620
-rw-r--r--guides/source/action_mailer_basics.md20
-rw-r--r--guides/source/action_view_overview.md14
-rw-r--r--guides/source/active_job_basics.md10
-rw-r--r--guides/source/active_model_basics.md2
-rw-r--r--guides/source/active_record_migrations.md4
-rw-r--r--guides/source/active_record_postgresql.md2
-rw-r--r--guides/source/active_record_querying.md24
-rw-r--r--guides/source/active_record_validations.md2
-rw-r--r--guides/source/active_support_core_extensions.md8
-rw-r--r--guides/source/api_app.md48
-rw-r--r--guides/source/asset_pipeline.md27
-rw-r--r--guides/source/association_basics.md6
-rw-r--r--guides/source/caching_with_rails.md8
-rw-r--r--guides/source/command_line.md4
-rw-r--r--guides/source/configuring.md40
-rw-r--r--guides/source/debugging_rails_applications.md10
-rw-r--r--guides/source/documents.yaml1
-rw-r--r--guides/source/engines.md10
-rw-r--r--guides/source/form_helpers.md2
-rw-r--r--guides/source/getting_started.md38
-rw-r--r--guides/source/i18n.md2
-rw-r--r--guides/source/layout.html.erb12
-rw-r--r--guides/source/layouts_and_rendering.md4
-rw-r--r--guides/source/rails_application_templates.md26
-rw-r--r--guides/source/rails_on_rack.md2
-rw-r--r--guides/source/routing.md18
-rw-r--r--guides/source/security.md8
-rw-r--r--guides/source/testing.md85
-rw-r--r--guides/source/upgrading_ruby_on_rails.md27
-rw-r--r--guides/source/working_with_javascript_in_rails.md18
33 files changed, 953 insertions, 172 deletions
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
index f45c8005da..dc631e5cb9 100644
--- a/guides/source/5_0_release_notes.md
+++ b/guides/source/5_0_release_notes.md
@@ -256,6 +256,12 @@ Please refer to the [Changelog][action-pack] for detailed changes.
* 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
-------------
@@ -294,6 +300,9 @@ Please refer to the [Changelog][action-view] for detailed changes.
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
-------------
@@ -313,6 +322,9 @@ Please refer to the [Changelog][action-mailer] for detailed 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))
@@ -324,6 +336,9 @@ Please refer to the [Changelog][action-mailer] for detailed changes.
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
-------------
@@ -381,6 +396,9 @@ Please refer to the [Changelog][active-record] for detailed changes.
* 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
@@ -702,7 +720,7 @@ Please refer to the [Changelog][active-support] for detailed changes.
* Changed the default test order from `:sorted` to `:random`.
([commit](https://github.com/rails/rails/commit/5f777e4b5ee2e3e8e6fd0e2a208ec2a4d25a960d))
-* Added `#on_weekend?`, `#next_weekday`, `#prev_weekday` methods to `Date`,
+* Added `#on_weekend?`, `#on_weekday?`, `#next_weekday`, `#prev_weekday` methods to `Date`,
`Time`, and `DateTime`.
([Pull Request](https://github.com/rails/rails/pull/18335))
@@ -765,6 +783,7 @@ framework it is. Kudos to all of them.
[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
diff --git a/guides/source/action_cable_overview.md b/guides/source/action_cable_overview.md
new file mode 100644
index 0000000000..16cfaf94e2
--- /dev/null
+++ b/guides/source/action_cable_overview.md
@@ -0,0 +1,620 @@
+Action Cable Overview
+=====================
+
+In this guide you will learn how Action Cable works and how to use WebSockets to
+incorporate real-time features into your Rails application.
+
+After reading this guide, you will know:
+
+* How to setup Action Cable
+* How to setup channels
+
+Introduction
+------------
+
+Action Cable seamlessly integrates WebSockets with the rest of your Rails application.
+It allows for real-time features to be written in Ruby in the same style and form as
+the rest of your Rails application, while still being performant and scalable. It's
+a full-stack offering that provides both a client-side JavaScript framework and a
+server-side Ruby framework. You have access to your full domain model written with
+Active Record or your ORM of choice.
+
+What is Pub/Sub
+---------------
+
+Pub/Sub, or Publish-Subscribe, refers to a message queue paradigm whereby senders
+of information (publishers), send data to an abstract class of recipients (subscribers),
+without specifying individual recipients. Action Cable uses this approach to communicate
+between the server and many clients.
+
+What is Action Cable
+--------------------
+
+Action Cable is a server which can handle multiple connection instances, with one
+client-server connection instance established per WebSocket connection.
+
+## Server-Side Components
+
+### Connections
+
+Connections form the foundation of the client-server relationship. For every WebSocket
+the cable server is accepting, a Connection object will be instantiated on the server side.
+This instance becomes the parent of all the channel subscriptions that are created from there on.
+The Connection itself does not deal with any specific application logic beyond authentication
+and authorization. The client of a WebSocket connection is called a consumer. An individual
+user will create one consumer-connection pair per browser tab, window, or device they have open.
+
+Connections are instantiated via the `ApplicationCable::Connection` class in Ruby.
+In this class, you authorize the incoming connection, and proceed to establish it
+if the user can be identified.
+
+#### Connection Setup
+
+```ruby
+# app/channels/application_cable/connection.rb
+module ApplicationCable
+ class Connection < ActionCable::Connection::Base
+ identified_by :current_user
+
+ def connect
+ self.current_user = find_verified_user
+ end
+
+ protected
+ def find_verified_user
+ if current_user = User.find_by(id: cookies.signed[:user_id])
+ current_user
+ else
+ reject_unauthorized_connection
+ end
+ end
+ end
+end
+```
+
+Here `identified_by` is a connection identifier that can be used to find the
+specific connection later. Note that anything marked as an identifier will automatically
+create a delegate by the same name on any channel instances created off the connection.
+
+This example relies on the fact that you will already have handled authentication of the user
+somewhere else in your application, and that a successful authentication sets a signed
+cookie with the `user_id`.
+
+The cookie is then automatically sent to the connection instance when a new connection
+is attempted, and you use that to set the `current_user`. By identifying the connection
+by this same current_user, you're also ensuring that you can later retrieve all open
+connections by a given user (and potentially disconnect them all if the user is deleted
+or deauthorized).
+
+### Channels
+
+A channel encapsulates a logical unit of work, similar to what a controller does in a
+regular MVC setup. By default, Rails creates a parent `ApplicationCable::Channel` class
+for encapsulating shared logic between your channels.
+
+#### Parent Channel Setup
+
+```ruby
+# app/channels/application_cable/channel.rb
+module ApplicationCable
+ class Channel < ActionCable::Channel::Base
+ end
+end
+```
+
+Then you would create your own channel classes. For example, you could have a
+**ChatChannel** and an **AppearanceChannel**:
+
+```ruby
+# app/channels/application_cable/chat_channel.rb
+class ChatChannel < ApplicationCable::Channel
+end
+
+# app/channels/application_cable/appearance_channel.rb
+class AppearanceChannel < ApplicationCable::Channel
+end
+```
+
+A consumer could then be subscribed to either or both of these channels.
+
+#### Subscriptions
+
+When a consumer is subscribed to a channel, they act as a subscriber;
+This connection is called a subscription.
+Incoming messages are then routed to these channel subscriptions based on
+an identifier sent by the cable consumer.
+
+```ruby
+# app/channels/application_cable/chat_channel.rb
+class ChatChannel < ApplicationCable::Channel
+ # Called when the consumer has successfully become a subscriber of this channel
+ def subscribed
+ end
+end
+```
+
+## Client-Side Components
+
+### Connections
+
+Consumers require an instance of the connection on their side. This can be
+established using the following Javascript, which is generated by default in Rails:
+
+#### Connect Consumer
+
+```coffeescript
+# app/assets/javascripts/cable.coffee
+#= require action_cable
+
+@App = {}
+App.cable = ActionCable.createConsumer()
+```
+
+This will ready a consumer that'll connect against /cable on your server by default.
+The connection won't be established until you've also specified at least one subscription
+you're interested in having.
+
+#### Subscriber
+
+When a consumer is subscribed to a channel, they act as a subscriber. A
+consumer can act as a subscriber to a given channel any number of times.
+For example, a consumer could subscribe to multiple chat rooms at the same time.
+(remember that a physical user may have multiple consumers, one per tab/device open to your connection).
+
+A consumer becomes a subscriber, by creating a subscription to a given channel:
+
+```coffeescript
+# app/assets/javascripts/cable/subscriptions/chat.coffee
+App.cable.subscriptions.create { channel: "ChatChannel", room: "Best Room" }
+
+# app/assets/javascripts/cable/subscriptions/appearance.coffee
+App.cable.subscriptions.create { channel: "AppearanceChannel" }
+```
+
+While this creates the subscription, the functionality needed to respond to
+received data will be described later on.
+
+## Client-Server Interactions
+
+### Streams
+
+Streams provide the mechanism by which channels route published content
+(broadcasts) to its subscribers.
+
+```ruby
+# app/channels/application_cable/chat_channel.rb
+class ChatChannel < ApplicationCable::Channel
+ def subscribed
+ stream_from "chat_#{params[:room]}"
+ end
+end
+```
+
+If you have a stream that is related to a model, then the broadcasting used
+can be generated from the model and channel. The following example would
+subscribe to a broadcasting like `comments:Z2lkOi8vVGVzdEFwcC9Qb3N0LzE`
+
+```ruby
+class CommentsChannel < ApplicationCable::Channel
+ def subscribed
+ post = Post.find(params[:id])
+ stream_for post
+ end
+end
+```
+
+You can then broadcast to this channel using: `CommentsChannel.broadcast_to(@post, @comment)`
+
+### Broadcastings
+
+A broadcasting is a pub/sub link where anything transmitted by a publisher
+is routed directly to the channel subscribers who are streaming that named
+broadcasting. Each channel can be streaming zero or more broadcastings.
+Broadcastings are purely an online queue and time dependent;
+If a consumer is not streaming (subscribed to a given channel), they'll not
+get the broadcast should they connect later.
+
+Broadcasts are called elsewhere in your Rails application:
+```ruby
+ WebNotificationsChannel.broadcast_to current_user, title: 'New things!', body: 'All the news fit to print'
+```
+
+The `WebNotificationsChannel.broadcast_to` call places a message in the current
+subscription adapter (Redis by default)'s pubsub queue under a separate
+broadcasting name for each user. For a user with an ID of 1, the broadcasting
+name would be `web_notifications_1`.
+
+The channel has been instructed to stream everything that arrives at
+`web_notifications_1` directly to the client by invoking the `#received(data)`
+callback.
+
+### Subscriptions
+
+When a consumer is subscribed to a channel, they act as a subscriber;
+This connection is called a subscription. Incoming messages are then routed
+to these channel subscriptions based on an identifier sent by the cable consumer.
+
+```coffeescript
+# app/assets/javascripts/cable/subscriptions/chat.coffee
+# Assumes you've already requested the right to send web notifications
+App.cable.subscriptions.create { channel: "ChatChannel", room: "Best Room" },
+ received: (data) ->
+ @appendLine(data)
+
+ appendLine: (data) ->
+ html = @createLine(data)
+ $("[data-chat-room='Best Room']").append(html)
+
+ createLine: (data) ->
+ """
+ <article class="chat-line">
+ <span class="speaker">#{data["sent_by"]}</span>
+ <span class="body">#{data["body"]}</span>
+ </article>
+ """
+```
+
+### Passing Parameters to Channel
+
+You can pass parameters from the client-side to the server-side when
+creating a subscription. For example:
+
+```ruby
+# app/channels/chat_channel.rb
+class ChatChannel < ApplicationCable::Channel
+ def subscribed
+ stream_from "chat_#{params[:room]}"
+ end
+end
+```
+
+Pass an object as the first argument to `subscriptions.create`, and that object
+will become your params hash in your cable channel. The keyword `channel` is required.
+
+```coffeescript
+# app/assets/javascripts/cable/subscriptions/chat.coffee
+App.cable.subscriptions.create { channel: "ChatChannel", room: "Best Room" },
+ received: (data) ->
+ @appendLine(data)
+
+ appendLine: (data) ->
+ html = @createLine(data)
+ $("[data-chat-room='Best Room']").append(html)
+
+ createLine: (data) ->
+ """
+ <article class="chat-line">
+ <span class="speaker">#{data["sent_by"]}</span>
+ <span class="body">#{data["body"]}</span>
+ </article>
+ """
+```
+
+```ruby
+# Somewhere in your app this is called, perhaps from a NewCommentJob
+ChatChannel.broadcast_to "chat_#{room}", sent_by: 'Paul', body: 'This is a cool chat app.'
+```
+
+
+### Rebroadcasting message
+
+A common use case is to rebroadcast a message sent by one client to any
+other connected clients.
+
+```ruby
+# app/channels/chat_channel.rb
+class ChatChannel < ApplicationCable::Channel
+ def subscribed
+ stream_from "chat_#{params[:room]}"
+ end
+
+ def receive(data)
+ ChatChannel.broadcast_to "chat_#{params[:room]}", data
+ end
+end
+```
+
+```coffeescript
+# app/assets/javascripts/cable/subscriptions/chat.coffee
+App.chatChannel = App.cable.subscriptions.create { channel: "ChatChannel", room: "Best Room" },
+ received: (data) ->
+ # data => { sent_by: "Paul", body: "This is a cool chat app." }
+
+App.chatChannel.send({ sent_by: "Paul", body: "This is a cool chat app." })
+```
+
+The rebroadcast will be received by all connected clients, _including_ the
+client that sent the message. Note that params are the same as they were when
+you subscribed to the channel.
+
+## Full-stack examples
+
+The following setup steps are common to both examples:
+
+ 1. [Setup your connection](#connection-setup)
+ 2. [Setup your parent channel](#parent-channel-setup)
+ 3. [Connect your consumer](#connect-consumer)
+
+### Example 1: User appearances
+Here's a simple example of a channel that tracks whether a user is online or not
+and what page they're on. (This is useful for creating presence features like showing
+a green dot next to a user name if they're online).
+
+#### Create the server-side Appearance Channel:
+
+```ruby
+# app/channels/appearance_channel.rb
+class AppearanceChannel < ApplicationCable::Channel
+ def subscribed
+ current_user.appear
+ end
+
+ def unsubscribed
+ current_user.disappear
+ end
+
+ def appear(data)
+ current_user.appear on: data['appearing_on']
+ end
+
+ def away
+ current_user.away
+ end
+end
+```
+
+When `#subscribed` callback is invoked by the consumer, a client-side subscription
+is initiated. In this case, we take that opportunity to say "the current user has
+indeed appeared". That appear/disappear API could be backed by Redis, a database,
+or whatever else.
+
+#### Create the client-side Appearance Channel subscription:
+
+```coffeescript
+# app/assets/javascripts/cable/subscriptions/appearance.coffee
+App.cable.subscriptions.create "AppearanceChannel",
+ # Called when the subscription is ready for use on the server
+ connected: ->
+ @install()
+ @appear()
+
+ # Called when the WebSocket connection is closed
+ disconnected: ->
+ @uninstall()
+
+ # Called when the subscription is rejected by the server
+ rejected: ->
+ @uninstall()
+
+ appear: ->
+ # Calls `AppearanceChannel#appear(data)` on the server
+ @perform("appear", appearing_on: $("main").data("appearing-on"))
+
+ away: ->
+ # Calls `AppearanceChannel#away` on the server
+ @perform("away")
+
+
+ buttonSelector = "[data-behavior~=appear_away]"
+
+ install: ->
+ $(document).on "page:change.appearance", =>
+ @appear()
+
+ $(document).on "click.appearance", buttonSelector, =>
+ @away()
+ false
+
+ $(buttonSelector).show()
+
+ uninstall: ->
+ $(document).off(".appearance")
+ $(buttonSelector).hide()
+```
+
+##### Client-Server Interaction
+1. **Client** establishes a connection with the **Server** via `App.cable = ActionCable.createConsumer("ws://cable.example.com")`. [*` cable.coffee`*] The **Server** identified this connection instance by `current_user`.
+2. **Client** initiates a subscription to the `Appearance Channel` for their connection via `App.cable.subscriptions.create "AppearanceChannel"`. [*`appearance.coffee`*]
+3. **Server** recognizes a new subscription has been initiated for `AppearanceChannel` channel performs the `subscribed` callback, which calls the `appear` method on the `current_user`. [*`appearance_channel.rb`*]
+4. **Client** recognizes that a subscription has been established and calls `connected` [*`appearance.coffee`*] which in turn calls `@install` and `@appear`. `@appear` calls`AppearanceChannel#appear(data)` on the server, and supplies a data hash of `appearing_on: $("main").data("appearing-on")`. This is possible because the server-side channel instance will automatically expose the public methods declared on the class (minus the callbacks), so that these can be reached as remote procedure calls via a subscription's `perform` method.
+5. **Server** receives the request for the `appear` action on the `AppearanceChannel` channel for the connection identified by `current_user`. [*`appearance_channel.rb`*] The server retrieves the data with the `appearing_on` key from the data hash, and sets it as the the value for the `on:` key being passed to `current_user.appear`.
+
+### Example 2: Receiving new web notifications
+
+The appearance example was all about exposing server functionality to
+client-side invocation over the WebSocket connection. But the great thing
+about WebSockets is that it's a two-way street. So now let's show an example
+where the server invokes an action on the client.
+
+This is a web notification channel that allows you to trigger client-side
+web notifications when you broadcast to the right streams:
+
+#### Create the server-side Web Notifications Channel:
+
+```ruby
+# app/channels/web_notifications_channel.rb
+class WebNotificationsChannel < ApplicationCable::Channel
+ def subscribed
+ stream_for current_user
+ end
+end
+```
+
+#### Create the client-side Web Notifications Channel subscription:
+```coffeescript
+# app/assets/javascripts/cable/subscriptions/web_notifications.coffee
+# Client-side which assumes you've already requested the right to send web notifications
+App.cable.subscriptions.create "WebNotificationsChannel",
+ received: (data) ->
+ new Notification data["title"], body: data["body"]
+```
+
+#### Broadcast content to a Web Notification Channel instance from elsewhere in your application
+
+```ruby
+# Somewhere in your app this is called, perhaps from a NewCommentJob
+ WebNotificationsChannel.broadcast_to current_user, title: 'New things!', body: 'All the news fit to print'
+```
+
+The `WebNotificationsChannel.broadcast_to` call places a message in the current
+subscription adapter (Redis by default)'s pubsub queue under a separate
+broadcasting name for each user. For a user with an ID of 1, the broadcasting
+name would be `web_notifications_1`.
+
+The channel has been instructed to stream everything that arrives at
+`web_notifications_1` directly to the client by invoking the `#received(data)`
+callback. The data is the hash sent as the second parameter to the server-side
+broadcast call, JSON encoded for the trip across the wire, and unpacked for
+the data argument arriving to `#received`.
+
+### More complete examples
+
+See the [rails/actioncable-examples](http://github.com/rails/actioncable-examples)
+repository for a full example of how to setup Action Cable in a Rails app and adding channels.
+
+## Configuration
+
+Action Cable has two required configurations: a subscription adapter and allowed request origins.
+
+### Subscription Adapter
+
+By default, `ActionCable::Server::Base` will look for a configuration file
+in `Rails.root.join('config/cable.yml')`. The file must specify an adapter
+and a URL for each Rails environment. See the "Dependencies" section for
+additional information on adapters.
+
+```yaml
+production: &production
+ adapter: redis
+ url: redis://10.10.3.153:6381
+development: &development
+ adapter: async
+test: *development
+```
+
+This format allows you to specify one configuration per Rails environment.
+You can also change the location of the Action Cable config file in
+a Rails initializer with something like:
+
+```ruby
+Rails.application.paths.add "config/redis/cable", with: "somewhere/else/cable.yml"
+```
+
+### Allowed Request Origins
+
+Action Cable will only accept requests from specified origins, which are
+passed to the server config as an array. The origins can be instances of
+strings or regular expressions, against which a check for match will be performed.
+
+```ruby
+Rails.application.config.action_cable.allowed_request_origins = ['http://rubyonrails.com', /http:\/\/ruby.*/]
+```
+
+To disable and allow requests from any origin:
+
+```ruby
+Rails.application.config.action_cable.disable_request_forgery_protection = true
+```
+
+By default, Action Cable allows all requests from localhost:3000 when running
+in the development environment.
+
+
+### Consumer Configuration
+
+To configure the URL, add a call to `action_cable_meta_tag` in your HTML layout HEAD.
+This uses a url or path typically set via `config.action_cable.url` in the environment configuration files.
+
+### Other Configurations
+
+The other common option to configure is the log tags applied to the per-connection logger. Here's close to what we're using in Basecamp:
+
+```ruby
+Rails.application.config.action_cable.log_tags = [
+ -> request { request.env['bc.account_id'] || "no-account" },
+ :action_cable,
+ -> request { request.uuid }
+]
+```
+
+For a full list of all configuration options, see the `ActionCable::Server::Configuration` class.
+
+Also note that your server must provide at least the same number of
+database connections as you have workers. The default worker pool is
+set to 100, so that means you have to make at least that available.
+You can change that in `config/database.yml` through the `pool` attribute.
+
+## Running standalone cable servers
+
+### In App
+
+Action Cable can run alongside your Rails application. For example, to
+listen for WebSocket requests on `/websocket`, mount the server at that path:
+
+```ruby
+# config/routes.rb
+Example::Application.routes.draw do
+ mount ActionCable.server => '/cable'
+end
+```
+
+You can use `App.cable = ActionCable.createConsumer()` to connect to the
+cable server if `action_cable_meta_tag` is included in the layout. A custom
+path is specified as first argument to `createConsumer`
+(e.g. `App.cable = ActionCable.createConsumer("/websocket")`).
+
+For every instance of your server you create and for every worker
+your server spawns, you will also have a new instance of ActionCable,
+but the use of Redis keeps messages synced across connections.
+
+### Standalone
+
+The cable servers can be separated from your normal application server.
+It's still a Rack application, but it is its own Rack application.
+The recommended basic setup is as follows:
+
+```ruby
+# cable/config.ru
+require ::File.expand_path('../../config/environment', __FILE__)
+Rails.application.eager_load!
+
+run ActionCable.server
+```
+
+Then you start the server using a binstub in bin/cable ala:
+
+```
+#!/bin/bash
+bundle exec puma -p 28080 cable/config.ru
+```
+
+The above will start a cable server on port 28080.
+
+### Notes
+
+The WebSocket server doesn't have access to the session, but it has
+access to the cookies. This can be used when you need to handle
+authentication. You can see one way of doing that with Devise in this [article](http://www.rubytutorial.io/actioncable-devise-authentication).
+
+## Dependencies
+
+Action Cable provides a subscription adapter interface to process its
+pubsub internals. By default, asynchronous, inline, PostgreSQL, evented
+Redis, and non-evented Redis adapters are included. The default adapter
+in new Rails applications is the asynchronous (`async`) adapter.
+
+The Ruby side of things is built on top of [websocket-driver](https://github.com/faye/websocket-driver-ruby),
+[nio4r](https://github.com/celluloid/nio4r), and [concurrent-ruby](https://github.com/ruby-concurrency/concurrent-ruby).
+
+## Deployment
+
+Action Cable is powered by a combination of WebSockets and threads. Both the
+framework plumbing and user-specified channel work are handled internally by
+utilizing Ruby's native thread support. This means you can use all your regular
+Rails models with no problem, as long as you haven't committed any thread-safety sins.
+
+The Action Cable server implements the Rack socket hijacking API,
+thereby allowing the use of a multithreaded pattern for managing connections
+internally, irrespective of whether the application server is multi-threaded or not.
+
+Accordingly, Action Cable works with all the popular application servers -- Unicorn, Puma and Passenger.
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 543937f8e5..ce6f943e49 100644
--- a/guides/source/action_view_overview.md
+++ b/guides/source/action_view_overview.md
@@ -260,7 +260,7 @@ With the `as` option we can specify a different name for the local variable. For
<%= render partial: "product", as: "item" %>
```
-The `object` option can be used to directly specify which object is rendered into the partial; useful when the template's object is elsewhere (eg. in a different instance variable or in a local variable).
+The `object` option can be used to directly specify which object is rendered into the partial; useful when the template's object is elsewhere (e.g. in a different instance variable or in a local variable).
For example, instead of:
@@ -442,7 +442,7 @@ image_path("edit.png") # => /assets/edit-2d1a2db63fc738690021fedb5a65b68e.png
#### image_url
-Computes the url to an image asset in the `app/assets/images` directory. This will call `image_path` internally and merge with your current host or your asset host.
+Computes the URL to an image asset in the `app/assets/images` directory. This will call `image_path` internally and merge with your current host or your asset host.
```ruby
image_url("edit.png") # => http://www.example.com/assets/edit.png
@@ -493,7 +493,7 @@ javascript_path "common" # => /assets/common.js
#### javascript_url
-Computes the url to a JavaScript asset in the `app/assets/javascripts` directory. This will call `javascript_path` internally and merge with your current host or your asset host.
+Computes the URL to a JavaScript asset in the `app/assets/javascripts` directory. This will call `javascript_path` internally and merge with your current host or your asset host.
```ruby
javascript_url "common" # => http://www.example.com/assets/common.js
@@ -530,7 +530,7 @@ stylesheet_path "application" # => /assets/application.css
#### stylesheet_url
-Computes the url to a stylesheet asset in the `app/assets/stylesheets` directory. This will call `stylesheet_path` internally and merge with your current host or your asset host.
+Computes the URL to a stylesheet asset in the `app/assets/stylesheets` directory. This will call `stylesheet_path` internally and merge with your current host or your asset host.
```ruby
stylesheet_url "application" # => http://www.example.com/assets/application.css
@@ -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 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 `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 %>
@@ -1247,7 +1247,7 @@ file_field_tag 'attachment'
#### form_tag
-Starts a form tag that points the action to a url configured with `url_for_options` just like `ActionController::Base#url_for`.
+Starts a form tag that points the action to a URL configured with `url_for_options` just like `ActionController::Base#url_for`.
```html+erb
<%= form_tag '/articles' do %>
@@ -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 76c13f0ea9..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
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_migrations.md b/guides/source/active_record_migrations.md
index 83f4b951ee..bd7dbd0f11 100644
--- a/guides/source/active_record_migrations.md
+++ b/guides/source/active_record_migrations.md
@@ -883,7 +883,7 @@ 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 `bin/rails db:rollback`), edit your migration and then run
@@ -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 68c6a77882..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
diff --git a/guides/source/active_record_querying.md b/guides/source/active_record_querying.md
index 63658e7c8b..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.
@@ -1296,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 0aca6db9b6..e66b9a4301 100644
--- a/guides/source/active_support_core_extensions.md
+++ b/guides/source/active_support_core_extensions.md
@@ -2240,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"
@@ -3078,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`.
@@ -3467,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:
@@ -3653,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 64b6bb64f2..8dba914923 100644
--- a/guides/source/api_app.md
+++ b/guides/source/api_app.md
@@ -13,8 +13,8 @@ In this guide you will learn:
--------------------------------------------------------------------------------
-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
@@ -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)
@@ -104,21 +103,21 @@ Handled at the Action Pack layer:
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
@@ -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
@@ -153,6 +154,8 @@ This will do three main things for you:
- 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
diff --git a/guides/source/asset_pipeline.md b/guides/source/asset_pipeline.md
index 439f2bef3a..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 your 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
@@ -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.
@@ -1290,7 +1293,7 @@ config.assets.digest = true
# 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`.
diff --git a/guides/source/association_basics.md b/guides/source/association_basics.md
index accce5a904..09ab64837a 100644
--- a/guides/source/association_basics.md
+++ b/guides/source/association_basics.md
@@ -713,7 +713,7 @@ By default, Active Record doesn't know about the connection between these associ
```ruby
a = Author.first
-b = c.books.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
@@ -726,7 +726,7 @@ class Author < ApplicationRecord
has_many :books, inverse_of: :author
end
-class book < ApplicationRecord
+class Book < ApplicationRecord
belongs_to :author, inverse_of: :books
end
```
@@ -735,7 +735,7 @@ With these changes, Active Record will only load one copy of the author object,
```ruby
a = author.first
-b = c.books.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
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 e25992fdef..e865a02cbd 100644
--- a/guides/source/command_line.md
+++ b/guides/source/command_line.md
@@ -325,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`.
@@ -618,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 26e13a4d74..1d3ff6e6e7 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 served over HTTPS by using the `ActionDispatch::SSL` middleware. 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.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`.
@@ -533,6 +535,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:
@@ -547,7 +552,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. 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 `rake rails: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.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`.
@@ -612,6 +617,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`.
@@ -1000,7 +1016,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.
@@ -1014,13 +1030,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.initialize_framework_caches` Sets `ActionController::Base.cache_store` - if it's not already set - to `Rails.cache`.
+* `action_controller.set_helpers_path` Sets Action Controller's helpers_path to the application's helpers_path
+
+* `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.
@@ -1030,13 +1050,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`.
diff --git a/guides/source/debugging_rails_applications.md b/guides/source/debugging_rails_applications.md
index 35ad6eb705..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.
diff --git a/guides/source/documents.yaml b/guides/source/documents.yaml
index fdd6d4d33d..2cf613f47f 100644
--- a/guides/source/documents.yaml
+++ b/guides/source/documents.yaml
@@ -137,7 +137,6 @@
description: This guide explains how to profile your Rails applications to improve performance.
-
name: Using Rails for API-only Applications
- work_in_progress: true
url: api_app.html
description: This guide explains how to effectively use Rails to develop a JSON API application.
diff --git a/guides/source/engines.md b/guides/source/engines.md
index 697938434c..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:
@@ -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
@@ -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
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 2cbc591629..4431512eda 100644
--- a/guides/source/getting_started.md
+++ b/guides/source/getting_started.md
@@ -298,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 "bin/rails 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
@@ -348,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
@@ -625,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.
@@ -635,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
@@ -653,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.
diff --git a/guides/source/i18n.md b/guides/source/i18n.md
index 5bbd4048b9..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
--------------------------------------------------------------------------------
diff --git a/guides/source/layout.html.erb b/guides/source/layout.html.erb
index 1f81ea4694..6db76b528e 100644
--- a/guides/source/layout.html.erb
+++ b/guides/source/layout.html.erb
@@ -24,7 +24,17 @@
<% end %>
<div id="topNav">
<div class="wrapper">
- <strong class="more-info-label">←<a href="http://rubyonrails.org/">Back to rubyonrails.org:</a> </strong>
+ <strong class="more-info-label">More at <a href="http://rubyonrails.org/">rubyonrails.org:</a> </strong>
+ <span class="red-button more-info-button">
+ More Ruby on Rails
+ </span>
+ <ul class="more-info-links s-hidden">
+ <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>
<div id="header">
diff --git a/guides/source/layouts_and_rendering.md b/guides/source/layouts_and_rendering.md
index d55e1007ee..83173e8d75 100644
--- a/guides/source/layouts_and_rendering.md
+++ b/guides/source/layouts_and_rendering.md
@@ -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
diff --git a/guides/source/rails_application_templates.md b/guides/source/rails_application_templates.md
index 5a46baff2d..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/rails rails:template LOCATION=~/template.rb
-$ bin/rails 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 3b61d65df5..b712965b7f 100644
--- a/guides/source/rails_on_rack.md
+++ b/guides/source/rails_on_rack.md
@@ -93,7 +93,7 @@ NOTE: `ActionDispatch::MiddlewareStack` is Rails equivalent of `Rack::Builder`,
### Inspecting Middleware Stack
-Rails has a handy rake task for inspecting the middleware stack in use:
+Rails has a handy task for inspecting the middleware stack in use:
```bash
$ bin/rails middleware
diff --git a/guides/source/routing.md b/guides/source/routing.md
index d9e64d56ac..bd3e236a2b 100644
--- a/guides/source/routing.md
+++ b/guides/source/routing.md
@@ -1136,21 +1136,21 @@ For example, here's a small section of the `rails routes` output for a RESTful r
edit_user GET /users/:id/edit(.:format) users#edit
```
-You can search through your routes with the --grep option (-g for short). This outputs any routes that partially match the URL helper method name, the HTTP verb, or the URL path.
+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/rake routes --grep new_comment
-$ bin/rake routes -g POST
-$ bin/rake routes -g admin
+$ 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 --controller option (-c for short).
+If you only want to see the routes that map to a specific controller, there's the -c option.
```
-$ bin/rake routes --controller users
-$ bin/rake routes --controller admin/users
-$ bin/rake routes -c Comments
-$ bin/rake routes -c Articles::CommentsController
+$ 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 `rails routes` is much more readable if you widen your terminal window until the output lines don't wrap.
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 f4894d4c11..09eec7a64c 100644
--- a/guides/source/testing.md
+++ b/guides/source/testing.md
@@ -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.
+specify to make your test failure messages clearer.
| Assertion | Purpose |
| ---------------------------------------------------------------- | ------- |
@@ -287,7 +287,7 @@ specify to make your test failure messages clearer.
| `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.|
@@ -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.
@@ -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
@@ -518,7 +520,7 @@ 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
@@ -589,7 +591,7 @@ class BlogFlowTest < ActionDispatch::IntegrationTest
end
```
-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.
+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 we visit our root path, we should see `welcome/index.html.erb` rendered for the view. So this assertion should pass.
@@ -828,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:
@@ -866,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:
@@ -912,13 +914,13 @@ 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.
+ # Reload association to fetch updated data and assert that title is updated.
article.reload
- assert_equal "updated", article.title
+ assert_equal "updated", article.title
end
```
@@ -957,11 +959,11 @@ class ArticlesControllerTest < ActionDispatch::IntegrationTest
test "should update article" do
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.
+ # Reload association to fetch updated data and assert that title is updated.
@article.reload
- assert_equal "updated", @article.title
+ assert_equal "updated", @article.title
end
end
```
@@ -1007,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
@@ -1053,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
@@ -1076,28 +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's full name" do
user = users(:david)
- assert_equal "David Heinemeier Hansson", user_full_name(user)
+
+ assert_dom_equal %{<a href="/user/#{user.id}">David Heinemeier Hansson</a>}, link_to_user(user)
end
end
```
@@ -1184,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
@@ -1261,8 +1268,10 @@ class ProductTest < ActiveJob::TestCase
end
```
-Testing Time-Dependent Code
----------------------------
+Additional Testing Resources
+----------------------------
+
+### Testing Time-Dependent Code
Rails provides built-in helper methods that enable you to assert that your time-sensitive code works as expected.
diff --git a/guides/source/upgrading_ruby_on_rails.md b/guides/source/upgrading_ruby_on_rails.md
index 202e5b5cb9..d5576be6f2 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 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
-in the Gemfile, run this rake task.
+Rails provides the `app:update` task. After updating the Rails version
+in the Gemfile, run this 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
@@ -168,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
@@ -402,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.
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
---------------