Zeeshan Asalm
Zeeshan Asalm

Reputation: 131

When is better to use preload or eager_load or includes?

SQL contains join Load associated record in memory Performs two queries
preload no yes yes
includes yes (left outer join) yes sometimes
eager load (left outer join) yes no

I am aware from the concepts.

I want to know when to use which API. I search but does not find exact answer.

Upvotes: 12

Views: 6622

Answers (2)

all these methods help to stay away from N+1 query problem, the key difference is between them how you want to query:

  1. preload: 2 sql queries
  2. includes: if it is a simple query, then 2 sql query; else left join in used
  3. eager_load: left join all of these loads and stores data in memory temporarily.

Upvotes: 1

Eyeslandic
Eyeslandic

Reputation: 14890

includes chooses whether to use preload or eager_load. If you're not happy with the decision includes makes, you have to resort to using either of eager_load or preload


From https://engineering.gusto.com/a-visual-guide-to-using-includes-in-rails/:

When does :includes use :preload?

In most cases :includes will default to use the method :preload which will fire 2 queries:

  • Load all records tied to the leading model
  • Load records associated with the leading model based off the foreign key on the associated model or the leading model

When does :includes use :eager_load?

:includes will default to use :preload unless you reference the association being loaded in a subsequent clause, such as :where or :order. When constructing a query this way, you also need to explicitly reference the eager loaded model.

Employee.includes(:forms).where('forms.kind = "health"').references(:forms)

Upvotes: 12

Related Questions