0
0
Ruby on Railsframework~5 mins

Association callbacks in Ruby on Rails

Choose your learning style9 modes available
Introduction

Association callbacks let you run code automatically when related records change. This helps keep your data connected and actions in sync.

When you want to run code right after adding or removing an associated record.
When you need to update or clean up related data automatically.
When you want to trigger notifications or logging when associations change.
When you want to enforce rules or validations on related records during save or destroy.
When you want to keep counters or caches updated based on association changes.
Syntax
Ruby on Rails
has_many :comments, after_add: :method_name, after_remove: :method_name

# method_name is a symbol for a method in the model
You can use after_add and after_remove callbacks on associations like has_many or has_and_belongs_to_many.
The callback method receives the associated record as an argument.
Examples
This runs notify_comment_added after a comment is added to a post.
Ruby on Rails
class Post < ApplicationRecord
  has_many :comments, after_add: :notify_comment_added

  def notify_comment_added(comment)
    puts "New comment added: #{comment.body}"
  end
end
This runs log_role_removed after a role is removed from a user.
Ruby on Rails
class User < ApplicationRecord
  has_many :roles, after_remove: :log_role_removed

  def log_role_removed(role)
    puts "Role removed: #{role.name}"
  end
end
Sample Program

This example shows an Author model with has_many :books association. It uses after_add and after_remove callbacks to print messages when books are added or removed.

When you add books to the author's collection, it announces the new book. When you remove a book, it announces the removal.

Ruby on Rails
class Author < ApplicationRecord
  has_many :books, after_add: :announce_new_book, after_remove: :announce_removed_book

  def announce_new_book(book)
    puts "Author #{name} added a new book titled '#{book.title}'."
  end

  def announce_removed_book(book)
    puts "Author #{name} removed the book titled '#{book.title}'."
  end
end

class Book < ApplicationRecord
  belongs_to :author
end

# Simulate adding and removing books
author = Author.new(name: "Alice")
book1 = Book.new(title: "Ruby Basics")
book2 = Book.new(title: "Rails Advanced")

# Add books
author.books << book1
author.books << book2

# Remove a book
author.books.delete(book1)
OutputSuccess
Important Notes

Callbacks run only when you modify the association collection, not when you save the parent or child alone.

Use callbacks carefully to avoid unexpected side effects or performance issues.

Summary

Association callbacks run code automatically when related records are added or removed.

Use after_add and after_remove options on associations like has_many.

They help keep related data and actions in sync without extra manual code.