diff --git a/guides/source/active_record_callbacks.md b/guides/source/active_record_callbacks.md
index a12e4d55486..bfa6712facc 100644
--- a/guides/source/active_record_callbacks.md
+++ b/guides/source/active_record_callbacks.md
@@ -3,108 +3,143 @@
Active Record Callbacks
=======================
-This guide teaches you how to hook into the life cycle of your Active Record objects.
+This guide teaches you how to hook into the life cycle of your Active Record
+objects.
After reading this guide, you will know:
-* When certain events occur during the life of an Active Record object
-* How to create callback methods that respond to events in the object life cycle.
-* How to create special classes that encapsulate common behavior for your callbacks.
+* When certain events occur during the life of an Active Record object.
+* How to register, run, and skip callbacks that respond to these events.
+* How to create relational, association, conditional, and transactional
+ callbacks.
+* How to create objects that encapsulate common behavior for your callbacks to
+ be reused.
--------------------------------------------------------------------------------
The Object Life Cycle
---------------------
-During the normal operation of a Rails application, objects may be created, updated, and destroyed. Active Record provides hooks into this *object life cycle* so that you can control your application and its data.
+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 an alteration of an object's state.
+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.
```ruby
-class Baby < ApplicationRecord
- after_create -> { puts "Congratulations!" }
+class BirthdayCake < ApplicationRecord
+ after_create -> { Rails.logger.info("Congratulations, the callback has run!") }
end
```
```irb
-irb> @baby = Baby.create
-Congratulations!
+irb> BirthdayCake.create
+Congratulations, the callback has run!
```
-As you will see, there are many life cycle events and you can choose to hook into any of these either before, after, or even around them.
+As you will see, there are many life cycle events and multiple options to hook
+into these — either before, after, or even around them.
-Callbacks Overview
-------------------
+Callback Registration
+---------------------
-Callbacks 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 created, saved, updated, deleted, validated, or loaded from the database.
+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.
-### Callback Registration
-
-In order to use the available callbacks, you need to register them. You can implement the callbacks as ordinary methods and use a macro-style class method to register them as callbacks:
+You can register the callbacks with a **macro-style class method that calls an
+ordinary method** for implementation.
```ruby
class User < ApplicationRecord
- validates :login, :email, presence: true
+ validates :username, :email, presence: true
- before_validation :ensure_login_has_a_value
+ before_validation :ensure_username_has_value
private
- def ensure_login_has_a_value
- if login.blank?
- self.login = email unless email.blank?
+ 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:
+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:
```ruby
class User < ApplicationRecord
- validates :login, :email, presence: true
+ validates :username, :email, presence: true
- before_create do
- self.name = login.capitalize if name.blank?
+ before_validation do
+ self.username = email if username.blank?
end
end
```
-Alternatively you can pass a proc to the callback to be triggered.
+Alternatively, you can **pass a proc to the callback** to be triggered.
```ruby
class User < ApplicationRecord
- before_create ->(user) { user.name = user.login.capitalize if user.name.blank? }
+ validates :username, :email, presence: true
+
+ before_validation ->(user) { user.username = user.email if user.username.blank? }
end
```
-Lastly, you can define your own custom callback object, which we will cover later in more detail [below](#callback-classes).
+Lastly, you can define **a custom callback object**, as shown below. We will
+cover these [later in more detail](#callback-objects).
```ruby
class User < ApplicationRecord
- before_create MaybeAddName
+ validates :username, :email, presence: true
+
+ before_validation AddUsername
end
-class MaybeAddName
- def self.before_create(record)
- if record.name.blank?
- record.name = record.login.capitalize
+class AddUsername
+ def self.before_validation(record)
+ if record.username.blank?
+ record.username = record.email
end
end
end
```
-Callbacks can also be registered to only fire on certain life cycle events, this allows complete control over when and in what context your callbacks are triggered.
+### 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.
+
+NOTE: 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.
```ruby
class User < ApplicationRecord
- before_validation :normalize_name, on: :create
+ 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 normalize_name
- self.name = name.downcase.titleize
+ def ensure_username_has_value
+ if username.blank?
+ self.username = email
+ end
end
def set_location
@@ -113,14 +148,23 @@ class User < ApplicationRecord
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.
+NOTE: 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.
-WARNING. Avoid calls to `update`, `save` or other methods which create side-effects to the object inside your callback. For example, don't call `update(attribute: "value")` within a callback. This can alter the state of the model and may result in unexpected side effects during commit. Instead, you can safely assign values directly (for example, `self.attribute = "value"`) in `before_create` / `before_update` or earlier callbacks.
+WARNING. 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.
Available Callbacks
-------------------
-Here is a list with all the available Active Record callbacks, listed in the same order in which they will get called during the respective operations:
+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:
### Creating an Object
@@ -134,19 +178,165 @@ Here is a list with all the available Active Record callbacks, listed in the sam
* [`after_save`][]
* [`after_commit`][] / [`after_rollback`][]
-[`after_create`]: https://api.rubyonrails.org/classes/ActiveRecord/Callbacks/ClassMethods.html#method-i-after_create
-[`after_commit`]: https://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html#method-i-after_commit
-[`after_rollback`]: https://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html#method-i-after_rollback
-[`after_save`]: https://api.rubyonrails.org/classes/ActiveRecord/Callbacks/ClassMethods.html#method-i-after_save
-[`after_validation`]: https://api.rubyonrails.org/classes/ActiveModel/Validations/Callbacks/ClassMethods.html#method-i-after_validation
-[`around_create`]: https://api.rubyonrails.org/classes/ActiveRecord/Callbacks/ClassMethods.html#method-i-around_create
-[`around_save`]: https://api.rubyonrails.org/classes/ActiveRecord/Callbacks/ClassMethods.html#method-i-around_save
-[`before_create`]: https://api.rubyonrails.org/classes/ActiveRecord/Callbacks/ClassMethods.html#method-i-before_create
-[`before_save`]: https://api.rubyonrails.org/classes/ActiveRecord/Callbacks/ClassMethods.html#method-i-before_save
-[`before_validation`]: https://api.rubyonrails.org/classes/ActiveModel/Validations/Callbacks/ClassMethods.html#method-i-before_validation
+`after_commit` / `after_rollback` examples can be found
+[here](active_record_callbacks.html#after-commit-and-after-rollback).
+
+[`after_create`]:
+ https://api.rubyonrails.org/classes/ActiveRecord/Callbacks/ClassMethods.html#method-i-after_create
+[`after_commit`]:
+ https://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html#method-i-after_commit
+[`after_rollback`]:
+ https://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html#method-i-after_rollback
+[`after_save`]:
+ https://api.rubyonrails.org/classes/ActiveRecord/Callbacks/ClassMethods.html#method-i-after_save
+[`after_validation`]:
+ https://api.rubyonrails.org/classes/ActiveModel/Validations/Callbacks/ClassMethods.html#method-i-after_validation
+[`around_create`]:
+ https://api.rubyonrails.org/classes/ActiveRecord/Callbacks/ClassMethods.html#method-i-around_create
+[`around_save`]:
+ https://api.rubyonrails.org/classes/ActiveRecord/Callbacks/ClassMethods.html#method-i-around_save
+[`before_create`]:
+ https://api.rubyonrails.org/classes/ActiveRecord/Callbacks/ClassMethods.html#method-i-before_create
+[`before_save`]:
+ https://api.rubyonrails.org/classes/ActiveRecord/Callbacks/ClassMethods.html#method-i-before_save
+[`before_validation`]:
+ https://api.rubyonrails.org/classes/ActiveModel/Validations/Callbacks/ClassMethods.html#method-i-before_validation
+
+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.
+
+#### Validation Callbacks
+
+Validation callbacks are triggered whenever the record is validated directly via
+the
+[`valid?`](https://api.rubyonrails.org/classes/ActiveModel/Validations.html#method-i-valid-3F)
+( or its alias
+[`validate`](https://api.rubyonrails.org/classes/ActiveModel/Validations.html#method-i-validate))
+or
+[`invalid?`](https://api.rubyonrails.org/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.
+
+```ruby
+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
+irb> user = User.new(name: "", email: "john.doe@example.com", password: "abc123456")
+=> #
+
+irb> user.valid?
+Name titleized to
+Validation failed: Name can't be blank
+=> false
+```
+
+#### 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.
+
+```ruby
+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
+irb> user = User.create(name: "Jane Doe", password: "password", email: "jane.doe@example.com")
+
+Password encrypted 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
+=> #
+```
+
+#### 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.
+
+```ruby
+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
+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
+=> #
+```
### 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`][]
* [`after_validation`][]
* [`before_save`][]
@@ -157,45 +347,186 @@ Here is a list with all the available Active Record callbacks, listed in the sam
* [`after_save`][]
* [`after_commit`][] / [`after_rollback`][]
-[`after_update`]: https://api.rubyonrails.org/classes/ActiveRecord/Callbacks/ClassMethods.html#method-i-after_update
-[`around_update`]: https://api.rubyonrails.org/classes/ActiveRecord/Callbacks/ClassMethods.html#method-i-around_update
-[`before_update`]: https://api.rubyonrails.org/classes/ActiveRecord/Callbacks/ClassMethods.html#method-i-before_update
+[`after_update`]:
+ https://api.rubyonrails.org/classes/ActiveRecord/Callbacks/ClassMethods.html#method-i-after_update
+[`around_update`]:
+ https://api.rubyonrails.org/classes/ActiveRecord/Callbacks/ClassMethods.html#method-i-around_update
+[`before_update`]:
+ https://api.rubyonrails.org/classes/ActiveRecord/Callbacks/ClassMethods.html#method-i-before_update
-WARNING. `after_save` runs both on create and update, but always _after_ the more specific callbacks `after_create` and `after_update`, no matter the order in which the macro calls were executed.
+WARNING: 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. `after_commit` / `after_rollback` examples
+can be found [here](#after-commit-and-after-rollback).
+
+#### Update Callbacks
+
+```ruby
+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
+irb> user = User.find(1)
+=> #
+
+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
+```
+
+#### 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.
+
+```ruby
+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
+irb> user = User.create(name: "John Doe", email: "john.doe@example.com")
+Confirmation email sent to: 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
+```
### 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`][]
* [`around_destroy`][]
* [`after_destroy`][]
* [`after_commit`][] / [`after_rollback`][]
-[`after_destroy`]: https://api.rubyonrails.org/classes/ActiveRecord/Callbacks/ClassMethods.html#method-i-after_destroy
-[`around_destroy`]: https://api.rubyonrails.org/classes/ActiveRecord/Callbacks/ClassMethods.html#method-i-around_destroy
-[`before_destroy`]: https://api.rubyonrails.org/classes/ActiveRecord/Callbacks/ClassMethods.html#method-i-before_destroy
+[`after_destroy`]:
+ https://api.rubyonrails.org/classes/ActiveRecord/Callbacks/ClassMethods.html#method-i-after_destroy
+[`around_destroy`]:
+ https://api.rubyonrails.org/classes/ActiveRecord/Callbacks/ClassMethods.html#method-i-around_destroy
+[`before_destroy`]:
+ https://api.rubyonrails.org/classes/ActiveRecord/Callbacks/ClassMethods.html#method-i-before_destroy
-NOTE: `before_destroy` callbacks 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`.
+`after_commit` / `after_rollback` examples can be found
+[here](#after-commit-and-after-rollback).
-WARNING. `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. While anything that happens `after_commit` can guarantee the transaction has already completed and the data was persisted to the database. More on [transactional callbacks](#transaction-callbacks) below.
+#### Destroy Callbacks
+
+```ruby
+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
+irb> user = User.find(1)
+=> #
+
+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
+```
### `after_initialize` and `after_find`
-Whenever an Active Record object is instantiated the [`after_initialize`][] callback will be called, either by directly using `new` or when a record is loaded from the database. It can be useful to avoid the need to directly override your Active Record `initialize` method.
+Whenever an Active Record object is instantiated, either by directly using `new`
+or when a record is loaded from the database, the [`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`][] callback will be called. `after_find` is called before `after_initialize` if both are defined.
+When loading a record from the database the [`after_find`][] callback will be
+called. `after_find` is called before `after_initialize` if both are defined.
-NOTE: The `after_initialize` and `after_find` callbacks have no `before_*` counterparts.
+NOTE: The `after_initialize` and `after_find` callbacks have no `before_*`
+counterparts.
They can be registered just like the other Active Record callbacks.
```ruby
class User < ApplicationRecord
after_initialize do |user|
- puts "You have initialized an object!"
+ Rails.logger.info("You have initialized an object!")
end
after_find do |user|
- puts "You have found an object!"
+ Rails.logger.info("You have found an object!")
end
end
```
@@ -211,26 +542,30 @@ You have initialized an object!
=> #
```
-[`after_find`]: https://api.rubyonrails.org/classes/ActiveRecord/Callbacks/ClassMethods.html#method-i-after_find
-[`after_initialize`]: https://api.rubyonrails.org/classes/ActiveRecord/Callbacks/ClassMethods.html#method-i-after_initialize
+[`after_find`]:
+ https://api.rubyonrails.org/classes/ActiveRecord/Callbacks/ClassMethods.html#method-i-after_find
+[`after_initialize`]:
+ https://api.rubyonrails.org/classes/ActiveRecord/Callbacks/ClassMethods.html#method-i-after_initialize
### `after_touch`
-The [`after_touch`][] callback will be called whenever an Active Record object is touched.
+The [`after_touch`][] callback will be called whenever an Active Record object
+is touched. You can read more about `touch`
+[here](https://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-touch).
```ruby
class User < ApplicationRecord
after_touch do |user|
- puts "You have touched an object"
+ Rails.logger.info("You have touched an object")
end
end
```
```irb
-irb> u = User.create(name: 'Kuldeep')
+irb> user = User.create(name: "Kuldeep")
=> #
-irb> u.touch
+irb> user.touch
You have touched an object
=> true
```
@@ -241,7 +576,7 @@ It can be used along with `belongs_to`:
class Book < ApplicationRecord
belongs_to :library, touch: true
after_touch do
- puts 'A Book was touched'
+ Rails.logger.info("A Book was touched")
end
end
@@ -251,22 +586,23 @@ class Library < ApplicationRecord
private
def log_when_books_or_library_touched
- puts 'Book/Library was touched'
+ Rails.logger.info("Book/Library was touched")
end
end
```
```irb
-irb> @book = Book.last
+irb> book = Book.last
=> #
-irb> @book.touch # triggers @book.library.touch
+irb> book.touch # triggers book.library.touch
A Book was touched
Book/Library was touched
=> true
```
-[`after_touch`]: https://api.rubyonrails.org/classes/ActiveRecord/Callbacks/ClassMethods.html#method-i-after_touch
+[`after_touch`]:
+ https://api.rubyonrails.org/classes/ActiveRecord/Callbacks/ClassMethods.html#method-i-after_touch
Running Callbacks
-----------------
@@ -289,26 +625,124 @@ The following methods trigger callbacks:
* `update`
* `update!`
* `valid?`
+* `validate`
-Additionally, the `after_find` callback is triggered by the following finder methods:
+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 `after_initialize` callback is triggered every time a new object of the
+class is initialized.
-NOTE: The `find_by_*` and `find_by_*!` methods are dynamic finders generated automatically for every attribute. Learn more about them at the [Dynamic finders section](active_record_querying.html#dynamic-finders)
+NOTE: 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-finders).
+
+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.
+
+### 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.
+
+```ruby
+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 [below](#multiple-callback-conditions).
+
+### 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:
+
+```ruby
+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:
+
+```ruby
+class Order < ApplicationRecord
+ before_save :normalize_card_number, if: -> { paid_with_card? }
+end
+```
+
+### Multiple Callback Conditions
+
+The `:if` and `:unless` options also accept an array of procs or method names as
+symbols:
+
+```ruby
+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:
+
+```ruby
+class Comment < ApplicationRecord
+ before_save :filter_content,
+ if: [:subject_to_parental_control?, -> { untrusted_author? }]
+end
+```
+
+### Using Both `:if` and `:unless`
+
+Callbacks can mix both `:if` and `:unless` in the same declaration:
+
+```ruby
+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`.
Skipping Callbacks
------------------
-Just as with validations, it is also possible to skip callbacks by using the following methods:
+Just as with [validations](active_record_validations.html), it is also possible
+to skip callbacks by using the following methods:
* [`decrement!`][]
* [`decrement_counter`][]
@@ -329,46 +763,284 @@ Just as with validations, it is also possible to skip callbacks by using the fol
* [`upsert`][]
* [`upsert_all`][]
-These methods should be used with caution, however, because important business rules and application logic may be kept in callbacks. Bypassing them without understanding the potential implications may lead to invalid data. Refer to the method documentation to learn more.
+Let's consider a `User` model where the `before_save` callback logs any changes
+to the user's email address:
-[`decrement!`]: https://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-decrement-21
-[`decrement_counter`]: https://api.rubyonrails.org/classes/ActiveRecord/CounterCache/ClassMethods.html#method-i-decrement_counter
-[`delete`]: https://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-delete
-[`delete_all`]: https://api.rubyonrails.org/classes/ActiveRecord/Relation.html#method-i-delete_all
-[`delete_by`]: https://api.rubyonrails.org/classes/ActiveRecord/Relation.html#method-i-delete_by
-[`increment!`]: https://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-increment-21
-[`increment_counter`]: https://api.rubyonrails.org/classes/ActiveRecord/CounterCache/ClassMethods.html#method-i-increment_counter
-[`insert`]: https://api.rubyonrails.org/classes/ActiveRecord/Persistence/ClassMethods.html#method-i-insert
-[`insert!`]: https://api.rubyonrails.org/classes/ActiveRecord/Persistence/ClassMethods.html#method-i-insert-21
-[`insert_all`]: https://api.rubyonrails.org/classes/ActiveRecord/Persistence/ClassMethods.html#method-i-insert_all
-[`insert_all!`]: https://api.rubyonrails.org/classes/ActiveRecord/Persistence/ClassMethods.html#method-i-insert_all-21
-[`touch_all`]: https://api.rubyonrails.org/classes/ActiveRecord/Relation.html#method-i-touch_all
-[`update_column`]: https://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-update_column
-[`update_columns`]: https://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-update_columns
-[`update_all`]: https://api.rubyonrails.org/classes/ActiveRecord/Relation.html#method-i-update_all
-[`update_counters`]: https://api.rubyonrails.org/classes/ActiveRecord/Relation.html#method-i-update_counters
-[`upsert`]: https://api.rubyonrails.org/classes/ActiveRecord/Persistence/ClassMethods.html#method-i-upsert
-[`upsert_all`]: https://api.rubyonrails.org/classes/ActiveRecord/Persistence/ClassMethods.html#method-i-upsert_all
+```ruby
+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
+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.
+
+WARNING. 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.
+
+[`decrement!`]:
+ https://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-decrement-21
+[`decrement_counter`]:
+ https://api.rubyonrails.org/classes/ActiveRecord/CounterCache/ClassMethods.html#method-i-decrement_counter
+[`delete`]:
+ https://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-delete
+[`delete_all`]:
+ https://api.rubyonrails.org/classes/ActiveRecord/Relation.html#method-i-delete_all
+[`delete_by`]:
+ https://api.rubyonrails.org/classes/ActiveRecord/Relation.html#method-i-delete_by
+[`increment!`]:
+ https://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-increment-21
+[`increment_counter`]:
+ https://api.rubyonrails.org/classes/ActiveRecord/CounterCache/ClassMethods.html#method-i-increment_counter
+[`insert`]:
+ https://api.rubyonrails.org/classes/ActiveRecord/Persistence/ClassMethods.html#method-i-insert
+[`insert!`]:
+ https://api.rubyonrails.org/classes/ActiveRecord/Persistence/ClassMethods.html#method-i-insert-21
+[`insert_all`]:
+ https://api.rubyonrails.org/classes/ActiveRecord/Persistence/ClassMethods.html#method-i-insert_all
+[`insert_all!`]:
+ https://api.rubyonrails.org/classes/ActiveRecord/Persistence/ClassMethods.html#method-i-insert_all-21
+[`touch_all`]:
+ https://api.rubyonrails.org/classes/ActiveRecord/Relation.html#method-i-touch_all
+[`update_column`]:
+ https://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-update_column
+[`update_columns`]:
+ https://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-update_columns
+[`update_all`]:
+ https://api.rubyonrails.org/classes/ActiveRecord/Relation.html#method-i-update_all
+[`update_counters`]:
+ https://api.rubyonrails.org/classes/ActiveRecord/Relation.html#method-i-update_counters
+[`upsert`]:
+ https://api.rubyonrails.org/classes/ActiveRecord/Persistence/ClassMethods.html#method-i-upsert
+[`upsert_all`]:
+ https://api.rubyonrails.org/classes/ActiveRecord/Persistence/ClassMethods.html#method-i-upsert_all
+
+Suppressing Callbacks
+---------------------
+
+In certain scenarios, you may need to temporarily prevent certain callbacks from
+being executed within your Rails application. This can be useful when you want
+to skip specific actions during certain operations without permanently disabling
+the callbacks.
+
+Rails provides a mechanism for suppressing callbacks using the
+[`ActiveRecord::Suppressor`
+module](https://api.rubyonrails.org/classes/ActiveRecord/Suppressor.html). By
+using this module, you can wrap a block of code where you want to suppress
+callbacks, ensuring that they are not executed during that specific operation.
+
+Let's consider a scenario where we have a `User` model with a callback that
+sends a welcome email to new users after they sign up. However, there might be
+cases where we want to create a user without sending the welcome email, such as
+during seeding the database with test data.
+
+```ruby
+class User < ApplicationRecord
+ after_create :send_welcome_email
+
+ def send_welcome_email
+ puts "Welcome email sent to #{self.email}"
+ end
+end
+```
+
+In this example, the `after_create` callback triggers the `send_welcome_email`
+method every time a new user is created.
+
+To create a user without sending the welcome email, we can use the
+`ActiveRecord::Suppressor` module as follows:
+
+```ruby
+User.suppress do
+ User.create(name: "Jane", email: "jane@example.com")
+end
+```
+
+In the above code, the `User.suppress` block ensures that the
+`send_welcome_email` callback is not executed during the creation of the "Jane"
+user, allowing us to create the user without sending the welcome email.
+
+WARNING: Using the Active Record Suppressor, while potentially beneficial for
+selectively controlling callback execution, can introduce complexity and
+unexpected behavior. Suppressing callbacks can obscure the intended flow of your
+application, leading to difficulties in understanding and maintaining the
+codebase over time. Carefully consider the implications of suppressing
+callbacks, ensuring thorough documentation and thoughtful testing to mitigate
+risks of unintended side effects, performance issues, and test failures.
Halting Execution
-----------------
-As you start registering new callbacks for your models, they will be queued for execution. This queue will include all your model's validations, the registered callbacks, and the database operation to be executed.
+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. To intentionally stop a chain use:
+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.
```ruby
-throw :abort
+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"
```
-WARNING. Any exception that is not `ActiveRecord::Rollback` or `ActiveRecord::RecordInvalid` will be re-raised by Rails after the callback chain is halted. Additionally, may break code that does not expect methods like `save` and `update` (which normally try to return `true` or `false`) to raise an exception.
+This unexpectedly breaks code that does not expect methods like `create` and
+`save` to raise exceptions.
-NOTE: If an `ActiveRecord::RecordNotDestroyed` is raised within `after_destroy`, `before_destroy` or `around_destroy` callback, it will not be re-raised and the `destroy` method will return `false`.
+NOTE: 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.
-Relational Callbacks
---------------------
+```ruby
+class Product < ActiveRecord::Base
+ before_validation do
+ throw :abort if total_price < 0
+ end
+end
-Callbacks work through model relationships, and can even be defined by them. 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 relationship to the `Article` model:
+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.
+
+```ruby
+User.create! # => raises an ActiveRecord::RecordNotSaved
+```
+
+
+When `throw :abort` is called in any destroy callback, `destroy` will return
+false:
+
+```ruby
+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!`.
+
+```ruby
+User.first.destroy! # => raises an ActiveRecord::RecordNotDestroyed
+```
+
+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.
+
+```ruby
+class Author < ApplicationRecord
+ has_many :books, before_add: :check_limit
+
+ private
+ def check_limit
+ 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.
+
+```ruby
+class Author < ApplicationRecord
+ has_many :books, before_add: [:check_limit, :calculate_shipping_charges]
+
+ def check_limit
+ 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.
+
+NOTE: These callbacks are called only when the associated objects are added or
+removed through the association collection.
+
+```ruby
+# Triggers `before_add` callback
+author.books << book
+author.books = [book, book2]
+
+# Does not trigger the `before_add` callback
+book.update(author_id: 1)
+```
+
+Cascading Association Callbacks
+-------------------------------
+
+Callbacks can be performed when asssociated 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:
```ruby
class User < ApplicationRecord
@@ -379,7 +1051,7 @@ class Article < ApplicationRecord
after_destroy :log_destroy_action
def log_destroy_action
- puts 'Article destroyed'
+ Rails.logger.info("Article destroyed")
end
end
```
@@ -394,198 +1066,42 @@ Article destroyed
=> #
```
-Association Callbacks
----------------------
-
-Association callbacks are similar to normal callbacks, but they are triggered by events in the life cycle of a collection. 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:
-
-```ruby
-class Author < ApplicationRecord
- has_many :books, before_add: :check_credit_limit
-
- def check_credit_limit(book)
- # ...
- end
-end
-```
-
-Rails passes the object being added or removed to the callback.
-
-You can stack callbacks on a single event by passing them as an array:
-
-```ruby
-class Author < ApplicationRecord
- has_many :books,
- before_add: [:check_credit_limit, :calculate_shipping_charges]
-
- def check_credit_limit(book)
- # ...
- end
-
- def calculate_shipping_charges(book)
- # ...
- end
-end
-```
-
-If a `before_add` callback throws `:abort`, the object does not get added to
-the collection. Similarly, if a `before_remove` callback throws `:abort`, the
-object does not get removed from the collection:
-
-```ruby
-# book won't be added if the limit has been reached
-def check_credit_limit(book)
- throw(:abort) if limit_reached?
-end
-```
-
-NOTE: These callbacks are called only when the associated objects are added or removed through the association collection:
-
-```ruby
-# Triggers `before_add` callback
-author.books << book
-author.books = [book, book2]
-
-# Does not trigger the `before_add` callback
-book.update(author_id: 1)
-```
-
-Conditional Callbacks
----------------------
-
-As with validations, 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.
-
-### 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.
-
-```ruby
-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 [below](#multiple-callback-conditions).
-
-### 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:
-
-```ruby
-class Order < ApplicationRecord
- before_save :normalize_card_number,
- if: Proc.new { |order| order.paid_with_card? }
-end
-```
-
-As the proc is evaluated in the context of the object, it is also possible to write this as:
-
-```ruby
-class Order < ApplicationRecord
- before_save :normalize_card_number, if: Proc.new { paid_with_card? }
-end
-```
-
-### Multiple Callback Conditions
-
-The `:if` and `:unless` options also accept an array of procs or method names as symbols:
-
-```ruby
-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:
-
-```ruby
-class Comment < ApplicationRecord
- before_save :filter_content,
- if: [:subject_to_parental_control?, Proc.new { untrusted_author? }]
-end
-```
-
-### Using Both `:if` and `:unless`
-
-Callbacks can mix both `:if` and `:unless` in the same declaration:
-
-```ruby
-class Comment < ApplicationRecord
- before_save :filter_content,
- if: Proc.new { forum.parental_control? },
- unless: Proc.new { author.trusted? }
-end
-```
-
-The callback only runs when all the `:if` conditions and none of the `:unless` conditions are evaluated to `true`.
-
-Callback Classes
-----------------
-
-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 where we create a class with an `after_destroy` callback to deal with the clean up 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.
-
-```ruby
-class FileDestroyerCallback
- def after_destroy(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:
-
-```ruby
-class PictureFile < ApplicationRecord
- after_destroy 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:
-
-```ruby
-class FileDestroyerCallback
- def self.after_destroy(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.
-
-```ruby
-class PictureFile < ApplicationRecord
- after_destroy FileDestroyerCallback
-end
-```
-
-You can declare as many callbacks as you want inside your callback classes.
+WARNING: 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`.
Transaction Callbacks
---------------------
### `after_commit` and `after_rollback`
-There are two additional callbacks that are triggered by the completion of a database transaction: [`after_commit`][] and [`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 which are not part of the database transaction.
+Two additional callbacks are triggered by the completion of a database
+transaction: [`after_commit`][] and [`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, for example, the previous example where the `PictureFile` model needs to delete a file after the corresponding record is destroyed. If anything raises an exception after the `after_destroy` callback is called and the transaction rolls back, 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.
+Consider a `PictureFile` model that needs to delete a file after the
+corresponding record is destroyed.
+
+```ruby
+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.
```ruby
PictureFile.transaction do
@@ -608,32 +1124,116 @@ class PictureFile < ApplicationRecord
end
```
-NOTE: The `:on` option specifies when a callback will be fired. If you don't supply the `:on` option the callback will fire for every action.
+NOTE: 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` [here](#registering-callbacks-to-fire-on-life-cycle-events).
-WARNING. 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. As such, if your callback code could raise an exception, you'll need to rescue it and handle it within the callback in order to allow other callbacks to run.
+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.
-WARNING. The code executed within `after_commit` or `after_rollback` callbacks is itself not enclosed within a transaction.
+```ruby
+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
+```
-WARNING. In the context of a single transaction, if you interact with multiple
-loaded objects that 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
-undergoes a change within the transaction. Other loaded objects, despite
-representing the same database record, will not have their respective
-`after_commit` or `after_rollback` callbacks triggered. 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.
+WARNING. 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.
+
+```ruby
+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.
+
+```ruby
+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.
+
+```ruby
+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
+irb> user = User.create
+irb> User.transaction { user.save; user.save }
+# User was saved to database
+```
+
+WARNING: 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.
### Aliases for `after_commit`
-Since using the `after_commit` callback only on create, update, or delete is
-common, there are aliases for those operations:
+Using the `after_commit` callback only on create, update, or delete 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`][]
* [`after_create_commit`][]
* [`after_update_commit`][]
-* [`after_destroy_commit`][]
+* [`after_save_commit`][]
+
+Let's go through some examples:
+
+Instead of using `after_commit` with the `on` option for a destroy like below:
+
+```ruby
+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`.
```ruby
class PictureFile < ApplicationRecord
@@ -647,7 +1247,12 @@ class PictureFile < ApplicationRecord
end
```
-WARNING. Using both `after_create_commit` and `after_update_commit` with the same method name 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.
+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.
```ruby
class User < ApplicationRecord
@@ -656,21 +1261,21 @@ class User < ApplicationRecord
private
def log_user_saved_to_db
- puts 'User was saved to database'
+ # This only gets called once
+ Rails.logger.info("User was saved to database")
end
end
```
```irb
-irb> @user = User.create # prints nothing
+irb> user = User.create # prints nothing
-irb> @user.save # updating @user
+irb> user.save # updating @user
User was saved to database
```
-### `after_save_commit`
-
-There is also [`after_save_commit`][], which is an alias for using the `after_commit` callback for both create and update together:
+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:
```ruby
class User < ApplicationRecord
@@ -678,44 +1283,111 @@ class User < ApplicationRecord
private
def log_user_saved_to_db
- puts 'User was saved to database'
+ Rails.logger.info("User was saved to database")
end
end
```
```irb
-irb> @user = User.create # creating a User
+irb> user = User.create # creating a User
User was saved to database
-irb> @user.save # updating @user
+irb> user.save # updating user
User was saved to database
```
### Transactional Callback Ordering
-By default, callbacks will run in the order they are defined. However, when
-defining multiple transactional `after_` callbacks (`after_commit`,
-`after_rollback`, etc), the order could be reversed from when they are defined.
+By default (from Rails 7.1), transaction callbacks will run in the order they
+are defined.
```ruby
class User < ActiveRecord::Base
- after_commit { puts("this actually gets called second") }
- after_commit { puts("this actually gets called first") }
+ after_commit { Rails.logger.info("this gets called first") }
+ after_commit { Rails.logger.info("this gets called second") }
end
```
-NOTE: This applies to all `after_*_commit` variations too, such as `after_destroy_commit`.
+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.
-This order can be set via configuration:
+If for some reason you'd still like them to run in reverse, you can set the
+[following
+configuration](configuring.html#config-active-record-run-after-transaction-callbacks-in-order-defined)
+to `false`. The callbacks will then run in the reverse order.
```ruby
config.active_record.run_after_transaction_callbacks_in_order_defined = false
```
-When set to `true` (the default from Rails 7.1), callbacks are executed in the order they
-are defined. When set to `false`, the order is reversed, just like in the example above.
+NOTE: This applies to all `after_*_commit` variations too, such as
+`after_destroy_commit`.
-[`after_create_commit`]: https://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html#method-i-after_create_commit
-[`after_destroy_commit`]: https://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html#method-i-after_destroy_commit
-[`after_save_commit`]: https://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html#method-i-after_save_commit
-[`after_update_commit`]: https://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html#method-i-after_update_commit
+[`after_create_commit`]:
+ https://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html#method-i-after_create_commit
+[`after_destroy_commit`]:
+ https://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html#method-i-after_destroy_commit
+[`after_save_commit`]:
+ https://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html#method-i-after_save_commit
+[`after_update_commit`]:
+ https://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html#method-i-after_update_commit
+
+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.
+
+```ruby
+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:
+
+```ruby
+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:
+
+```ruby
+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.
+
+```ruby
+class PictureFile < ApplicationRecord
+ after_commit FileDestroyerCallback
+end
+```
+
+You can declare as many callbacks as you want inside your callback objects.