- 1.0.0
- 1.1.6
- 1.2.6
- 2.0.3
- 2.1.0
- 2.2.1
- 2.3.8
- 3.0.0
- 3.0.9
- 3.1.0 (0)
- 3.2.1 (0)
- 3.2.8 (0)
- 3.2.13 (0)
- 4.0.2 (7)
- 4.1.8 (0)
- 4.2.1 (-38)
- 4.2.7 (9)
- 4.2.9 (0)
- 5.0.0.1 (0)
- 5.1.7 (0)
- 5.2.3 (0)
- 6.0.0 (0)
- 6.1.3.1 (0)
- 6.1.7.7 (0)
- 7.0.0 (0)
- 7.1.3.2 (22)
- 7.1.3.4 (0)
- What's this?
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 end class Book < ActiveRecord::Base # columns: title, sales, author_id end
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.
Preload our own with out incude
we can preload our data whenever we want.
ActiveRecord::Associations::Preloader.new.preload(@users, :address)