What's the difference between “includes” and “preload” in an ActiveRecord query?
Asked Answered
L

2

64

I'm struggling to find a comparison of includes() and preload() for ActiveRecord objects. Can anyone explain the difference ?

Lynd answered 14/8, 2012 at 5:38 Comment(0)
T
95

Rails has 2 ways of avoiding the n+1 problem. One involves creating a big join based query to pull in your associations, the other involves making a separate query per association.

When you do includes rails decides which strategy to use for you. It defaults to the separate query approach (preloading) unless it thinks you are using the columns from the associations in you conditions or order. Since that only works with the joins approach it uses that instead.

Rails' heuristics sometimes get it wrong or you may have a specific reason for preferring one approach over the other. preload ( and its companion method eager_load) allow you to specify which strategy you want rails to use.

Taffeta answered 14/8, 2012 at 7:2 Comment(4)
Awesome - a murky, undocumented corner of ActiveRecord that one. Thanks for shining some light !Lynd
This blog discusses the same topic blog.bigbinary.com/2013/07/01/…Alephnull
This blog post is very useful and clear blog.arkency.com/2013/12/rails4-preloadingDaric
Awesome explanation. Thanks alot!Equilibrate
I
-7

As apidoc said "This method is deprecated or moved on the latest stable version. The last existing version (v3.0.9) is shown here." So the difference is that includes just NOT deprecated.

Inaudible answered 14/8, 2012 at 5:58 Comment(3)
'deprecated or moved'. In this case it's moved, not deprecated. And they're not the same.Taffeta
Sorry, but if I have possibility to call it (Rails 3.2.6) it doesn't moved for me - just deprecated.Inaudible
apidoc gets massively confused when people refactor code from one module to another - it can think that a method has moved even through from the public api point of view it hasn'tTaffeta

© 2022 - 2024 — McMap. All rights reserved.