Fetching the top n per group with window functions

25-Aug-2022 732
Have you ever needed to get the most recent N posts for each user in rails, but didn’t know how to do it without using map?Or maybe something similar like:The first or last X comments for each postThe first or last Y payments for each customerThe first or last Z reviews for each customerSometimes could be ok to just fetch all elements and filter with ruby, but sometimes it is not possible. Also it can cause n 1 queries if your are not careful.Here I want to show you how you can solve this problem using window functions.
Use coupon code:

RUBYONRAILS

to get 30% discount on our bundle!
Prepare for your next tech interview with our comprehensive collection of programming interview guides. Covering JavaScript, Ruby on Rails, React, and Python, these highly-rated books offer thousands of essential questions and answers to boost your interview success. Buy our 'Ultimate Job Interview Preparation eBook Bundle' featuring 2200+ questions across multiple languages. Ultimate Job Interview Preparation eBook Bundle