Scope Methods in Rails

I have been re-working some old projects recently. I forgot how much I enjoyed working with Rails. The amount of built-in features can be daunting but Rails does a wonderful job of guiding you if you messed up syntax. Something that I have been refreshing myself on is adding a scope method to a model. If you are confused on how to implement a scope method or just not really sure what they are, we will go over that here.

First off, what is a scope method? Scopes are just a way to return a specific active record association. Say your application allowed a user to purchase shirts online. You can use scope methods to return the relationship of items you want based off of attributes of that object. An applicable example would be if you wanted a way for the user to only see long-sleeved shirts or a way to filter your shirts so that only red shirts came up. If you’ve spent some time with Ruby, you might be thinking that you could just use the find method. This will return the data you want but this wouldn’t be using their active record relationship. Using scope methods allows the programmer to chain scope methods, allowing for detailed searches for the exact object you are looking for. Let’s go back to our shirt example again. We have a class for shirts. They have attributes of size, color, type and price. If you wanted to create a scope that shows only long-sleeved red shirts. You would create a scope method within the class file under models. you can split it up into two scopes looking something like this:

We can chain these together to create a query for active record that looks something like this: Shirt.red_shirt.long_sleeved. this will query all red colored and long sleeved shirts. This is called a “named scope”. You are giving it a name that can be referenced anywhere that your Shirt class is. If you have experience in SQL, you will probably notice that you can exchange where in our example with our SQL queries. If we had only a certain amount of red long-sleeved shirts, we could create a scope that utilized sum to give us the number of shirts left.

I wanted to write this as something a bit more basic because as I’ve done my research on scope methods, I have noticed a ton of really in-depth blogs on more advanced uses. I remembered when I first started working with scopes, I found the basic explanation was a lot harder to find. Be sure to check official documentation here. As always, happy coding!