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.

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s