Skip to content
This repository
Browse code

Don't add non-new records back to the target array after loading targ…

…ets on associations, as that makes destroy_all destroy any created records that don't match the scope destroy_all is called on

Signed-off-by: Michael Koziarski <michael@koziarski.com>
  • Loading branch information...
commit 0fee3592786da833bcfbe20afc3a9483118c3c12 1 parent e0eb8e9
Will Bryant authored NZKoz committed
2  activerecord/lib/active_record/associations/association_collection.rb
@@ -361,7 +361,7 @@ def load_target
361 361
                     else
362 362
                       f
363 363
                     end
364  
-                  end + @target
  364
+                  end + @target.find_all {|t| t.new_record?}
365 365
                 else
366 366
                   @target = find_target
367 367
                 end
11  activerecord/test/cases/associations/has_many_associations_test.rb
@@ -866,6 +866,17 @@ def test_destroy_all
866 866
     assert companies(:first_firm).clients_of_firm(true).empty?, "37signals has no clients after destroy all and refresh"
867 867
   end
868 868
 
  869
+  def test_destroy_all_with_creates_and_scope_that_doesnt_match_created_records
  870
+    company = companies(:first_firm)
  871
+    unloaded_client_matching_scope = companies(:second_client)
  872
+    created_client_matching_scope = company.clients_of_firm.create!(:name => "Somesoft")
  873
+    created_client_not_matching_scope = company.clients_of_firm.create!(:name => "OtherCo")
  874
+    destroyed = company.clients_of_firm.with_oft_in_name.destroy_all
  875
+    assert destroyed.include?(unloaded_client_matching_scope), "unloaded clients matching the scope destroy_all on should have been destroyed"
  876
+    assert destroyed.include?(created_client_matching_scope), "loaded clients matching the scope destroy_all on should have been destroyed"
  877
+    assert !destroyed.include?(created_client_not_matching_scope), "loaded clients not matching the scope destroy_all on should not have been destroyed"
  878
+  end
  879
+
869 880
   def test_dependence
870 881
     firm = companies(:first_firm)
871 882
     assert_equal 2, firm.clients.size
2  activerecord/test/models/company.rb
@@ -12,6 +12,8 @@ class Company < AbstractCompany
12 12
   has_many :contracts
13 13
   has_many :developers, :through => :contracts
14 14
 
  15
+  named_scope :with_oft_in_name, :conditions => "name LIKE '%oft%'"
  16
+
15 17
   def arbitrary_method
16 18
     "I am Jack's profound disappointment"
17 19
   end

0 notes on commit 0fee359

Please sign in to comment.
Something went wrong with that request. Please try again.