Photo by Sharon McCutcheon on Unsplash

A ‘Scope’ful of Syntactic Sugar

Ruby on Rails — ActiveRecord Scopes

Jamie Berrier
2 min readJan 9, 2021

--

In computer science, syntactic sugar is syntax within a programming language that is designed to make things easier to read or to express. It makes the language “sweeter” for human use: things can be expressed more clearly, more concisely, or in an alternative style that some may prefer. (Wikipedia)

Scopes are syntactic sugar for defining class methods in Rails.

ActiveRecord scopes are custom queries defined inside a model and are available as class methods. Scopes take 2 arguments:

  1. a name
  2. a lambda

But what is a lambda?

Does anyone else immediately think of ‘Revenge of the Nerds’? The Lambda Lambda Lambda fraternity. No? Just me?

A lambda is an object that represents a block and has method-like behavior. By wrapping the logic and data in a lambda, a block can be manipulated as an object (e.g. chained). In scopes, the lambda:

  • re-evaluates the scope each time it is called and guarantees it will return an ActiveRecord::Relation object
  • can take arguments and utilize conditionals

Let’s scope it out!

For this example, we have 2 models:

  1. aDanceStudio model that has_many :dancers
  2. a Dancer model that belongs_to :dance_studio, with a boolean field current_dancer

To get all of the current dancers at a dance studio, we could define a class method in Dancer:

But, a spoonful of syntactic sugar helps define a scope:

The literal lambda operator, aka ‘stabby lambda’ syntax, can also be used:

With either syntax, the scope is called as if it were a class method:

Dancer.current_dancers(@dance_studio)

Scopes are also available to has_many associations!

Since the DanceStudio model has_many :dancers, the scope can be sweetened further to:

Now, the method call is:

@dance_studio.dancers.current_dancers
In a most delightful way!

📚 Resources 👀

Rails Guides — Active Record Query Interface — Scopes

Ruby on Rails API — ActiveRecord — Scoping

How to Use Lambdas in Ruby

Sign up to discover human stories that deepen your understanding of the world.

--

--

No responses yet

Write a response