From b1e509ad7a8c8264544f10f4666705cd806b5408 Mon Sep 17 00:00:00 2001 From: Francesco Rodriguez Date: Mon, 2 Jul 2012 11:57:10 -0500 Subject: Backport #3329 to 3-2-stable Fix bug with autosave collection association on new record with a marked for destroy record in autosave collection. Fixes #6918. --- .../lib/active_record/autosave_association.rb | 36 +++++++++++++--------- 1 file changed, 21 insertions(+), 15 deletions(-) (limited to 'activerecord/lib') diff --git a/activerecord/lib/active_record/autosave_association.rb b/activerecord/lib/active_record/autosave_association.rb index c86eaba498..e1499fc3b0 100644 --- a/activerecord/lib/active_record/autosave_association.rb +++ b/activerecord/lib/active_record/autosave_association.rb @@ -332,25 +332,31 @@ module ActiveRecord if records = associated_records_to_validate_or_save(association, @new_record_before_save, autosave) begin - records.each do |record| - next if record.destroyed? + records_to_destroy = [] + + records.each do |record| + next if record.destroyed? + + saved = true + + if autosave && record.marked_for_destruction? + records_to_destroy << record + elsif autosave != false && (@new_record_before_save || record.new_record?) + if autosave + saved = association.insert_record(record, false) + else + association.insert_record(record) unless reflection.nested? + end + elsif autosave + saved = record.save(:validate => false) + end - saved = true + raise ActiveRecord::Rollback unless saved + end - if autosave && record.marked_for_destruction? + records_to_destroy.each do |record| association.proxy.destroy(record) - elsif autosave != false && (@new_record_before_save || record.new_record?) - if autosave - saved = association.insert_record(record, false) - else - association.insert_record(record) unless reflection.nested? - end - elsif autosave - saved = record.save(:validate => false) end - - raise ActiveRecord::Rollback unless saved - end rescue records.each {|x| IdentityMap.remove(x) } if IdentityMap.enabled? raise -- cgit v1.2.3