Joins, includes, preloads, etc. - aavedula/how-to-notes GitHub Wiki

Back

Includes (Eager loading)

Includes and references association

  Member.
    includes(:population).
    references(:population).
    where("populations.kind = 2")
  • 1 Query, Loads populations, returns Member objects

Includes association

  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)

Joins

  Member.joins(:population)
  • 1 Query, returns Member objects, no populations

Preload only

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

Back

Preload with joins

  Member.joins(:population).preload(:population)
  • 2 Queries, Loads populations, returns Member objects

Select from table

  Member.
    preload(:population).
    joins(:population).
    where(populations: { kind: 2 } ).
    select(:population_id)
  • Returns an array of some objects containing the selected fields

Pluck from table

  Member.
    preload(:population).
    joins(:population).
    where(populations: { kind: 2 } ).
    pluck(:population_id)
  • Returns an array of values.
  • Eagerly loads data

Pluck from table and association