Ruby on Rails latest stable (v6.1.7.7) - 1 note - Superclass: Object

Implements the details of eager loading of Active Record associations.

Suppose that you have the following two Active Record models:

class Author < ActiveRecord::Base
  # columns: name, age
  has_many :books

class Book < ActiveRecord::Base
  # columns: title, sales, author_id

When you load an author with all associated books Active Record will make multiple queries like this:

Author.includes(:books).where(name: ['bell hooks', 'Homer']).to_a

=> SELECT `authors`.* FROM `authors` WHERE `name` IN ('bell hooks', 'Homer')
=> SELECT `books`.* FROM `books` WHERE `author_id` IN (2, 5)

Active Record saves the ids of the records from the first query to use in the second. Depending on the number of associations involved there can be arbitrarily many SQL queries made.

However, if there is a WHERE clause that spans across tables Active Record will fall back to a slightly more resource-intensive single query:

Author.includes(:books).where(books: {title: 'Illiad'}).to_a
=> SELECT `authors`.`id` AS t0_r0, `authors`.`name` AS t0_r1, `authors`.`age` AS t0_r2,
          `books`.`id`   AS t1_r0, `books`.`title`  AS t1_r1, `books`.`sales` AS t1_r2
   FROM `authors`
   LEFT OUTER JOIN `books` ON `authors`.`id` =  `books`.`author_id`
   WHERE `books`.`title` = 'Illiad'

This could result in many rows that contain redundant data and it performs poorly at scale and is therefore only used when necessary.

Show files where this class is defined (3 files)
Register or log in to add new notes.
February 1, 2017 - (v4.1.8 - v4.2.7)
0 thanks

Preload our own with out incude

we can preload our data whenever we want.

ActiveRecord::Associations::Preloader.new.preload(@users, :address)