Small ruby tips

N+1 Query

What is a N+1 query? Consider a situation where you have users that each have many friends. If we loop to map the friends, we could write the following map code.

With this first solution every time you access a user’s friends, it goes back to the database to load them, generating an N+1 query.

The ActiveRecord solution is to eagerly load the data and this is accomplished with a simple method includes.


Memoization is a technique you can use to cache the result of a method that do time-consuming work and can be executed once.

That means that you’ll only make the network call the first time you call memoized_friends, and future calls will just return the value of the instance variable friends.

Map Shorthand

You can use a shorthand version for map when you’re calling a method that doesn’t need any arguments.

Thanks for reading!



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store