Discover how to make your app handle extra tasks automatically without messy code!
Why Callbacks overview in Ruby on Rails? - Purpose & Use Cases
Imagine you have a web app where you must send a welcome email every time a new user signs up. You write code to save the user, then separately write code to send the email right after. But what if you forget to send the email in some places? Or you add more steps later, like logging or notifications?
Manually adding extra steps after saving or updating data is easy to forget and leads to repeated code everywhere. It becomes messy, hard to maintain, and bugs sneak in when you miss a step or change the order.
Rails callbacks let you hook into the lifecycle of your data objects. You can automatically run code before or after events like saving, updating, or deleting. This keeps your extra steps organized, consistent, and easy to manage.
user.save send_welcome_email(user)
class User < ApplicationRecord after_create :send_welcome_email def send_welcome_email # email logic here end end
Callbacks enable automatic, reliable execution of related tasks tied to data changes without cluttering your main code.
When a user deletes their account, callbacks can automatically clean up related data like posts or comments, ensuring nothing is left behind.
Manual extra steps after data changes are error-prone and repetitive.
Callbacks run code automatically at key points in data lifecycle.
This keeps your app clean, consistent, and easier to maintain.
Practice
Solution
Step 1: Understand what callbacks do
Callbacks are hooks that run code automatically during certain model events like saving or deleting.Step 2: Identify the correct purpose
Callbacks help automate tasks at specific points in a model's lifecycle, not manual calls or styling.Final Answer:
To run code automatically at specific points in a model's life -> Option AQuick Check:
Callbacks = automatic code run [OK]
- Confusing callbacks with controller methods
- Thinking callbacks style views
- Mixing callbacks with database migrations
Solution
Step 1: Recall callback syntax
Rails usesbefore_save :method_nameto run a method before saving a record.Step 2: Check other options
after_saveruns after saving,on_saveis invalid, and the block syntax is incorrect here.Final Answer:
before_save :method_name -> Option DQuick Check:
before_save syntax = before_save :method_name [OK]
- Using after_save instead of before_save
- Trying to use on_save which doesn't exist
- Incorrect block syntax for callbacks
class User < ApplicationRecord
before_create :set_default_role
def set_default_role
self.role ||= 'guest'
end
endWhat will be the role of a new User if none is set before saving?
Solution
Step 1: Understand before_create callback
Thebefore_createcallback runs the methodset_default_rolebefore the record is created in the database.Step 2: Analyze set_default_role method
The method setsself.roleto 'guest' only if it is currently nil or falsey (using ||=).Final Answer:
'guest' -> Option AQuick Check:
before_create sets role to 'guest' if none set [OK]
- Assuming role stays nil if not set
- Confusing before_create with after_create
- Thinking it raises an error without role
class Post < ApplicationRecord
before_save :check_title
def check_title
if title.blank?
errors.add(:title, "can't be blank")
throw :abort
end
end
endSolution
Step 1: Review callback usage
Thebefore_savecallback runscheck_titlebefore saving.Step 2: Check error handling
Adding errors and usingthrow :abortis the correct way to stop saving if validation fails.Final Answer:
No error, this is correct usage -> Option BQuick Check:
throw :abort stops save correctly [OK]
- Thinking throw :abort is invalid
- Believing errors.add needs a different method
- Assuming callback methods must be private
log_update only after a record is updated but not created. Which callback should you use?Solution
Step 1: Understand callback timing
after_saveruns after both create and update, butafter_updateruns only after updates.Step 2: Choose callback for updates only
Since you want to runlog_updateonly after updates,after_updateis the correct choice.Final Answer:
after_update -> Option CQuick Check:
after_update runs only after updates [OK]
- Using after_save which runs on create too
- Choosing before_update which runs before update
- Confusing before_save with after_update
Ready to prove it?
Pass the test and this pattern moves unknown
