Benito Serna Tips and tools for Ruby on Rails developers

Tool to run the examples for the 5 ways to fetch the latest-n-of-each record

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.

How to run the examples

1 - Install the dependencies with bundle install.

2 - Database setup - run the command:

ruby db/setup.rb

3 - Run the examples with ruby fixes_examples/<file name>. For example:

ruby fixes_examples/01_fetch_all_and_select_for_each.rb

4 - Change the posts and comments count on db/seeds.rb you can change 10, comments_count: 10) and re-run ruby db/setup.rb to test different scenarios.

Get the code to run the examples

Subscribe, and get the code to run each of the examples in the post. You will receive a zip with the code.

Related articles

Do you feel bad for asking for help to fix an n+1 queries problem?

Making things work isn't enough for you any more? Now you need to consider performance and scalability?

... But you normally have troubles fixing n+1 queries and trying to find why active record is ignoring your "includes"?

Are you are worried because you feel unqualified to tackle tasks with complex data models?

Sign up to learn how to fix n+1 queries on Rails