DEV Community

Kartikey Tanna
Kartikey Tanna

Posted on

The surpising behaviour of Rails' default_scope method

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 Bookwith an attribute approved.

This is how the column is defined in the migration:

t.boolean :approved, null: false, default: false
Enter fullscreen mode Exit fullscreen mode

This is how the default_scope method is declared in the model:

class Book
  default_scope -> { where(approved: true) }
end
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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)