From 9d08a07c48274686f8bd21e590249bfe3865df89 Mon Sep 17 00:00:00 2001 From: Michael Koziarski Date: Thu, 26 Apr 2007 00:18:38 +0000 Subject: Improve Performance of calling create on has_many :through associations by avoiding loading the target collection. Closes #8150 [evan] git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@6581 5ecf4fe2-1ee6-0310-87b1-e25e094e27de --- .../associations/has_many_through_association.rb | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) (limited to 'activerecord/lib/active_record') diff --git a/activerecord/lib/active_record/associations/has_many_through_association.rb b/activerecord/lib/active_record/associations/has_many_through_association.rb index a8ad52bef9..93f1b2ee6a 100644 --- a/activerecord/lib/active_record/associations/has_many_through_association.rb +++ b/activerecord/lib/active_record/associations/has_many_through_association.rb @@ -51,8 +51,6 @@ module ActiveRecord through = @reflection.through_reflection raise ActiveRecord::HasManyThroughCantAssociateNewRecords.new(@owner, through) if @owner.new_record? - load_target - klass = through.klass klass.transaction do flatten_deeper(records).each do |associate| @@ -60,7 +58,7 @@ module ActiveRecord raise ActiveRecord::HasManyThroughCantAssociateNewRecords.new(@owner, through) unless associate.respond_to?(:new_record?) && !associate.new_record? @owner.send(@reflection.through_reflection.name).proxy_target << klass.with_scope(:create => construct_join_attributes(associate)) { klass.create! } - @target << associate + @target << associate if loaded? end end @@ -138,11 +136,11 @@ module ActiveRecord # Construct attributes for :through pointing to owner and associate. def construct_join_attributes(associate) - returning construct_owner_attributes(@reflection.through_reflection).merge(@reflection.source_reflection.primary_key_name => associate.id) do |join_attributes| - if @reflection.options[:source_type] - join_attributes.merge!(@reflection.source_reflection.options[:foreign_type] => associate.class.base_class.name.to_s) - end + join_attributes = construct_owner_attributes(@reflection.through_reflection).merge(@reflection.source_reflection.primary_key_name => associate.id) + if @reflection.options[:source_type] + join_attributes.merge!(@reflection.source_reflection.options[:foreign_type] => associate.class.base_class.name.to_s) end + join_attributes end # Associate attributes pointing to owner, quoted. -- cgit v1.2.3