aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib
diff options
context:
space:
mode:
authorJohnny Holton <johnny@holton.co>2013-04-10 23:29:19 -0400
committerJohnny Holton <johnny@holton.co>2013-05-02 03:27:06 -0400
commit483c301e0a132a6415355be2296fb932d07bd1c5 (patch)
tree2d644bfa199b89e6df0584772a5d24585e5d7779 /activerecord/lib
parentdfd5dc93a1ead62353cc33f5065e23b4fdf25b3e (diff)
downloadrails-483c301e0a132a6415355be2296fb932d07bd1c5.tar.gz
rails-483c301e0a132a6415355be2296fb932d07bd1c5.tar.bz2
rails-483c301e0a132a6415355be2296fb932d07bd1c5.zip
destroys association records before saving/inserting new association records
fixes bug introduced by #3329 These are the conditions necessary to reproduce the bug: - For an association, autosave => true. - An association record is being destroyed - A new association record is being created. - There is a unique index one of the association's fields. - The record being created has the same value as the record being destroyed on the indexed field. Before, the deletion of records was postponed until after all insertions/saves. Therefore the new record with the identical value in the indexed field caused a non-unique value error to be thrown at the database level. With this fix, the deletions happen first, before the insertions/saves. Therefore the record with the duplicate value is gone from the database before the new record is created, thereby avoiding the non-uniuqe value error.
Diffstat (limited to 'activerecord/lib')
-rw-r--r--activerecord/lib/active_record/autosave_association.rb17
1 files changed, 8 insertions, 9 deletions
diff --git a/activerecord/lib/active_record/autosave_association.rb b/activerecord/lib/active_record/autosave_association.rb
index b0bd78ad46..87d4daa6d9 100644
--- a/activerecord/lib/active_record/autosave_association.rb
+++ b/activerecord/lib/active_record/autosave_association.rb
@@ -335,15 +335,18 @@ module ActiveRecord
autosave = reflection.options[:autosave]
if records = associated_records_to_validate_or_save(association, @new_record_before_save, autosave)
- records_to_destroy = []
+
+ if autosave
+ records_to_destroy = records.select(&:marked_for_destruction?)
+ records_to_destroy.each { |record| association.destroy(record) }
+ records -= records_to_destroy
+ end
+
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 != false && (@new_record_before_save || record.new_record?)
if autosave
saved = association.insert_record(record, false)
else
@@ -355,10 +358,6 @@ module ActiveRecord
raise ActiveRecord::Rollback unless saved
end
-
- records_to_destroy.each do |record|
- association.destroy(record)
- end
end
# reconstruct the scope now that we know the owner's id