Performance: Dependent destroy and nullify
MEDIUM IMPACT
This concept affects database query performance and page load speed by controlling how associated records are handled when a parent record is deleted.
class User < ApplicationRecord has_many :posts, dependent: :nullify end # Deleting a user sets user_id to NULL in posts with a single UPDATE query
class User < ApplicationRecord has_many :posts, dependent: :destroy end # Deleting a user triggers DELETE queries for each post individually
| Pattern | Database Queries | Query Count | Server Response Impact | Verdict |
|---|---|---|---|---|
| dependent: :destroy | Multiple DELETE queries for each child | N+1 queries | High server processing time | [X] Bad |
| dependent: :nullify | Single UPDATE query to nullify foreign keys | 1 query | Lower server processing time | [OK] Good |