Author that has_many :books, dependent: :destroy. What happens to the associated books when an Author is deleted?class Author < ApplicationRecord has_many :books, dependent: :destroy end class Book < ApplicationRecord belongs_to :author end # In Rails console: author = Author.find(1) author.destroy
Using dependent: :destroy means Rails will automatically delete all associated child records when the parent is destroyed. So, all books linked to the author are deleted from the database.
Category that has_many :products, dependent: :nullify, what happens to the products when a Category is destroyed?class Category < ApplicationRecord has_many :products, dependent: :nullify end class Product < ApplicationRecord belongs_to :category, optional: true end # In Rails console: category = Category.find(1) category.destroy
Using dependent: :nullify means Rails will set the foreign key (category_id) to NULL on all associated products when the category is destroyed. The products remain in the database but are no longer linked to the deleted category.
Comment with a self-referential association:has_many :replies, class_name: 'Comment', foreign_key: 'parent_id', dependent: :destroyand
belongs_to :parent, class_name: 'Comment', optional: true.Destroying a comment with replies causes a
SystemStackError: stack level too deep. Why?class Comment < ApplicationRecord has_many :replies, class_name: 'Comment', foreign_key: 'parent_id', dependent: :destroy belongs_to :parent, class_name: 'Comment', optional: true end comment = Comment.find(1) comment.destroy
The dependent: :destroy option causes Rails to destroy all replies recursively. Since replies also have dependent: :destroy on their replies, this can cause infinite recursion if a reply's parent is destroyed again during the process, leading to a stack overflow error.
has_many association where deleting the parent sets the child's foreign key to NULL. Which code is correct?The correct option is dependent: :nullify. The other options are invalid and will cause errors.
class Post < ApplicationRecord
has_many :comments, dependent: :destroy
endclass Comment < ApplicationRecord
belongs_to :post
before_destroy { puts "Destroying comment #{id}" }
endWhen
post.destroy is called, what is the output and final state of comments?post = Post.find(1)
post.destroyWhen dependent: :destroy is used, Rails calls destroy on each child record, triggering callbacks like before_destroy. Then the child records are deleted from the database.