Performance: Dependent destroy and nullify
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 |
dependent: :destroy do in a Rails model association?dependent option in Rails associations controls what happens to associated records when the parent is deleted.:destroy:destroy option deletes all associated records automatically when the parent record is deleted.:destroy, :delete_all, and :nullify as valid dependent options.dependent: :nullify sets the foreign keys of associated records to null instead of deleting them.class Post < ApplicationRecord has_many :comments, dependent: :nullify end class Comment < ApplicationRecord belongs_to :post, optional: true end
dependent: :nullify option means when a post is deleted, associated comments' foreign keys (post_id) are set to null.post_idbelongs_to :post, optional: true allows comments to exist without a post, so setting post_id to null is valid.class User < ApplicationRecord has_many :posts, dependent: :nullify end class Post < ApplicationRecord belongs_to :user end
belongs_to :user by default requires user_id to be present (not null). Since it's not marked optional, nullifying user_id causes validation or DB errors.Library model with many Books. You want to delete a library and automatically delete all its books. But if a Book has Reviews, you want to keep the reviews but remove the book reference (set book_id to null). Which setup correctly achieves this?dependent: :destroy on has_many :books deletes all books when a library is deleted.dependent: :nullify on has_many :reviews keeps reviews but sets their book_id to null.belongs_to :book, optional: true in Review allows book_id to be null without errors.Pass the test and this pattern moves unknown