A Beginner's Guide to Ruby on Rails Callbacks
Tags: ruby, rails, beginners
Published: 2023-11-10 15:13:33

---
title: A Beginner's Guide to Ruby on Rails Callbacks
published: true
date: 2023-11-07 12:51:44 UTC
tags: ruby, rails, beginner
canonical_url: https://web-crunch.com/posts/a-beginner-s-guide-to-ruby-on-rails-callbacks
---

![A Beginner's Guide to Ruby on Rails Callbacks](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pa6aqrrfsp84ijj0st98.jpg)

Love them or hate them, I find callbacks are like strapping a supercharger to Ruby on Rails apps. With sprinklings of these throughout your app, you can automate quite a bit and save some keystrokes.

This article briefly introduces callbacks, how they get utilized, and why or why not you should leverage them in your own apps.

**What Are Callbacks, Anyway?**

Think of Callbacks as little helpers that do specific tasks at different points during the lifecycle of your Rails objects. They're like tiny assistants, making your code more organized and efficient.

**Why Use Callbacks?**

Callbacks help you automate repetitive tasks in your app. Let's say you want to update a timestamp when a user's profile gets modified. Instead of writing that code all over the place, you can use a Callback to do it automatically.

**The Four Types of Callbacks**

Rails has four main types of Callbacks:

1. `before_validation`: Runs before validation so you can make sure your data is in good shape.
2. `before_save`: This happens just before the record is saved, making it great for final adjustments.
3. `after_save`: This runs right after the record is saved for things like sending notifications.
4. `after_commit`: This occurs after the transaction is committed, ensuring data integrity.

Want to explore? [There are more](https://guides.rubyonrails.org/active_record_callbacks.html#available-callbacks)!

## **Example**

Let's create a simple scenario. You have a `Post` model and want to update the `published_at` timestamp whenever you save a post.

```ruby
class Post < ApplicationRecord
  before_save :update_published_at

  def update_published_at
    self.published_at = Time.now if published?
  end
end
```

In this example, we use the `before_save` callback to update the `published_at` timestamp when a post is saved. Easy peasy, right?

Before ActiveRecord callbacks, you would usually need to do this in a controller in a messy way.

Callbacks allow you to extract some of this work into an automated function in the model layer.

Callbacks, of course, can happen [inside controllers](https://api.rubyonrails.org/classes/AbstractController/Callbacks.html), too, but there's a common convention in the community to use "fat" models and "skinny" controllers, so I think this is the path most choose as a result.

## My pros and cons list for Ruby on Rails callbacks

There are plenty of reasons to leverage callbacks, but many other reasons to opt out of using them. Below is a list of pros and cons to help you decide their usefulness.

### Pros

1. **Simplifies Code** : Callbacks can help simplify your code by allowing you to encapsulate specific actions within the model, making it more organized and easier to read.
2. **Automates Repetitive Tasks** : They are excellent for automating repetitive tasks, like updating timestamps, sending notifications, or performing validations before saving a record.
3. **Maintains Data Integrity** : Callbacks ensure that related actions are carried out consistently, maintaining the integrity of your data. For example, you can guarantee that associated records are continuously updated correctly.
4. **Modular and Reusable** : Callbacks promote modularity and reusability. You can define callbacks in one place and use them across multiple models, reducing redundancy in your code.
5. **Separation of Concerns** : They allow you to separate different concerns within your model. For example, you can use `before_save` for data validation and `after_save` to send notifications, keeping each responsibility organized.
6. **Easy to Implement** : Callbacks are relatively easy to implement, making them accessible to developers of all levels, including beginners.
7. **Flexibility** : Rails provides multiple callback types (before and after actions), allowing you to choose the most suitable one for a particular task. This flexibility can be a significant advantage in different scenarios.
8. **Time-Saving** : By automating routine tasks, callbacks save you time and effort, enabling you to focus on more complex aspects of your application.
9. **Consistency** : Callbacks ensure that specific actions occur consistently whenever a particular event occurs, such as record creation or update.
10. **Real-Time Reactions** : You can use callbacks to create real-time reactions to events in your application, like triggering notifications or alerts as soon as something happens.

### Cons

1. **Complexity** : Callbacks can make the flow of your code less obvious. When you have many callbacks scattered throughout your models, it can be challenging to follow the logic of your application, especially for newcomers. This complexity can lead to debugging nightmares.
2. **Hidden Behavior** : Callbacks can create "magic" behavior in your code. Actions happen behind the scenes, and what's happening might only sometimes be clear. This hidden behavior can make it harder to predict how changes to your code might affect the application.
3. **Ordering Issues** : The order in which callbacks are defined can be crucial. If not handled properly, it can lead to unexpected results. Sometimes, getting the correct order for callbacks can be tricky.
4. **Testing Challenges** : Writing tests for code that heavily relies on callbacks can be more complicated. Make sure that the callbacks trigger as expected, which can add extra work to your testing process.
5. **Maintenance and Debugging** : Managing and debugging callbacks can become a headache as your application grows. Finding where a specific callback is defined or what it's doing can be challenging.
6. **Alternative Approaches** : Some developers prefer to use alternative patterns like service objects or service classes to handle specific actions instead of callbacks. These patterns can offer more explicit and testable control over your code.

### Wrapping up

Callbacks are a fantastic tool in Ruby on Rails that can make your coding life much more comfortable, especially when you're just starting. They keep your code organized and help you automate repetitive tasks.

Ample use of callbacks is great, but consider the consequences outlined in this article. Sometimes, they can be too “magical,” so some community members often opt out of using them or at least overusing them.

* * *

### Continue reading

- [Ruby on Rails for Beginners: A Comprehensive Overview and Guide to Developer Growth](https://dev.to/justalever/ruby-on-rails-for-beginners-a-comprehensive-overview-and-guide-to-developer-growth-l8a)
- [Understanding ActiveRecord callbacks](https://dev.to/justalever/understanding-active-record-callbacks-2l2g)
- [Understanding Ruby on Rails ActiveRecord Validations](https://web-crunch.com/posts/understanding-ruby-on-rails-activerecord-validations)
- Premium course: [Hello Rails](https://hellorails.io)