Active Record Callbacks
Callbacks are methods which are triggered in an objects lifecycle. Examples of callback for an Active Record object include before_save
, after_save
, before_create
, and after_destroy
. Callbacks are able to execute code in response to events.
Example:
class User < ApplicationRecord
before_save :send_welcome_email
private
def send_welcome_email
puts "Email sent"
end
end
# rails console
User.create
"Email sent"
Above is an example of implementing the callback as a method (send_welcome_email
) and then registering the method as a callback using a class method before_save
. Methods that are used as callbacks should generally be private methods so that they can only be called from within the context of the current object