Benito Serna Tips and tools for Ruby on Rails developers

When is better to use preload or eager_load vs includes?

January 19, 2021

Even if you already know what is the difference between includes, preload and eager_load, maybe is not that clear when is better for you to use one vs the other.

If you don’t know the difference you can read… What is the difference between includes, preload, eager_load and joins?

Well, as you may know, with Rails/ActiveRecord you can preload associations in 2 different ways:

Using includes by default

When you use includes Rails will decide which strategy to use for you. I think that this is a good default. Use includes and let rails decide for you.

But, to be honest, that is not what I do…

Using preload by default

I (at least for now) prefer to use preload explicitly by default, because that is also the default for includes, and I think that is easier to know what is going to happen just by watching the code.

I use eager_load just when I already know that is significantly faster than the preload.

So, what should you do?

I would say, “Don’t worry to much”, and just pick one of this two strategies.

Do you want to practice?

Practice will help you understand this concepts better. I have prepared some examples/excercises to help you understand how you can use this methods. Give it try!

Examples to learn the difference between preload, includes or eager_load

Related articles

No more… “Why active record is ignoring my includes?”

Get for free the first part of the ebook Fix n+1 queries on Rails that will help you:

  • Explain what is an n+1 queries problem
  • Identify when ActiveRecord will execute a query
  • Solve the latest comment example
  • Detect n+1 queries by watching the logs
  • Learn the tools to detect n+1 queries
Get the first part of the ebook for free