Joins, includes, preloads, etc. - aavedula/how-to-notes GitHub Wiki
Includes (Eager loading)
Includes and references association
Member.
includes(:population).
references(:population).
where("populations.kind = 2")
- 1 Query, Loads populations, returns Member objects
Member.includes(:population)
- 2 Queries, Loads populations, returns Member objects
Includes association and references table
Member.includes(:population).references(:members)
- 2 Queries, Loads populations, returns Member objects
References table with no includes
Member.references(:population)
- 1 Query, returns Members, no populations
Joins (Lazy loading)
Member.joins(:population)
- 1 Query, returns Member objects, no populations
Preload only
Member.preload(:population)
- 2 Independent queries (no join). Loads populations, returns Member objects
Preload only with where in an associated table
Member.preload(:population).where(populations: { kind: 2 } ).first
- Returns an error
Preload with joins - with select, pluck, and where
Member.joins(:population).preload(:population)
- 2 Queries, Loads populations, returns Member objects
Member.
preload(:population).
joins(:population).
where(populations: { kind: 2 } ).
select(:population_id)
- Returns an array of some objects containing the selected fields
Member.
preload(:population).
joins(:population).
where(populations: { kind: 2 } ).
pluck(:population_id)
- Returns an array of values.
- Eagerly loads data