aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib/active_record/association_preload.rb
diff options
context:
space:
mode:
authorJon Leighton <j@jonathanleighton.com>2011-01-03 13:38:40 +0000
committerAaron Patterson <aaron.patterson@gmail.com>2011-01-03 16:24:32 -0800
commita9bed985cfd7d1ae93f475542bb878aa939e1c1e (patch)
treeddd967ba3ddb08f07dffe3860a489fffa974f5d4 /activerecord/lib/active_record/association_preload.rb
parent99a8d8430f9b819cd3e8cb3aab44cb04ea402532 (diff)
downloadrails-a9bed985cfd7d1ae93f475542bb878aa939e1c1e.tar.gz
rails-a9bed985cfd7d1ae93f475542bb878aa939e1c1e.tar.bz2
rails-a9bed985cfd7d1ae93f475542bb878aa939e1c1e.zip
When preloading a belongs_to, the target should still be set (to nil) if there is no foreign key present. And the loaded flag should be set on the association proxy. This then allows us to remove the foreign_key_present? check from BelongsToAssociation#find_target. Also added a test for the same thing on polymorphic associations.
Diffstat (limited to 'activerecord/lib/active_record/association_preload.rb')
-rw-r--r--activerecord/lib/active_record/association_preload.rb23
1 files changed, 14 insertions, 9 deletions
diff --git a/activerecord/lib/active_record/association_preload.rb b/activerecord/lib/active_record/association_preload.rb
index e3aee701a8..5aad2b4558 100644
--- a/activerecord/lib/active_record/association_preload.rb
+++ b/activerecord/lib/active_record/association_preload.rb
@@ -339,22 +339,27 @@ module ActiveRecord
key = record.send(reflection.foreign_key)
key && key.to_s
end
- id_map.delete nil
klasses_and_ids[reflection.klass] = id_map unless id_map.empty?
end
klasses_and_ids.each do |klass, _id_map|
- table = klass.arel_table
primary_key = (reflection.options[:primary_key] || klass.primary_key).to_s
- method = in_or_equal(_id_map.keys)
- conditions = table[primary_key].send(*method)
+ keys = _id_map.keys.compact
- custom_conditions = append_conditions(reflection, preload_options)
- conditions = custom_conditions.inject(conditions) do |ast, cond|
- ast.and cond
- end
+ unless keys.empty?
+ table = klass.arel_table
+ method = in_or_equal(keys)
+ conditions = table[primary_key].send(*method)
- associated_records = klass.unscoped.where(conditions).apply_finder_options(options.slice(:include, :select, :joins, :order)).to_a
+ custom_conditions = append_conditions(reflection, preload_options)
+ conditions = custom_conditions.inject(conditions) do |ast, cond|
+ ast.and cond
+ end
+
+ associated_records = klass.unscoped.where(conditions).apply_finder_options(options.slice(:include, :select, :joins, :order)).to_a
+ else
+ associated_records = []
+ end
set_association_single_records(_id_map, reflection.name, associated_records, primary_key)
end