0
0
Ruby on Railsframework~5 mins

Callbacks overview in Ruby on Rails

Choose your learning style9 modes available
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.

You want to set a default value before saving a record.
You need to clean or format data before saving it.
You want to send a notification right after a record is created.
You want to check or prevent something before deleting a record.
You want to log changes automatically when a record updates.
Syntax
Ruby on Rails
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
Callbacks are methods that run automatically at specific moments like before saving or after creating a record.
Use before_ or after_ prefixes to specify when the callback runs.
Examples
This runs the normalize_name method before saving the record.
Ruby on Rails
before_save :normalize_name
This runs the send_welcome_email method right after a new record is created.
Ruby on Rails
after_create :send_welcome_email
This runs check_dependencies before deleting a record to make sure it is safe to delete.
Ruby on Rails
before_destroy :check_dependencies
Sample Program

This example shows a User model with two callbacks. Before saving, it capitalizes the user's name. After creating, it prints a welcome message.

Ruby on Rails
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
OutputSuccess
Important Notes

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.

Summary

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).