Association callbacks let you run code automatically when related records change. This helps keep your data connected and actions in sync.
Association callbacks in Ruby on Rails
has_many :comments, after_add: :method_name, after_remove: :method_name
# method_name is a symbol for a method in the modelafter_add and after_remove callbacks on associations like has_many or has_and_belongs_to_many.notify_comment_added after a comment is added to a post.class Post < ApplicationRecord has_many :comments, after_add: :notify_comment_added def notify_comment_added(comment) puts "New comment added: #{comment.body}" end end
log_role_removed after a role is removed from a user.class User < ApplicationRecord has_many :roles, after_remove: :log_role_removed def log_role_removed(role) puts "Role removed: #{role.name}" end end
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.
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)
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.
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.
Practice
after_add and after_remove callbacks in Rails associations?Solution
Step 1: Understand association callbacks
Rails providesafter_addandafter_removecallbacks to trigger code when associated records change.Step 2: Identify their purpose
These callbacks run automatically when you add or remove related records, helping keep data in sync.Final Answer:
To run code automatically when related records are added or removed -> Option DQuick Check:
Association callbacks = automatic code on add/remove [OK]
- Confusing callbacks with validations
- Thinking callbacks preload data
- Assuming callbacks define indexes
after_add callback to a has_many association named comments in a Rails model?Solution
Step 1: Recall correct hash syntax for options
Rails uses symbol keys with colon and value pairs likeafter_add: :method_name.Step 2: Match syntax to association
The correct syntax ishas_many :comments, after_add: :notify_comment_added.Final Answer:
has_many :comments, after_add: :notify_comment_added -> Option AQuick Check:
Use colon syntax for options in associations [OK]
- Using hash rocket => instead of colon :
- Trying to define callback inside block
- Using wrong option name like callback_after_add
comment is added to a Post?
class Post < ApplicationRecord
has_many :comments, after_add: :log_comment_added
def log_comment_added(comment)
puts "Comment added: #{comment.body}"
end
end
post = Post.new
post.comments << Comment.new(body: 'Nice post!')Solution
Step 1: Understand after_add callback behavior
Theafter_addcallback callslog_comment_addedwith the new comment when added.Step 2: Check the method output
The method prints "Comment added: " plus the comment's body, which is "Nice post!".Final Answer:
Comment added: Nice post! -> Option BQuick Check:
after_add calls method with new record [OK]
- Expecting no output
- Thinking callback is not triggered on << operator
- Assuming method is missing error
after_remove callback:
class User < ApplicationRecord
has_many :posts, after_remove: :notify_post_removed
def notify_post_removed
puts 'Post removed'
end
endSolution
Step 1: Check callback method signature
Callbacks likeafter_removereceive the removed record as an argument.Step 2: Compare method definition
The methodnotify_post_removedhas no parameters, so it will cause an error.Final Answer:
The callback method must accept the removed record as an argument -> Option AQuick Check:
Callback methods need removed record argument [OK]
- Defining callback method without parameters
- Using invalid callback option name
- Thinking method visibility causes error
Article model using has_many :tags. You want to update a counter on Article each time tags change. Which is the best way to implement this using association callbacks?Solution
Step 1: Understand the goal
You want to update a counter automatically when tags are added or removed.Step 2: Choose appropriate callback
after_addandafter_removeonhas_many :tagsrun code exactly when tags change.Step 3: Compare other options
Overriding setter or usingbefore_saveis less direct and can miss changes; manual calls are error-prone.Final Answer:
Use after_add and after_remove callbacks on has_many :tags to update the counter method -> Option CQuick Check:
Use association callbacks for automatic related record updates [OK]
- Overriding setter unnecessarily
- Using before_save which may miss association changes
- Forgetting to automate updates
Ready to prove it?
Pass the test and this pattern moves unknown
