Using Scopes in RoR

Abstract: Scopes Can Effectively Create a Database within Your Database

David Hunt
When Code Explodes!

--

Why Scopes are Awesome

As the subtitle implies, I like to conceptualize the purpose of queries, especially scopes, as creating subsets of data, or a tiny database. A scope allows you to specify commonly used queries which can be referenced as method calls. Here’s an example.

Above, we’re creating a scope within an application that tracks wildfires throughout the U.S. Our scope allows us to easily grab all of the fires currently burning in our database.

Step 1: Create the scope

We define the scope itself in the model, like so:

Step 2: Let the Controller Use It

And give ourself a way to push it to the front end for display. We’ll add this to our wildfire controller.

Step 3: Build a Route

Then we go into our routes and add a collection.

Step 4: Make it Available

And finally, we’ll give the user the ability to access our newly populated index by calling on our brand new ‘burning’ route. This link was added as a part of our navigation bar in our application layout.html.haml file.

Summary

We used a scope to create a subset of our data dedicated to only those fires which are burning at the moment, indicated by giving the model a boolean attribute of burning, and accessing those where that boolean is set to true.

Fact: You could choose to use either a scope or create a class method, as in this case the two are interchangeable. If you’d like to download the entire application’s source code, you can download wildfire_app here.

--

--