How to use preload in Ruby on Rails

To avoid problem N + 1 in RoR, we can use preload, preload will load all association records using another sql query.

Example: we have model User, Post and Comment with relation:

User has_many Posts

Post has_many Comments

Now you want to show all male users associated with their posts and comments.

If you can do like this

User.preload(posts: :comments).where(gender: :male)

It will generate 3 sql query.

1. For load all user with gender male

2. Load all posts with user_id in id of first query

3. Load all comments with post_id in id of second query

So it only take 3 query for all users instead of 3 query for each users. It will save a lot of time

That’s all.