Named Scopes vs Default Scopes

This article will discuss two important concepts in Ruby on Rails - Named Scopes and Default Scopes. The main idea is to get results based on some condition.

Named Scopes

Let’s say we have a model named Post that has columns title, body and author and is_published with title, body and author as string and is_published as boolean.

Assume we want to get only those posts that are published. In app/models/post.rb:

# app/models/post.rb

scope :published, lambda { where(is_published: true) }

Now hit the following scope:

Post.published

This will generate the following query:

SELECT "posts".* FROM "posts" WHERE "posts"."is_published" = $1 LIMIT $2  [["is_published", true], ["LIMIT", 11]]

Default Scopes

There is another use case where we want only published posts even if we hit Post.all method. Here, default scopes come in.

In app/models/post.rb.

# app/models/post.rb

default_scope { where(is_published: true) }

Now get all the posts.

Post.all

This will generate the following query:

SELECT "posts".* FROM "posts" WHERE "posts"."is_published" = $1 LIMIT $2  [["is_published", true], ["LIMIT", 11]]

Now you know how to utilize Named Scopes and Default Scopes in your Ruby on Rails applications!