From 0ceb21e3354a7cec0c56effdd7a5917f7fa3b564 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Tue, 10 May 2011 11:14:39 +0200 Subject: [PATCH] Revert "b9ea751d0e56bd00d341766977a607ed3f7ddd0f". Wrapping each Record.associations.build in a transaction is going to make several unneeded queries. Reverting this commit also fixes #479. --- .../associations/collection_association.rb | 53 ++++++++++--------- 1 file changed, 27 insertions(+), 26 deletions(-) diff --git a/activerecord/lib/active_record/associations/collection_association.rb b/activerecord/lib/active_record/associations/collection_association.rb index 6cdec8c487..270b43cd5d 100644 --- a/activerecord/lib/active_record/associations/collection_association.rb +++ b/activerecord/lib/active_record/associations/collection_association.rb @@ -94,7 +94,14 @@ def last(*args) end def build(attributes = {}, options = {}, &block) - build_or_create(:build, attributes, options, &block) + if attributes.is_a?(Array) + attributes.collect { |attr| build(attr, options, &block) } + else + add_to_target(build_record(attributes, options)) do |record| + yield(record) if block_given? + set_owner_attributes(record) + end + end end def create(attributes = {}, options = {}, &block) @@ -102,7 +109,16 @@ def create(attributes = {}, options = {}, &block) raise ActiveRecord::RecordNotSaved, "You cannot call create unless the parent is saved" end - build_or_create(:create, attributes, options, &block) + if attributes.is_a?(Array) + attributes.collect { |attr| create(attr, options, &block) } + else + transaction do + add_to_target(build_record(attributes, options)) do |record| + yield(record) if block_given? + insert_record(record) + end + end + end end def create!(attrs = {}, options = {}, &block) @@ -337,20 +353,18 @@ def load_target end def add_to_target(record) - transaction do - callback(:before_add, record) - yield(record) if block_given? - - if options[:uniq] && index = @target.index(record) - @target[index] = record - else - @target << record - end + callback(:before_add, record) + yield(record) if block_given? - callback(:after_add, record) - set_inverse_instance(record) + if options[:uniq] && index = @target.index(record) + @target[index] = record + else + @target << record end + callback(:after_add, record) + set_inverse_instance(record) + record end @@ -403,19 +417,6 @@ def merge_target_lists(loaded, existing) end + existing end - def build_or_create(method, attributes, options) - records = Array.wrap(attributes).map do |attrs| - record = build_record(attrs, options) - - add_to_target(record) do - yield(record) if block_given? - insert_record(record) if method == :create - end - end - - attributes.is_a?(Array) ? records : records.first - end - # Do the relevant stuff to insert the given record into the association collection. def insert_record(record, validate = true) raise NotImplementedError -- GitLab