Consider a Rails model Author has_many books with dependent: :destroy. What happens when an Author is destroyed?
class Author < ApplicationRecord has_many :books, dependent: :destroy end class Book < ApplicationRecord belongs_to :author before_destroy :log_destroy def log_destroy puts "Destroying book #{id}" end end # In console: author = Author.find(1) author.destroy
Think about the order of callbacks and what dependent: :destroy means.
With dependent: :destroy, Rails destroys all associated records by calling their destroy method, which triggers callbacks like before_destroy. This happens before the parent record is destroyed.
Given a has_many :comments, after_add: :notify_addition association, when does the notify_addition method get called?
class Post < ApplicationRecord has_many :comments, after_add: :notify_addition def notify_addition(comment) puts "Added comment #{comment.id}" end end post = Post.find(1) comment = Comment.new(content: 'Nice post!') post.comments << comment
Consider when the callback triggers relative to adding objects to the association.
The after_add callback runs immediately after an object is added to the association collection in memory, even before saving it to the database.
Choose the correct syntax to define a before_remove callback on a has_many :tags association that calls log_removal.
class Article < ApplicationRecord has_many :tags, ??? def log_removal(tag) puts "Removing tag #{tag.id}" end end
Look for the correct Ruby hash syntax for options in associations.
The correct syntax uses a symbol key and symbol value with a colon: before_remove: :log_removal.
Given this code:
post.comments << comment post.update(comments: post.comments + [new_comment])
The after_add callback on comments does not run for new_comment. Why?
Think about how callbacks are triggered when modifying associations directly vs. via update.
Using update with an array replaces the association in bulk and does not trigger after_add callbacks, which only run when adding objects directly to the association collection.
In a has_many :items, before_add: :check_limit, after_remove: :log_removal association, what is the combined effect of these callbacks?
Consider the timing and purpose of before_add and after_remove callbacks.
before_add runs before an object is added to the association, allowing checks or prevention. after_remove runs after an object is removed, useful for logging or cleanup.