Rails default_scope is an ActiveRecord macro that allows you to set a default scope for all the operations on the model. This is useful to filter out records by default, such as soft deleted ones.
class User < ApplicationRecord
default_scope { where(deleted_at: nil) }
end
In this way, we can filter out soft deleted users from all queries.
User.all
# SELECT * FROM users WHERE deleted_at IS NULL
This is a powerful tool, but it can lead to unexpected behavior. If you Google it, you will find a lot of examples. This is what I found out the hard way. On a Friday. Afternoon.