Permalink
Browse files

keep preloaded records in a list rather than extract from a hash

  • Loading branch information...
1 parent 4c04587 commit be91bb26408cadf3522eb8b8798f2118920cd1eb @tenderlove tenderlove committed Sep 25, 2013
@@ -3,6 +3,7 @@ module Associations
class Preloader
class Association #:nodoc:
attr_reader :owners, :reflection, :preload_scope, :model, :klass
+ attr_reader :preloaded_records
def initialize(klass, owners, reflection, preload_scope)
@klass = klass
@@ -12,7 +13,7 @@ def initialize(klass, owners, reflection, preload_scope)
@model = owners.first && owners.first.class
@scope = nil
@owners_by_key = nil
- @associated_records_by_owner = nil
+ @preloaded_records = []
end
def run(preloader)
@@ -65,15 +66,9 @@ def options
reflection.options
end
- def preloaded_records
- @associated_records_by_owner.values.flatten
- end
-
private
def associated_records_by_owner(preloader)
- return @associated_records_by_owner if @associated_records_by_owner
-
owners_map = owners_by_key
owner_keys = owners_map.keys.compact
@@ -94,18 +89,19 @@ def associated_records_by_owner(preloader)
end
end
end
+
owners.each_with_object(records_by_owner) do |owner,h|
h[owner] ||= []
end
-
- @associated_records_by_owner = records_by_owner
end
def load_slices(slices)
- slices.flat_map { |slice|
- records_for(slice).to_a.map! { |record|
- [record, record[association_key_name]]
- }
+ @preloaded_records = slices.flat_map { |slice|
+ records_for(slice)
+ }
+
+ @preloaded_records.map { |record|
+ [record, record[association_key_name]]
}
end
@@ -38,14 +38,17 @@ def load_slices(slices)
caster = nil
name = association_key_name
- slices.flat_map { |slice|
+ records_to_keys = slices.flat_map { |slice|
records = records_for(slice)
caster ||= records.column_types.fetch(name, records.identity_type)
records.map! { |row|
record = identity_map[row[klass.primary_key]] ||= klass.instantiate(row)
[record, caster.type_cast(row[name])]
}
}
+ @preloaded_records = records_to_keys.map(&:first)
+
+ records_to_keys
end
def build_scope
@@ -2,6 +2,10 @@ module ActiveRecord
module Associations
class Preloader
module ThroughAssociation #:nodoc:
+ def initialize(klass, owners, reflection, preload_scope)
+ super
+ @associated_records_by_owner = nil
+ end
def through_reflection
reflection.through_reflection
@@ -11,9 +15,11 @@ def source_reflection
reflection.source_reflection
end
- def associated_records_by_owner(preloader)
- return @associated_records_by_owner if @associated_records_by_owner
+ def preloaded_records
+ @associated_records_by_owner.values.flatten
+ end
+ def associated_records_by_owner(preloader)
preloader.preload(owners,
through_reflection.name,
through_scope)

0 comments on commit be91bb2

Please sign in to comment.