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 belongs_to and 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 includes:
Instead of 6 SQL calls, we only did two.
(Using 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:
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.
Pushing through tutorials, and still not learning anything?
Have you slogged through the same guide three times and still don't know how to build a real app?
In this free 7-day Rails course, you'll learn specific steps to start your own Rails apps — without giving up, and without being overwhelmed.
You'll also discover the fastest way to learn new Rails features with your 32-page sample of Practicing Rails: Learn Rails Without Being Overwhelmed.
Sign up below to get started:
Thanks! You should get an email from me in a few minutes with your free sample chapter.
While you wait, I'd love to <a href="https://mastodon.justinweiss.com/@justin">meet you on Mastodon</a>. You can learn a little bit more about Ruby each day -- I share the best Ruby and Rails articles I read. And it's great for short conversations and answering questions about software development.