Using Scopes to Write Custom Queries in Rails
July 15, 2014
In our Rails Level I course we look at how to define custom queries by writing class methods in models. For example, to find all events that occurred in the past (versus upcoming events), we write a past
method in the Event
model and then query past events using Event.past
.
We build on that foundation in our Rails Level II course by learning how to write custom queries using the declarative style offered by the scope
method. A scope simply names a chunk of query code, and behind the scenes it dynamically defines a class method that encapsulates the query code.
One of the keys to writing a scope is to make the query code a callable Ruby object (also called a Proc
object). It’s at this point that many folks are first exposed to a Ruby lambda
, or the more cryptic ->
shortcut. As a quick introduction to how lambdas work, check out this 3-minute excerpt from the Scopes module in our Rails Level II course where we convert the past
class method to a scope:
If you found that helpful, go ahead and watch the entire Scopes module, as well as other free modules in the Rails Level II course. You can also check out the course introduction video for an overview of the application features we build in this course. Or jump right in and purchase the entire course (with downloadable HD videos!). Our course is based on Rails 5, so you’ll learn and apply the most up-to-date techniques!
"I know after completing your Rails I and II courses that I can build pretty much whatever I want to in Rails. These two courses are far and away the best value-for-money Rails courses out there." — Jonathan Mundy