It is very convinient to declare default_scope
in the Rails models. Specially for something like deleted_at
. But it has an interesting side effect that has to be kept in mind.
Let's take an example model Book
with an attribute approved
.
This is how the column is defined in the migration:
t.boolean :approved, null: false, default: false
This is how the default_scope
method is declared in the model:
class Book
default_scope -> { where(approved: true) }
end
Whenever a new record is created, the approved
is going to be true
for the record even though the migration has the default
value set as false
. Let's see it in action:
book = Book.new
book.approved # true
To conclude, the default_scope
overrides the default value set at the migration level. That has to be kept in mind while declaring default_scope
in a model.
Top comments (0)