This article is also available in Korean, thanks to Soonsang Hong!
Rails’ scopes make it easy to find the records you want:
But if you’re not careful with them, you’ll seriously hurt your app’s performance.
Why? You can’t really preload a scope. So if you tried to show a few restaurants with their positive reviews:
Yep, that’s an N+1 query. The biggest cause of slow Rails apps.
You can fix this pretty easily, though, if you think about the relationship in a different way.
Convert scopes to associations
When you use the Rails association methods, like
has_many, your model usually looks like this:
But if you check out the documentation, you’ll see that they can do more. You can pass other parameters to those methods and change how they work.
scope is one of the most useful. It works just like the
scope from earlier:
Now, you can preload your new association with
Instead of 6 SQL calls, we only did two.
class_name, you can have multiple associations to the same object. This comes in handy pretty often.)
What about duplication?
There still might be a problem here. The
where("rating > 3.0") is now on your Restaurant class. If you later changed positive reviews to
rating > 3.5, you’d have to update it twice!
It gets worse: If you also wanted to grab all the positive reviews a person has ever left, you’d have to duplicate that scope over on the User class, too:
It’s not very DRY.
There’s an easy way around this, though. Inside of
where, you can use the
positive scope you added to the Review class:
That way, the idea of what makes a review a positive review is still only in one place.
Scopes are great. In the right place, they can make querying your data easy and fun. But if you want to avoid N+1 queries, you have to be careful with them.
So, if a scope starts to cause you trouble, wrap it in an association and preload it. It’s not much more work, and it’ll save you a bunch of SQL calls.