Module: OccamsRecord::EagerLoaders::Builder

Included in:
Query, RawQuery
Defined in:
lib/occams-record/eager_loaders.rb

Overview

Methods for adding eager loading to a query.

Instance Method Summary collapse

Instance Method Details

#eager_load(assoc, scope = nil, select: nil, use: nil, as: nil) { ... } ⇒ OccamsRecord::Query

Specify an association to be eager-loaded. For maximum memory savings, only SELECT the colums you actually need.

ActiveRecord::Relation on which you may call all the normal query hethods (select, where, etc) as well as any scopes you’ve defined on the model.

Parameters:

  • assoc (Symbol)

    name of association

  • scope (Proc) (defaults to: nil)

    a scope to apply to the query (optional). It will be passed an

  • select (String) (defaults to: nil)

    a custom SELECT statement, minus the SELECT (optional)

  • use (Array<Module>) (defaults to: nil)

    optional Module to include in the result class (single or array)

  • as (Symbol) (defaults to: nil)

    Load the association usign a different attribute name

Yields:

  • a block where you may perform eager loading on this association (optional)

Returns:



28
29
30
31
32
33
34
35
# File 'lib/occams-record/eager_loaders.rb', line 28

def eager_load(assoc, scope = nil, select: nil, use: nil, as: nil, &eval_block)
  ref = @model ? @model.reflections[assoc.to_s] : nil
  ref ||= @model.subclasses.map(&:reflections).detect { |x| x.has_key? assoc.to_s }&.[](assoc.to_s) if @model
  raise "OccamsRecord: No assocation `:#{assoc}` on `#{@model&.name || '<model missing>'}` or subclasses" if ref.nil?
  scope ||= ->(q) { q.select select } if select
  @eager_loaders << eager_loader_for_association(ref).new(ref, scope, use: use, as: as, &eval_block)
  self
end