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.

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more