0
0
RailsConceptBeginner · 3 min read

What is before_save Callback in Ruby on Rails: Explained Simply

In Ruby on Rails, the before_save callback is a method that runs just before an object is saved to the database. It lets you change or check data automatically before the save happens.
⚙️

How It Works

The before_save callback in Rails acts like a checkpoint that runs right before your data is saved to the database. Imagine you are filling out a form and before submitting it, you double-check or adjust some answers. This callback lets you do that automatically in your code.

When you save a record, Rails looks for any before_save methods you defined and runs them first. If any of these methods throw an exception or return false (in Rails 5 and earlier), the save is stopped. This helps keep your data clean and consistent without extra manual steps.

💻

Example

This example shows a User model that automatically downcases the email before saving it to the database.

ruby
class User < ApplicationRecord
  before_save :downcase_email

  private

  def downcase_email
    self.email = email.downcase
  end
end

# Usage
user = User.new(email: 'EXAMPLE@MAIL.COM')
user.save
puts user.email
Output
example@mail.com
🎯

When to Use

Use before_save when you want to make sure some changes or checks happen every time before data is saved. For example:

  • Normalize or format data like emails or names
  • Set default values or timestamps
  • Validate or modify attributes that depend on others
  • Log or track changes before saving

This callback is helpful when you want to keep your database clean and avoid repeating code in many places.

Key Points

  • before_save runs before both creating and updating a record.
  • If it returns false (Rails 5 and earlier) or throws an exception, the save is canceled.
  • It is useful for automatic data cleanup or setting values.
  • It runs inside the model, keeping logic organized.

Key Takeaways

before_save runs just before saving a record to the database.
It lets you modify or check data automatically before saving.
Returning false in a before_save callback stops the save (in Rails 5 and earlier).
Use it to keep data clean and consistent without extra manual steps.
It works for both new records and updates.