0
0
RailsHow-ToBeginner · 4 min read

How to Use Callbacks in Rails: Syntax and Examples

In Rails, callbacks are methods that run automatically at certain points in an object's lifecycle, like before saving or after creating a record. You use them by defining methods and linking them with callback macros such as before_save or after_create inside your model.
📐

Syntax

Rails callbacks are declared inside models using macros that specify when the callback runs. Common callbacks include before_save, after_create, and before_destroy. You provide a method name or a block to run at that lifecycle event.

Example parts:

  • before_save :method_name runs method_name before saving the record.
  • after_create do ... end runs the block after a new record is created.
ruby
class User < ApplicationRecord
  before_save :normalize_name
  after_create :send_welcome_email

  private

  def normalize_name
    self.name = name.strip.titleize
  end

  def send_welcome_email
    # code to send email
  end
end
💻

Example

This example shows a User model that cleans the user's name before saving and prints a message after creation.

ruby
class User < ApplicationRecord
  before_save :normalize_name
  after_create :print_welcome_message

  private

  def normalize_name
    self.name = name.strip.capitalize
  end

  def print_welcome_message
    puts "Welcome, #{name}! Your account was created."
  end
end

# Usage example in Rails console:
user = User.new(name: "  alice  ")
user.save
# Output:
# Welcome, Alice! Your account was created.
Output
Welcome, Alice! Your account was created.
⚠️

Common Pitfalls

Common mistakes when using callbacks include:

  • Modifying attributes in after_save or after_create which won't trigger another save automatically.
  • Using callbacks for complex business logic instead of service objects, making code hard to maintain.
  • Forgetting to make callback methods private, exposing internal logic.
  • Causing infinite loops by saving a record inside a before_save callback.
ruby
class User < ApplicationRecord
  # Wrong: modifying attribute after save won't persist changes
  after_save :change_name

  private

  def change_name
    self.name = "Changed"
    # This change won't be saved automatically
  end
end

# Correct approach:
class User < ApplicationRecord
  before_save :change_name

  private

  def change_name
    self.name = "Changed"
  end
end
📊

Quick Reference

CallbackWhen It RunsDescription
before_validationBefore validation runsModify data before validation
after_validationAfter validation runsCheck or log validation results
before_saveBefore saving (create or update)Change data before saving
around_saveWraps save actionRun code before and after save
after_saveAfter savingPerform actions after save
before_createBefore creating new recordSet data before insert
after_createAfter creating new recordTrigger actions after insert
before_updateBefore updating recordModify data before update
after_updateAfter updating recordActions after update
before_destroyBefore deleting recordCleanup before delete
after_destroyAfter deleting recordActions after delete

Key Takeaways

Use Rails callbacks to run code automatically at specific model lifecycle events.
Define callback methods as private and link them with callback macros like before_save or after_create.
Avoid complex logic in callbacks to keep code maintainable and prevent unexpected side effects.
Modify attributes in before_save or before_create callbacks to ensure changes persist.
Be careful to avoid infinite loops by not saving records inside callbacks that trigger saves.