A ‘Scope’ful of Syntactic Sugar
Ruby on Rails — ActiveRecord Scopes
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:
- a name
- 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:
- a
DanceStudio
model thathas_many :dancers
- a
Dancer
model thatbelongs_to :dance_studio
, with a boolean fieldcurrent_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
📚 Resources 👀
Rails Guides — Active Record Query Interface — Scopes