What is after_create callback in Ruby on Rails: Explanation & Example
after_create callback is a method that runs automatically right after a new record is saved to the database for the first time. It lets you trigger extra actions immediately after creating an object, such as sending notifications or updating related data.How It Works
The after_create callback in Rails is like a little helper that runs right after a new record is saved to the database. Imagine you just planted a seed (created a record), and immediately after planting, you want to water it or put a label on it. This callback lets you do those extra tasks automatically.
When you call save on a new object, Rails first inserts the record into the database. Once that is successful, it runs any after_create methods you defined. This happens only once per object creation, not on updates.
This callback is part of Rails’ lifecycle hooks, which let you add custom behavior at different stages of saving or updating data.
Example
This example shows a User model that sends a welcome email right after a new user is created.
class User < ApplicationRecord after_create :send_welcome_email private def send_welcome_email puts "Welcome email sent to #{email}!" end end # Simulate creating a new user user = User.new(email: 'friend@example.com') user.save
When to Use
Use after_create when you want to run code only once, right after a new record is saved. This is useful for tasks like:
- Sending welcome emails or notifications
- Creating related records that depend on the new record’s ID
- Logging or auditing creation events
- Triggering background jobs that start after creation
It is not suitable for actions that should happen on every save or update; for those, use other callbacks like after_save or after_update.
Key Points
- Runs only once: after the record is first created in the database.
- Automatic trigger: no need to call it manually.
- Good for side effects: like sending emails or creating related data.
- Part of Active Record lifecycle callbacks.