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.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay