Custom Scopes in Model Files in a Rails Application
In this lesson, we are going to talk about adding custom scopes to models in a Ruby on Rails application.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

In this lesson, we are going to talk about adding custom scopes to models.

To do that, let's say we want to display only those projects that are complete or near complete. Before going into the code, I'm going to add some values to the percent_complete field.

Next, let's go to project.rb and add a custom scope with the following code.

scope :almost_completed, -> { where('percent_complete > 75.0') }

In this code, I'm creating a method called almost_completed and allowing it to be called from our controller file with the symbol ->. The logic inside it is simple SQL query using where.

Next, let's go to projects_controller.rb In the index method, and here I'm going to make a small change to the existing code. Instead of Project.all I'm changing it to Project.almost_completed.

Now, if we go back to the browser and hit refresh, it will display only those projects that have a percent_complete value of more than 75.

medium

We can keep adding more scopes too. For example, let's go back to our model file project.rb and create another scope.

scope :still_needs_more_work, -> { where('percent_complete <75.0') }

Likewise, in the controller file, change the code to:

@projects = Project.still_needs_some_work

The browser will now display this list.

medium

If you notice, it only displays those records that have a value of 0.0, and not the ones that have a nil value.

So, this is how you integrate custom scopes into your model files.