From d90b4e2615e8048fdeffc6dffe3246704adee01f Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Wed, 23 Feb 2011 00:17:01 +0000 Subject: Rewrote AssociationPreload. --- .../associations/preloader/through_association.rb | 66 ++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 activerecord/lib/active_record/associations/preloader/through_association.rb (limited to 'activerecord/lib/active_record/associations/preloader/through_association.rb') diff --git a/activerecord/lib/active_record/associations/preloader/through_association.rb b/activerecord/lib/active_record/associations/preloader/through_association.rb new file mode 100644 index 0000000000..d630fc4c63 --- /dev/null +++ b/activerecord/lib/active_record/associations/preloader/through_association.rb @@ -0,0 +1,66 @@ +module ActiveRecord + module Associations + class Preloader + module ThroughAssociation #:nodoc: + + def through_reflection + reflection.through_reflection + end + + def source_reflection + reflection.source_reflection + end + + def associated_records_by_owner + through_records = through_records_by_owner + + ActiveRecord::Associations::Preloader.new( + through_records.values.flatten, + source_reflection.name, options + ).run + + through_records.each do |owner, owner_through_records| + owner_through_records.map! { |r| r.send(source_reflection.name) }.flatten! + end + end + + private + + def through_records_by_owner + ActiveRecord::Associations::Preloader.new( + owners, through_reflection.name, + through_options + ).run + + Hash[owners.map do |owner| + through_records = Array.wrap(owner.send(through_reflection.name)) + + # Dont cache the association - we would only be caching a subset + if reflection.options[:source_type] && through_reflection.collection? + owner.association(through_reflection.name).reset + end + + [owner, through_records] + end] + end + + def through_options + through_options = {} + + if options[:source_type] + through_options[:conditions] = { reflection.foreign_type => options[:source_type] } + else + if options[:conditions] + through_options[:include] = options[:include] || options[:source] + through_options[:conditions] = options[:conditions] + end + + through_options[:order] = options[:order] + end + + through_options + end + end + end + end +end -- cgit v1.2.3