0
0
Ruby on Railsframework~5 mins

Dependent destroy and nullify in Ruby on Rails

Choose your learning style9 modes available
Introduction

Dependent destroy and nullify help manage related data automatically when you delete a record. They keep your database clean and avoid broken links.

When deleting a user should also delete all their posts automatically.
When removing a category should set the category_id in products to null instead of deleting products.
When you want to keep related records but remove their connection after deleting the parent.
When you want to avoid orphaned records that point to deleted data.
When you want to ensure data integrity without manual cleanup.
Syntax
Ruby on Rails
has_many :associated_records, dependent: :destroy
has_many :associated_records, dependent: :nullify

dependent: :destroy deletes all associated records when the parent is deleted.

dependent: :nullify sets the foreign key in associated records to null instead of deleting them.

Examples
When a user is deleted, all their posts are deleted too.
Ruby on Rails
class User < ApplicationRecord
  has_many :posts, dependent: :destroy
end
When a category is deleted, the category_id in products is set to null, keeping the products.
Ruby on Rails
class Category < ApplicationRecord
  has_many :products, dependent: :nullify
end
Sample Program

This example shows a user with two posts. When the user is deleted, all their posts are deleted automatically because of dependent: :destroy.

Ruby on Rails
class User < ApplicationRecord
  has_many :posts, dependent: :destroy
end

class Post < ApplicationRecord
  belongs_to :user
end

# In Rails console or test
user = User.create(name: "Alice")
post1 = user.posts.create(title: "Hello")
post2 = user.posts.create(title: "World")

puts Post.count # => 2
user.destroy
puts Post.count # => 0
OutputSuccess
Important Notes

Use dependent: :destroy carefully because it deletes data permanently.

dependent: :nullify keeps data but removes the link, so make sure your app handles null foreign keys.

These options help keep your database consistent without extra code.

Summary

dependent: :destroy deletes associated records when the parent is deleted.

dependent: :nullify sets foreign keys to null instead of deleting associated records.

They help manage related data automatically and keep your database clean.