Once you understand that n+1 queries can be a problem, it can be frustrating that is very easy to end with n+1 queries in rails, sometimes as an accident and sometimes just because you don’t know why.
When n+1 queries happen a lot to you, and you are not the one that find them, It can make you feel that you are not “good enough”.
And when you try to fix the n+1 queries, and it results in rails “ignoring your includes” it can make you even more insecure or unqualified to handle more complex tasks or even try to fix other performance problems.
The common advice to fix n+1 queries is “have you tried
includes?”… But it don’t solve all the problems, and maybe you have other questions…
You wont be taking time from your team asking for help for you n+1 queries problems.
You could feel secure and “qualified” to take complex tasks, with complex associations, because you will feel secure that you can fetch the need data efficiently. You know how to preload direct associations but also, complex nested associations.
You can decide when is better to preload just counts, instead of the whole association. Or you can decide if it is a good time to introduce a counter cache.
You can help your team leaders to decide which tool to use to detect n+1 queries proactively.
You know went to use includes, when to use preload and when to use eager_load, and can help your team when someone don’t know when is better to use one over the other.
You can preload direct associations and nested associations and combine them with other kind of filters and sorting in your queries.
It is true, is very easy to produce n+1 queries working with ActiveRecord associations, and fixing them alone can be frustrating and some “fixes” can hurt performance even more… but it doesn’t have to.
Master n+1 queries identification, preloading, counts and counter caches, and eliminate n+1 queries from your code.
You will learn:
You’ll learn, how you can use active record features and other tools to avoid n+1 queries and start shipping performant code.
Just pick the story/task/feature that you want, buy my ebook “Avoid n+1 queries basics”, and you’ll be shipping beautiful and efficient code in no time.