How to Use Scopes in Ruby on Rails

09/24/2021

Contents

In this article, you will learn how to use scopes in Ruby on Rails.

Using scopes in Ruby on Rails

In Ruby on Rails, scopes are used to define commonly used queries that can be applied to database models. They allow you to encapsulate a particular query as a method on the model class, making it easier to reuse and maintain.

Here are the steps to use scopes in Ruby on Rails:

Define a scope on a model

Scopes are defined using the scope method on a model. The scope method takes a block that returns an ActiveRecord query. For example, if you want to define a scope that returns all active users, you would define it like this:

class User < ApplicationRecord
  scope :active, -> { where(active: true) }
end

Use a scope

To use a scope, you simply call the method on the model class. For example, to get all active users, you would call the active method on the User class:

users = User.active

Chain scopes

You can chain scopes together to build more complex queries. For example, if you want to get all active users who have signed up in the last month, you could define a scope like this:

class User < ApplicationRecord
  scope :active, -> { where(active: true) }
  scope :signed_up_last_month, -> { where(created_at: 1.month.ago..Time.current) }
end

And then chain the scopes together like this:

users = User.active.signed_up_last_month

Pass arguments to scopes

You can pass arguments to scopes to make them more flexible. For example, if you want to define a scope that returns users with a certain role, you could define it like this:

class User < ApplicationRecord
  scope :with_role, ->(role) { where(role: role) }
end

And then pass the role as an argument:

users = User.with_role('admin')