DEV Community

Cover image for MAKING A CLASS LEVEL ACTIVERECORD CHAINABLE SCOPE METHOD
Kimberly Kohel-Hayes
Kimberly Kohel-Hayes

Posted on • Originally published at kak79.github.io

MAKING A CLASS LEVEL ACTIVERECORD CHAINABLE SCOPE METHOD

This is how to make a class level ActiveRecord chainable scope method from what is a scope to implementation.

First, I had to find a good definition of scope method. I found one here. Ok. This definition brought up another thing that I don’t understand, lambdas, so let’s find a good article about those. This blog explains how to get from a method to a proc to a lambda. Great! Now we’re in business!

The next thing I’m going to do is look at my models for a validation that I can call either Model.order or Model.where on. For more information on these two ActiveRecord queries go here. Fortunately, I have a year table in my Car model that I can order either ascending or descending to get the oldest or the newest car in my database.

Car Scope

Now how do I use this and chain it?

Car Scope

In the example above, I used the scope in one of my views. I then used interpolation to call on Car.oldest_car in order to access the year, make, model, the path for the link_to, and another class for the owner name. These are the results of my scope methods...

Car Scope

Discussion (0)