From ef724e41a2e53ff786f2ff9a145815b29a985b4f Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Wed, 28 Aug 2013 18:09:00 -0700 Subject: correctly typecast keys, remove conditionals, reduce object allocations --- .../lib/active_record/associations/preloader/association.rb | 13 ++++++------- .../associations/preloader/has_and_belongs_to_many.rb | 5 +++++ 2 files changed, 11 insertions(+), 7 deletions(-) (limited to 'activerecord/lib/active_record') diff --git a/activerecord/lib/active_record/associations/preloader/association.rb b/activerecord/lib/active_record/associations/preloader/association.rb index 3eb3407dea..928da71eed 100644 --- a/activerecord/lib/active_record/associations/preloader/association.rb +++ b/activerecord/lib/active_record/associations/preloader/association.rb @@ -56,12 +56,9 @@ module ActiveRecord raise NotImplementedError end - # We're converting to a string here because postgres will return the aliased association - # key in a habtm as a string (for whatever reason) def owners_by_key @owners_by_key ||= owners.group_by do |owner| - key = owner[owner_key_name] - key && key.to_s + owner[owner_key_name] end end @@ -84,8 +81,9 @@ module ActiveRecord sliced = owner_keys.each_slice(klass.connection.in_clause_length || owner_keys.size) sliced.each { |slice| records = records_for(slice) + caster = type_caster(records, association_key_name) records.each do |record| - owner_key = owner_id_for records, record + owner_key = caster.call record[association_key_name] owners_map[owner_key].each do |owner| records_by_owner[owner] << record @@ -97,8 +95,9 @@ module ActiveRecord records_by_owner end - def owner_id_for(results, record) - record[association_key_name].to_s + IDENTITY = lambda { |value| value } + def type_caster(results, name) + IDENTITY end def reflection_scope 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 08a36db877..c042a44b21 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 @@ -40,6 +40,11 @@ module ActiveRecord end end + def type_caster(results, name) + caster = results.column_types.fetch(name, results.identity_type) + lambda { |value| caster.type_cast value } + end + def build_scope super.joins(join).select(join_select) end -- cgit v1.2.3