Module: EagerRecord::ScopedPreloading::HasManyAssociationExtensions

Defined in:
lib/eager_record/scoped_preloading.rb

Instance Method Summary collapse

Instance Method Details

#find_using_scoped_preload(originating_collection, *args) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/eager_record/scoped_preloading.rb', line 59

def find_using_scoped_preload(originating_collection, *args)
  options = args.extract_options!
  reflection_name = @reflection.name
  current_scope = 
    if current_scoped_methods && current_scoped_methods[:find] #XXX regression test
      @reflection.options.merge(current_scoped_methods[:find])
    else
      @reflection.options
    end
  owner_class = @owner.class
  reflection_class = @reflection.klass
  scope_key = current_scope.inspect
  if preloaded_association = @owner.__send__(:scoped_preloaded_associations_for, reflection_name)[scope_key]
    return preloaded_association
  end
  reflection = owner_class.__send__(
    :create_has_many_reflection,
    TEMPORARY_SCOPED_PRELOAD_ASSOCIATION,
    current_scope.merge(
      :class_name => reflection_class.name,
      :readonly => true
  )
  )
  originating_collection.each do |record|
    association = ActiveRecord::Associations::HasManyAssociation.new(record, reflection)
    record.__send__(:association_instance_set, TEMPORARY_SCOPED_PRELOAD_ASSOCIATION, association)
  end
  owner_class.__send__(:preload_has_many_association, originating_collection, reflection)
  originating_collection.each do |record|
    record.instance_eval do
      @scoped_preloaded_associations ||= Hash.new { |h, k| h[k] = {} }
      @scoped_preloaded_associations[reflection_name][scope_key] =
        association_instance_get(TEMPORARY_SCOPED_PRELOAD_ASSOCIATION)
      association_instance_set(TEMPORARY_SCOPED_PRELOAD_ASSOCIATION, nil)
    end
  end
  @owner.__send__(:scoped_preloaded_associations_for, reflection_name)[scope_key]
end