Rails Scopes: Create Faster, Cleaner Queries

Deloris Thompson
Deloris ThompsonWednesday, February 15, 2023
Rails Scopes: Create Faster, Cleaner Queries

With the use of scopes, a developer can create a fast query and add additional methods like pluck that would otherwise throw an error.

Why use Scopes?

Scopes allow a developer to create reusable code instead of a method in the controller. Scopes also return an ActiveRecord::Relation object, opening the door for combining multiple scopes.

Let's look at one example where scopes are better:

def member_ids member_emails = ['', '', ''] Account.where(email: member_emails) end

How to Create:

scopes are created inside a method. While not required, adding additional arguments is possible.


scope :name_for_method, →(arguments NOT required) {query is inserted here!}

# Grab all users with a certain role (roles is an array) scope :admin, { where('? = ANY(roles)', 'Admin') }

This will allow using the method globally for the class. A class in Ruby is a controller. It also has methods.


Or grab all accounts with a certain role. This is created inside the method file for your Ruby class.

def admin Account.admin.pluck(:id) end


Scopes provide cleaner code and remove the need for multiple class methods. They also allow combining multiple scopes and do not contain overly complicated logic.


Share this post


Related Posts:

Interested in working with us?

Give us some details about your project, and our team will be in touch with how we can help.

Get in Touch