Class Methods vs. Scopes in Rails

Image for post
Image for post
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:

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:

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:

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.

Written by

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store