0
0
Ruby on Railsframework~30 mins

Dependent destroy and nullify in Ruby on Rails - Mini Project: Build & Apply

Choose your learning style9 modes available
Dependent destroy and nullify in Rails associations
📖 Scenario: You are building a simple blog application where each Author can have many Posts. When an author is deleted, you want to control what happens to their posts.
🎯 Goal: Learn how to use dependent: :destroy and dependent: :nullify in Rails models to manage associated records when the parent record is deleted.
📋 What You'll Learn
Create an Author model with a has_many :posts association
Create a Post model with a belongs_to :author association
Add dependent: :destroy to the Author model association
Add dependent: :nullify to the Author model association
Understand the difference in behavior when deleting an author
💡 Why This Matters
🌍 Real World
Managing data relationships in web apps is common. Knowing how to control what happens to related data when deleting records helps keep data clean and consistent.
💼 Career
Rails developers often work with associations and must understand dependent options to avoid data loss or orphaned records.
Progress0 / 4 steps
1
Create Author and Post models with associations
Create a Rails model called Author with a has_many :posts association and a Rails model called Post with a belongs_to :author association.
Ruby on Rails
Need a hint?

Use has_many :posts inside the Author model and belongs_to :author inside the Post model.

2
Add dependent: :destroy to Author's posts association
Modify the Author model to add dependent: :destroy to the has_many :posts association to delete posts when an author is deleted.
Ruby on Rails
Need a hint?

Add dependent: :destroy inside the has_many :posts association in the Author model.

3
Change dependent option to :nullify
Change the dependent option in the Author model's has_many :posts association from :destroy to :nullify so posts are not deleted but their author_id is set to NULL when an author is deleted.
Ruby on Rails
Need a hint?

Replace dependent: :destroy with dependent: :nullify in the has_many :posts association.

4
Add optional: true to Post's belongs_to association
Modify the Post model's belongs_to :author association to add optional: true so posts can exist without an author after nullification.
Ruby on Rails
Need a hint?

Add optional: true inside the belongs_to :author association in the Post model.