0
0
Ruby on Railsframework~3 mins

Why Association callbacks in Ruby on Rails? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how to make your app update related data automatically without messy manual code!

The Scenario

Imagine you have a blog app where each post has many comments. You want to update a post's comment count every time a comment is added or removed.

Doing this manually means writing extra code everywhere you add or delete comments, like in controllers or services.

The Problem

Manually updating related data is easy to forget and leads to bugs. You might miss updating the count in some places, causing wrong numbers to show.

This scattered logic makes your code messy and hard to maintain.

The Solution

Association callbacks let you hook into the lifecycle of related objects automatically.

For example, when a comment is created or destroyed, Rails can run code to update the post's comment count without extra manual calls.

Before vs After
Before
def create_comment
  comment.save
  post.update(comment_count: post.comments.count)
end
After
has_many :comments, after_add: :update_comment_count, after_remove: :update_comment_count

def update_comment_count(comment)
  update(comment_count: comments.size)
end
What It Enables

This makes your app more reliable and your code cleaner by automating related updates.

Real Life Example

In an e-commerce app, when you add or remove items from a shopping cart, association callbacks can automatically update the cart's total price.

Key Takeaways

Manual updates of related data are error-prone and scattered.

Association callbacks automate running code when related objects change.

This leads to cleaner, more reliable, and easier-to-maintain code.