Dependent destroy and nullify help manage related data automatically when you delete a record. They keep your database clean and avoid broken links.
Dependent destroy and nullify in 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.
class User < ApplicationRecord
has_many :posts, dependent: :destroy
endcategory_id in products is set to null, keeping the products.class Category < ApplicationRecord
has_many :products, dependent: :nullify
endThis example shows a user with two posts. When the user is deleted, all their posts are deleted automatically because of dependent: :destroy.
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
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.
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.