Introduction
Callbacks let you run code automatically at certain points in an object's life. They help keep your code organized and avoid repeating yourself.
Callbacks let you run code automatically at certain points in an object's life. They help keep your code organized and avoid repeating yourself.
class ModelName < ApplicationRecord before_save :method_name after_create :another_method private def method_name # code to run before saving end def another_method # code to run after creating end end
before_ or after_ prefixes to specify when the callback runs.normalize_name method before saving the record.before_save :normalize_name
send_welcome_email method right after a new record is created.after_create :send_welcome_email
check_dependencies before deleting a record to make sure it is safe to delete.before_destroy :check_dependencies
This example shows a User model with two callbacks. Before saving, it capitalizes the user's name. After creating, it prints a welcome message.
class User < ApplicationRecord before_save :capitalize_name after_create :welcome_message private def capitalize_name self.name = name.capitalize end def welcome_message puts "Welcome, #{name}! Your account was created." end end # Simulate creating a user user = User.new(name: 'alice') user.save
Callbacks help keep your code clean by running code automatically at key moments.
Be careful not to put too much logic in callbacks to keep your code easy to understand.
Callbacks run code automatically at specific points in a model's life.
Use before_ and after_ prefixes to control when they run.
They help keep your code organized and DRY (Don't Repeat Yourself).
before_save :method_name to run a method before saving a record.after_save runs after saving, on_save is invalid, and the block syntax is incorrect here.class User < ApplicationRecord
before_create :set_default_role
def set_default_role
self.role ||= 'guest'
end
endbefore_create callback runs the method set_default_role before the record is created in the database.self.role to 'guest' only if it is currently nil or falsey (using ||=).class Post < ApplicationRecord
before_save :check_title
def check_title
if title.blank?
errors.add(:title, "can't be blank")
throw :abort
end
end
endbefore_save callback runs check_title before saving.throw :abort is the correct way to stop saving if validation fails.log_update only after a record is updated but not created. Which callback should you use?after_save runs after both create and update, but after_update runs only after updates.log_update only after updates, after_update is the correct choice.Pass the test and this pattern moves unknown