Class Methods vs. Scopes in Rails

Shaqqour
2 min readNov 7, 2020
Photo by Taras Shypka on Unsplash

Class methods and scopes are both methods. A method in Ruby is defined as a block that performs a specific task. For example, if you have a task of calculating the sum of two numbers, you would create a method that looks like this:

def sum(num1, num2)
return num1 + num2
end

This was a simple method. However, in Rails, the idea of methods is expanded to include three types of methods: Instance methods, Class methods, and Scope methods. This blog will explain the difference between Class methods and Scopes.

Class Methods

A class method is a method that is related to the class itself rather than an object that was created from that class. In another word, it is a method that returns data about (all or some) objects from that class. If you have a Student class, a class method would be a method that returns the number of students that was created from that class, or maybe a list of all students.
Let’s say you want a list of all ‘A’ students in your class to perform an action on these students, you would write a class method that first finds all ‘A’ students and then iterates over them to perform a specific action. Let’s write this class method using the where clause:

class Student
.
.
.
def self.award_a_students
Student.where("average > ?", 90).each do |student|
student.award = "$100"
end
end
end

It will become very repetitive if every time you want to perform an action to the same student to write the above where clause. Here comes the idea of Scopes in Rails.

Scope Methods

Scope method is as it sounds; it is a subset of a big collection. Think about our previous example where you have a big collection, all the students, a subset of this collection would be the ‘A’ students for instance. Rails offers an easy way to get a subset that matches our condition, ‘A students’, from a collection. Let’s write the previous example using scope:

class Student
scope :a_students, -> { where("average > ?", 90) }
.
.
.
def self.award_a_students
Student.a_students.each do |student|
student.award = "$100"
end
end
end

You see how it was easy to get all ‘A’ students when I needed them in my award method! This is just a very simple example of how to use Scopes in Rails. I will explain in detail in one of my next blogs why to use Scopes in your application instead of a simple class method.

If you have anything you would like to add, please comment below.

--

--

Shaqqour

Full stack software engineer. Passionate about making people’s lives better and easier through programming. LinkedIn.com/in/shaqqour