DEV Community

Cover image for How to Use Scopes in Ruby on Rails
Ronak Bhatt for Main Street

Posted on • Updated on

How to Use Scopes in Ruby on Rails

Scopes are custom queries that you define inside your Rails models with the scope method.

Every scope takes two arguments:

A name, which you use to call this scope in your code
A lambda, which implements the query

It looks like this:

class User < ApplicationRecord
  scope :active, -> { where("status: 0") }
end
Enter fullscreen mode Exit fullscreen mode

As a result of calling a scope, you’ll get an ActiveRecord::Relation object.

Which means you can chain & combine scopes!

Example:

User.active
Enter fullscreen mode Exit fullscreen mode

When To Use Scopes?

Let’s see an example.

def index
  @books = Book.where("LENGTH(title) > 20")
end 
Enter fullscreen mode Exit fullscreen mode

This is an index controller action that wants to display books with titles longer than 20 characters.

It’s fine.

But if you want to use this query in other places, you’re going to have duplicated code.

Duplicated code makes your project harder to maintain.

Let’s move this query into a scope.

Like this:

class Book
  scope :with_long_title, -> { where("LENGTH(title) > 20") }
end
Enter fullscreen mode Exit fullscreen mode

Now our controller action looks like this:

def index
  @books = Book.with_long_title
end
Enter fullscreen mode Exit fullscreen mode

Summary
Good job! As a result of reading this article, you’ve learned how to use Rails scopes in the most effective way.

Don’t forget to put this new knowledge into practice so you can remember how it works.

Thanks for reading. 🙂

I’d love to hear thoughts or comments around this. Feel free to email me at ronakabhattrz@gmail.com or hit me up on twitter, @ronakabhattrz.

Top comments (3)

Collapse
 
bizzibody profile image
Ian bradbury

Scopes are great but it's worth highlighting, when a scope returns nil, all records are returned. This can cause unexpected consequences - especially when the scope is being used to limit access to data.

Collapse
 
eminarium profile image
Merdan Durdyyev

Exactly. Hey Ronak, great coincidence. I was working on something last night. It's good I came across your post. I can scope 'archived'/'inactive' menus, categories and items in my project. Thank you ...

Collapse
 
ronakabhattrz profile image
Ronak Bhatt

Welcome 😃