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:

1
2
3
# app/models/post.rb

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

Now hit the following scope:

1
Post.published

This will generate the following query:

1
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.

1
2
3
# app/models/post.rb

default_scope { where(is_published: true) }

Now get all the posts.

1
Post.all

This will generate the following query:

1
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!