Benito Serna Tips and tools for Ruby on Rails developers

Code to run the examples for preload, includes or eager_load

Do you know “in theory” the difference between “includes”, “preload”, “eager_load” and “joins”, but you still think that you need more examples to really understand how to use them?

Here you will find a set of examples to help you understand how you can use this 4 methods.

You can find the code on bhserna/preloading_examples

This is the code that I used for the post: Examples to learn the difference between preload, includes or eager_load.

On lib/examples.rb you will find a list of examples with:

You can use this code to play a little more and try different things.

How to run the examples

  1. Create a postgres database with createdb preloading_examples. As you can see the in db/config.rb the name of the database is hardcoded, so you will need to create a database with that name.

  2. Install the dependencies with bundle install.

  3. Run the seeds with ruby db/seeds.rb. You can also update the data that you want to use, there.

  4. Run the examples with ruby lib/examples.rb.

Related articles

Do you want to solve n+1 queries with confidence?

Sign up to download my free ebook, where I will show you how to deal with n+1 problems like a pro, by helping you...

  • Understand the principal methods (joins, includes, etc...) to work with associations.
  • Identify when active record will execute a query.
  • And the tools that can help you detect n+1 queries before they hit production (like the bullet gem).