Practical Application of Scopes in Ruby on Rails

Andrew Casino
3 min readApr 19, 2021

Rails’ scopes make it easy to find the records you want. As custom queries that you define within your models, they take two arguments:

  1. A name (what you call the scope in your code*)
  2. A lambda, which implements the query

Example:

In our scenario, our lambdas will consist of ActiveRecord Query methods in order to build practical filters on an index page. As scopes are chainable, they are particularly useful in calling on classes or associated class objects.

To get started, we’ll first update our Model.

In the example above, we’ve created three scope methods to filter our index page data by an attribute status (:not_yet_contacted), an unassigned id (:not_yet_assigned), and a descending datetime attribute (:time_occurred_desc).

With our scopes built out on the Model level, we’ll next want to update our Routes file to get the scope methods within a nested collection block.

This syntax enables Rails to recognize paths such as /not_yet_contacted with GET, and route to the action within the “IncidentsController”. It will also create “not_yet_contacted_incidents_url” and “not_yet_contacted_incidents_path” route helpers.

With our Model now complete, it’s time to update our Controller file.

In our example, you’ll see that we’ve simply created controller methods using the same naming conventions as applied to our Model and Routes files. To get this working, we create an @incidents variable equal to an Incident object chained to our scope methods accordingly. In effect, we’re applying the Active Record query from our scopes against all “Incidents” to then display our result set within the @incidents variable in our view. And since we don’t want individual pages for each of filtered result sets, we’ll simply render against our index page using “render action: :index”.

Speaking of views, our final step is to update our index file to display our filters as clickable links to filter our data.

“index.html.erb”; Don’t forget the erb tags!

Following link_to convention, we list “link_to”, the display text we’d like to be visible in quotes, and the _path method.

Note: The appropriate _path method can be found by typing “rails routes” in your terminal, or navigating to http://localhost:3000/rails/info/routes presuming your rails server is running via ‘rails s’ command

With all of the above set up and files saved for your particular project, relocate to your index page and you’ll find our new filter buttons applied:

You did it! Scope away!

--

--