Do you have to fetch the latest “x” of each record?
One example of this problem is trying to get the latest comment on a list of posts, but there are others, like the last review in a list of products, or the cheapest price, or the latest payment for each costumer, etc…
I want to share with you the code I used in the post 5 ways to fix the latest-comment n+1 problem.
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.
You can see the code on github at bhserna/latest_comment_n-1_examples
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