Blog Ruby Maths

Ruby Scopes

Ruby scopes are special active record methods to run database queries. Scopes enables us to define reusable query fragments which can then be chained together to define complex and expressive queries.

Scopes are cleaner in code because of their syntax. Scopes are used exactly for one thing, so we know what it means when we see one.

Scopes are not mixed with other methods, so they are easier to see.


  class Awesome < ApplicationRecord
      scope :tada, ~> { where(like_grapes: true) }
  end

They are cleaner than class methods.

To define a simple scope, we use the scope method inside the class, passing the query we would like to pass.

Back to Home Page