A common cause of n+1 queries is fetching the “latest-N-of-each” record on a list of records.
Some examples of this problem are trying to get…
I have one post named 5 ways to fetch the latest-N-of-each record on Rails where I share different ways to solve this problem. Here I want to share with you the code that I used in the post.
You can use it to run the examples, and play with the code and seed values, to pick the right solution for you current case.
1 - Install the dependencies with
2 - Database setup - run the command:
3 - Run the examples with
ruby fixes_examples/<file name>. For example:
4 - Change the posts and comments count on
db/seeds.rb you can change
Seeds.run(posts_count: 10, comments_count: 10) and re-run
db/setup.rb to test different scenarios.
Subscribe, and get the code to run each of the examples in the post. You will receive a zip with the code.
Sign up to download free ebook, where I will show the basics on how to deal with n+1 problems.
includes, etc...) to work with associations.