Reputation: 131
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
Reputation: 11
all these methods help to stay away from N+1 query problem, the key difference is between them how you want to query:
Upvotes: 1
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:
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