Ticket #7096: has_one_dependent_destroy_on_reassign.diff
| File has_one_dependent_destroy_on_reassign.diff, 3.0 kB (added by aeden, 2 years ago) |
|---|
-
test/associations_test.rb
old new 248 248 firm.save! 249 249 assert_nothing_raised { firm.destroy } 250 250 end 251 252 def test_destroying_removes_dependent_from_db 253 tw = Firm.create("name" => "GlobalMegaCorp") 254 acct = tw.create_account("credit_limit" => 1000) 255 assert_nothing_raised { Account.find(acct.id) } 256 tw.destroy 257 assert_raises(ActiveRecord::RecordNotFound) { 258 Account.find(acct.id) 259 } 260 end 251 261 262 def test_reassignment_removes_old_dependent_from_db 263 tw = Firm.create("name" => "GlobalMegaCorp") 264 first_dependent = tw.create_account("credit_limit" => 1000) 265 second_dependent = tw.create_account("credit_limit" => 2000) 266 tw.save! 267 assert_raises(ActiveRecord::RecordNotFound) { 268 Account.find(first_dependent.id) 269 } 270 end 271 252 272 def test_succesful_build_association 253 273 firm = Firm.new("name" => "GlobalMegaCorp") 254 274 firm.save -
lib/active_record/associations/has_one_association.rb
old new 6 6 construct_sql 7 7 end 8 8 9 # Create the associated model instance, persisting it to the database 9 10 def create(attrs = {}, replace_existing = true) 10 new_record(replace_existing ) { |klass| klass.create(attrs) }11 new_record(replace_existing, false) { |klass| klass.create(attrs) } 11 12 end 12 13 14 # Create the associated mode instance, persisting it to the database 13 15 def create!(attrs = {}, replace_existing = true) 14 new_record(replace_existing ) { |klass| klass.create!(attrs) }16 new_record(replace_existing, false) { |klass| klass.create!(attrs) } 15 17 end 16 18 19 # Build the associated model instance, but do not persist it to the database 17 20 def build(attrs = {}, replace_existing = true) 18 new_record(replace_existing ) { |klass| klass.new(attrs) }21 new_record(replace_existing, true) { |klass| klass.new(attrs) } 19 22 end 20 23 21 24 def replace(obj, dont_save = false) … … 75 78 { :create => create_scoping } 76 79 end 77 80 78 def new_record(replace_existing )81 def new_record(replace_existing, dont_save=true) 79 82 # make sure we load the target first, if we plan on replacing the existing 80 83 # instance. Otherwise, if the target has not previously been loaded 81 84 # elsewhere, the instance we create will get orphaned. … … 83 86 record = @reflection.klass.with_scope(:create => construct_scope[:create]) { yield @reflection.klass } 84 87 85 88 if replace_existing 86 replace(record, true)89 replace(record, dont_save) 87 90 else 88 91 record[@reflection.primary_key_name] = @owner.id unless @owner.new_record? 89 92 self.target = record