Class: OccamsRecord::EagerLoaders::Habtm

Inherits:
Base
  • Object
show all
Defined in:
lib/occams-record/eager_loaders/habtm.rb

Overview

Eager loader for has_and_belongs_to_many associations.

Instance Attribute Summary

Attributes inherited from Base

#eval_block, #name, #use

Instance Method Summary collapse

Methods inherited from Base

#initialize

Constructor Details

This class inherits a constructor from OccamsRecord::EagerLoaders::Base

Instance Method Details

#merge!(assoc_rows, rows) ⇒ Object

Merge the association rows into the given rows.

Parameters:



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/occams-record/eager_loaders/habtm.rb', line 22

def merge!(assoc_rows, rows)
  joins_by_id = join_rows(rows).reduce({}) { |a, join|
    id = join[0].to_s
    a[id] ||= []
    a[id] << join[1].to_s
    a
  }

  assoc_rows_by_id = assoc_rows.reduce({}) { |a, row|
    id = row.send(@ref.association_primary_key).to_s
    a[id] = row
    a
  }

  assign = "#{name}="
  rows.each do |row|
    id = row.send(@ref.active_record_primary_key).to_s
    assoc_fkeys = (joins_by_id[id] || []).uniq
    associations = assoc_rows_by_id.values_at(*assoc_fkeys).compact.uniq
    row.send assign, associations
  end
end

#query(rows) { ... } ⇒ Object

Yield one or more ActiveRecord::Relation objects to a given block.

Parameters:

Yields:



11
12
13
14
# File 'lib/occams-record/eager_loaders/habtm.rb', line 11

def query(rows)
  assoc_ids = join_rows(rows).map { |row| row[1] }.compact.uniq
  yield base_scope.where(@ref.association_primary_key => assoc_ids)
end