Scope in RoR (Ruby on Rails) is commonly used when you have one query repeated various times in your project, so you can use a scope to reduce the duplicate code amount and centralize future maintenance. Scopes works like a class method, and in its definition, you can use any Query Methods, like where, includes, order. The query results in an ActiveRecord::Relation or nil.

For example, I am working on a shipment system as a project and want to query which transport models have an active status in the system. So I can use scope like this:

class TransportModel < ActiveRecord
 scope :active, -> { where(status: 'active') }
end

You can write the same query using class methods like this:

class TransportModel < ActiveRecord
 def self.active
  where(status: 'active')
 end
end

So, why choose to use scope over a class method?

For some reasons:

  • Scopes result in cleaner code because of their syntax;
  • Scopes are used for precisely one thing, so you know what you get when you see one.

The article How to Use Scopes in Ruby on Rails teaches how to use scopes in ROR if you are starting to use it.

But when should I use a class method instead of a scope? These are some reasons:

  • When the scope logic gets complicated;
  • When you want to mix Ruby with database code;
  • When you want to collect data from different places: your database, Redis, or an external API or service.