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

Ruby on-RailsRubyActiverecord

Ruby on-Rails Problem Overview


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

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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.

Solution 2 - Ruby on-Rails

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPhantomwhaleView Question on Stackoverflow
Solution 1 - Ruby on-RailsFrederick CheungView Answer on Stackoverflow
Solution 2 - Ruby on-RailsfreezeView Answer on Stackoverflow