In the Scope of Things
What is a Scope Method?
Simply put a scope method is just a class method, in a way. This scope method always returns an ActiveRecord association though, it will never return a nil
value but instead if there is no value, it will return an empty array []
. Scope methods are used to be able to grab certain objects from your database based on certain criteria. For example, if you had a database about different types of cars and wanted to find all the cars within that database that have a certain color(attribute), you would write a scope method in your Car
's model for it that would look like this :
scope :find_color, -> (color) {where("color LIKE ?", color)
Now with this scope method in our Car
model we can then call the scope method in our controller like this :
def search_cars
@color_to_find = params[:color]
@found_cars = Car.find_color(@color_to_find)
end
The params would come from a form that will prompt for a search criteria from the user. Scope methods have a hidden bonus of being able to chain them to other scope methods. For example if you wanted to find all the (insert color choice here) colored cars that belong to a certain owner. You can simply right another scope method to find the certain cars in the database that all belong to the certain owner you are looking for. Then having both scope methods in your model you can call them on each other in your controller like so :
Car.find_color(@color_to_find).cars_owned(@owner_to_find)
I can call the first scope method and then call the second scope method all chained together and it would return the information that we are looking for, it can do it because even if there are no cars in the database that match the color that is desired the scope method would return an empty array instead of nil
which would break the entire chained method. But because a scope returns an ActiveRecord association you can also chain other methods to it. Scope methods are very helpful and they help keep your code DRY because they can be written into short one lines.
Scope Method in Practice
My rails project is a simple virtual gun safe that can keep track of an owners’ guns and how much ammo that owner has. I wanted the owners to be able to see all the ammo that they own, so I needed to query my ammunitions database to find all the ammo in the database that belonged to the certain owner that was actively using the application. Thats where my scope method came into play. I made a scope method in my Ammunition model that would search the database and give me all the ammo that belongs to the current user that is logged into the session.