0
0
RailsHow-ToBeginner · 3 min read

How to Use Dependent Destroy in Rails for Automatic Child Deletion

In Rails, use dependent: :destroy in a model's association to automatically delete associated child records when the parent record is destroyed. This ensures data integrity by removing related objects without manual cleanup.
📐

Syntax

The dependent: :destroy option is added to an association in a Rails model. It tells Rails to delete all associated child records when the parent record is deleted.

  • has_many :children, dependent: :destroy - deletes all children when parent is destroyed.
  • has_one :child, dependent: :destroy - deletes the single child when parent is destroyed.
ruby
class Parent < ApplicationRecord
  has_many :children, dependent: :destroy
end
💻

Example

This example shows a Parent model with many Child models. When a parent is deleted, all its children are automatically deleted too.

ruby
class Parent < ApplicationRecord
  has_many :children, dependent: :destroy
end

class Child < ApplicationRecord
  belongs_to :parent
end

# Usage in Rails console or controller
parent = Parent.create(name: "Mom")
child1 = parent.children.create(name: "Child 1")
child2 = parent.children.create(name: "Child 2")

parent.destroy

# After destroy, child1 and child2 are also deleted from the database.
Output
Parent.count # => 0 Child.count # => 0
⚠️

Common Pitfalls

Common mistakes include:

  • Using dependent: :delete_all instead of :destroy, which skips callbacks on children.
  • Not setting dependent: :destroy and leaving orphaned child records.
  • Forgetting to add belongs_to in child models, which can cause association errors.
ruby
class Parent < ApplicationRecord
  # Wrong: skips callbacks on children
  has_many :children, dependent: :delete_all
end

# Correct:
class Parent < ApplicationRecord
  has_many :children, dependent: :destroy
end
📊

Quick Reference

OptionEffect
dependent: :destroyDeletes associated records and runs their callbacks
dependent: :delete_allDeletes associated records directly in database, skips callbacks
dependent: :nullifySets foreign keys to NULL instead of deleting
dependent: :restrict_with_exceptionPrevents deletion if associated records exist
dependent: :restrict_with_errorAdds error on parent if associated records exist

Key Takeaways

Add dependent: :destroy to associations to auto-delete child records with the parent.
dependent: :destroy runs callbacks on child records, unlike :delete_all.
Always define belongs_to in child models for proper association behavior.
Use dependent options carefully to maintain data integrity and avoid orphan records.
Test deletions to confirm associated records are removed as expected.