Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 964
Phantomwhale Avatar asked Aug 14 '12 05:08

Phantomwhale


People also ask

What is eager loading in Ruby?

Eager loading solves this problem by creating a left outer join on the table, returning all of the data in a single query. Adding an eager load is as simple as adding an :includes statement to the controller.

What is config Eager_load?

config. eager_load when true, eager loads all registered config. eager_load_namespaces . This includes your application, engines, Rails frameworks and any other registered namespace.


1 Answers

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.

like image 100
Frederick Cheung Avatar answered Sep 21 '22 02:09

Frederick Cheung