From c6fbbbc17440b6629fc41fef1a6fc80a1830f982 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Fri, 20 Sep 2013 15:39:10 -0700 Subject: push `run` up to preload --- .../lib/active_record/associations/preloader/association.rb | 10 +++++++--- .../associations/preloader/has_and_belongs_to_many.rb | 5 ++++- 2 files changed, 11 insertions(+), 4 deletions(-) (limited to 'activerecord/lib/active_record/associations/preloader') diff --git a/activerecord/lib/active_record/associations/preloader/association.rb b/activerecord/lib/active_record/associations/preloader/association.rb index 051bc3a8da..9b8750b9ea 100644 --- a/activerecord/lib/active_record/associations/preloader/association.rb +++ b/activerecord/lib/active_record/associations/preloader/association.rb @@ -72,6 +72,12 @@ module ActiveRecord end def target_records + associated_records_by_owner.values.flatten + end + + private + + def lhs_records return @target_records if @target_records owners_map = owners_by_key @@ -85,8 +91,6 @@ module ActiveRecord } end - private - def associated_records_by_owner owners_map = owners_by_key owner_keys = owners_map.keys.compact @@ -98,7 +102,7 @@ module ActiveRecord # Some databases impose a limit on the number of ids in a list (in Oracle it's 1000) # Make several smaller queries if necessary or make one query if the adapter supports it caster = type_caster - target_records.each do |record| + lhs_records.each do |record| owner_key = caster.call record[association_key_name] owners_map[owner_key].each do |owner| diff --git a/activerecord/lib/active_record/associations/preloader/has_and_belongs_to_many.rb b/activerecord/lib/active_record/associations/preloader/has_and_belongs_to_many.rb index 87992a70e8..48ae99819b 100644 --- a/activerecord/lib/active_record/associations/preloader/has_and_belongs_to_many.rb +++ b/activerecord/lib/active_record/associations/preloader/has_and_belongs_to_many.rb @@ -7,6 +7,7 @@ module ActiveRecord def initialize(klass, records, reflection, preload_options) super @join_table = Arel::Table.new(reflection.join_table).alias('t0') + @records_by_owner = nil end # Unlike the other associations, we want to get a raw array of rows so that we can @@ -34,8 +35,10 @@ module ActiveRecord # actual records, ensuring that we don't create more than one instances of the same # record def associated_records_by_owner + return @records_by_owner if @records_by_owner + records = {} - super.each_value do |rows| + @records_by_owner = super.each_value do |rows| rows.map! { |row| records[row[klass.primary_key]] ||= klass.instantiate(row) } end end -- cgit v1.2.3