has_one_associations_test.rb 20.0 KB
Newer Older
1
require "cases/helper"
2
require 'models/developer'
A
Arun Agrawal 已提交
3
require 'models/computer'
4 5
require 'models/project'
require 'models/company'
6 7
require 'models/ship'
require 'models/pirate'
8
require 'models/car'
9
require 'models/bulb'
10
require 'models/author'
11
require 'models/image'
12
require 'models/post'
13 14

class HasOneAssociationsTest < ActiveRecord::TestCase
15
  self.use_transactional_tests = false unless supports_savepoints?
16
  fixtures :accounts, :companies, :developers, :projects, :developers_projects, :ships, :pirates
17 18 19 20 21 22 23 24 25

  def setup
    Account.destroyed_account_ids.clear
  end

  def test_has_one
    assert_equal companies(:first_firm).account, Account.find(1)
    assert_equal Account.find(1).credit_limit, companies(:first_firm).account.credit_limit
  end
26

27 28 29 30 31 32 33
  def test_has_one_does_not_use_order_by
    ActiveRecord::SQLCounter.clear_log
    companies(:first_firm).account
  ensure
    assert ActiveRecord::SQLCounter.log_all.all? { |sql| /order by/i !~ sql }, 'ORDER BY was used in the query'
  end

34 35 36 37 38
  def test_has_one_cache_nils
    firm = companies(:another_firm)
    assert_queries(1) { assert_nil firm.account }
    assert_queries(0) { assert_nil firm.account }

39
    firms = Firm.all.merge!(:includes => :account).to_a
40 41 42
    assert_queries(0) { firms.each(&:account) }
  end

43 44
  def test_with_select
    assert_equal Firm.find(1).account_with_select.attributes.size, 2
45
    assert_equal Firm.all.merge!(:includes => :account_with_select).find(1).account_with_select.attributes.size, 2
46 47
  end

48 49
  def test_finding_using_primary_key
    firm = companies(:first_firm)
50
    assert_equal Account.find_by_firm_id(firm.id), firm.account
51 52 53
    firm.firm_id = companies(:rails_core).id
    assert_equal accounts(:rails_core_account), firm.account_using_primary_key
  end
54 55 56 57

  def test_update_with_foreign_and_primary_keys
    firm = companies(:first_firm)
    account = firm.account_using_foreign_and_primary_keys
58
    assert_equal Account.find_by_firm_name(firm.name), account
59 60 61 62
    firm.save
    firm.reload
    assert_equal account, firm.account_using_foreign_and_primary_keys
  end
63

64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
  def test_can_marshal_has_one_association_with_nil_target
    firm = Firm.new
    assert_nothing_raised do
      assert_equal firm.attributes, Marshal.load(Marshal.dump(firm)).attributes
    end

    firm.account
    assert_nothing_raised do
      assert_equal firm.attributes, Marshal.load(Marshal.dump(firm)).attributes
    end
  end

  def test_proxy_assignment
    company = companies(:first_firm)
    assert_nothing_raised { company.account = company.account }
  end

  def test_type_mismatch
82 83
    assert_raise(ActiveRecord::AssociationTypeMismatch) { companies(:first_firm).account = 1 }
    assert_raise(ActiveRecord::AssociationTypeMismatch) { companies(:first_firm).account = Project.find(1) }
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
  end

  def test_natural_assignment
    apple = Firm.create("name" => "Apple")
    citibank = Account.create("credit_limit" => 10)
    apple.account = citibank
    assert_equal apple.id, citibank.firm_id
  end

  def test_natural_assignment_to_nil
    old_account_id = companies(:first_firm).account.id
    companies(:first_firm).account = nil
    companies(:first_firm).save
    assert_nil companies(:first_firm).account
    # account is dependent, therefore is destroyed when reference to owner is lost
99
    assert_raise(ActiveRecord::RecordNotFound) { Account.find(old_account_id) }
100 101
  end

102 103 104
  def test_nullification_on_association_change
    firm = companies(:rails_core)
    old_account_id = firm.account.id
105
    firm.account = Account.new(:credit_limit => 5)
106 107 108 109
    # account is dependent with nullify, therefore its firm_id should be nil
    assert_nil Account.find(old_account_id).firm_id
  end

110 111 112 113 114 115 116 117
  def test_nullification_on_destroyed_association
    developer = Developer.create!(name: "Someone")
    ship = Ship.create!(name: "Planet Caravan", developer: developer)
    ship.destroy
    assert !ship.persisted?
    assert !developer.persisted?
  end

118 119 120 121 122 123 124 125 126
  def test_natural_assignment_to_nil_after_destroy
    firm = companies(:rails_core)
    old_account_id = firm.account.id
    firm.account.destroy
    firm.account = nil
    assert_nil companies(:rails_core).account
    assert_raise(ActiveRecord::RecordNotFound) { Account.find(old_account_id) }
  end

127
  def test_association_change_calls_delete
128
    companies(:first_firm).deletable_account = Account.new(:credit_limit => 5)
129 130 131 132
    assert_equal [], Account.destroyed_account_ids[companies(:first_firm).id]
  end

  def test_association_change_calls_destroy
133
    companies(:first_firm).account = Account.new(:credit_limit => 5)
134 135 136
    assert_equal [companies(:first_firm).id], Account.destroyed_account_ids[companies(:first_firm).id]
  end

137 138 139 140 141 142 143 144 145 146
  def test_natural_assignment_to_already_associated_record
    company = companies(:first_firm)
    account = accounts(:signals37)
    assert_equal company.account, account
    company.account = account
    company.reload
    account.reload
    assert_equal company.account, account
  end

147 148 149 150
  def test_dependence
    num_accounts = Account.count

    firm = Firm.find(1)
151
    assert_not_nil firm.account
152 153 154 155 156 157 158 159 160 161 162 163
    account_id = firm.account.id
    assert_equal [], Account.destroyed_account_ids[firm.id]

    firm.destroy
    assert_equal num_accounts - 1, Account.count
    assert_equal [account_id], Account.destroyed_account_ids[firm.id]
  end

  def test_exclusive_dependence
    num_accounts = Account.count

    firm = ExclusivelyDependentFirm.find(9)
164
    assert_not_nil firm.account
165 166 167 168 169 170 171 172 173 174 175 176 177
    assert_equal [], Account.destroyed_account_ids[firm.id]

    firm.destroy
    assert_equal num_accounts - 1, Account.count
    assert_equal [], Account.destroyed_account_ids[firm.id]
  end

  def test_dependence_with_nil_associate
    firm = DependentFirm.new(:name => 'nullify')
    firm.save!
    assert_nothing_raised { firm.destroy }
  end

178 179
  def test_restrict_with_exception
    firm = RestrictedWithExceptionFirm.create!(:name => 'restrict')
180 181 182 183
    firm.create_account(:credit_limit => 10)

    assert_not_nil firm.account

184 185
    assert_raise(ActiveRecord::DeleteRestrictionError) { firm.destroy }
    assert RestrictedWithExceptionFirm.exists?(:name => 'restrict')
186
    assert firm.account.present?
187 188
  end

189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
  def test_restrict_with_error_is_deprecated_using_key_one
    I18n.backend = I18n::Backend::Simple.new
    I18n.backend.store_translations :en, activerecord: { errors: { messages: { restrict_dependent_destroy: { one: 'message for deprecated key' } } } }

    firm = RestrictedWithErrorFirm.create!(name: 'restrict')
    firm.create_account(credit_limit: 10)

    assert_not_nil firm.account

    assert_deprecated { firm.destroy }

    assert !firm.errors.empty?
    assert_equal 'message for deprecated key', firm.errors[:base].first
    assert RestrictedWithErrorFirm.exists?(name: 'restrict')
    assert firm.account.present?
  ensure
    I18n.backend.reload!
  end

208 209
  def test_restrict_with_error
    firm = RestrictedWithErrorFirm.create!(:name => 'restrict')
210 211 212 213 214 215 216
    firm.create_account(:credit_limit => 10)

    assert_not_nil firm.account

    firm.destroy

    assert !firm.errors.empty?
217 218
    assert_equal "Cannot delete record because a dependent account exists", firm.errors[:base].first
    assert RestrictedWithErrorFirm.exists?(:name => 'restrict')
219 220 221
    assert firm.account.present?
  end

222 223 224
  def test_restrict_with_error_with_locale
    I18n.backend = I18n::Backend::Simple.new
    I18n.backend.store_translations 'en', activerecord: {attributes: {restricted_with_error_firm: {account: 'firm account'}}}
225 226
    firm = RestrictedWithErrorFirm.create!(name: 'restrict')
    firm.create_account(credit_limit: 10)
227 228 229 230 231 232 233

    assert_not_nil firm.account

    firm.destroy

    assert !firm.errors.empty?
    assert_equal "Cannot delete record because a dependent firm account exists", firm.errors[:base].first
234
    assert RestrictedWithErrorFirm.exists?(name: 'restrict')
235 236 237 238 239
    assert firm.account.present?
  ensure
    I18n.backend.reload!
  end

240
  def test_successful_build_association
241 242 243 244 245 246 247 248
    firm = Firm.new("name" => "GlobalMegaCorp")
    firm.save

    account = firm.build_account("credit_limit" => 1000)
    assert account.save
    assert_equal account, firm.account
  end

249
  def test_build_association_dont_create_transaction
250
    assert_no_queries(ignore_none: false) {
251 252 253 254
      Firm.new.build_account
    }
  end

255 256 257
  def test_building_the_associated_object_with_implicit_sti_base_class
    firm = DependentFirm.new
    company = firm.build_company
258
    assert_kind_of Company, company, "Expected #{company.class} to be a Company"
259 260 261 262 263
  end

  def test_building_the_associated_object_with_explicit_sti_base_class
    firm = DependentFirm.new
    company = firm.build_company(:type => "Company")
264
    assert_kind_of Company, company, "Expected #{company.class} to be a Company"
265 266 267 268 269
  end

  def test_building_the_associated_object_with_sti_subclass
    firm = DependentFirm.new
    company = firm.build_company(:type => "Client")
270
    assert_kind_of Client, company, "Expected #{company.class} to be a Client"
271 272 273 274 275 276 277 278 279 280 281 282
  end

  def test_building_the_associated_object_with_an_invalid_type
    firm = DependentFirm.new
    assert_raise(ActiveRecord::SubclassNotFound) { firm.build_company(:type => "Invalid") }
  end

  def test_building_the_associated_object_with_an_unrelated_type
    firm = DependentFirm.new
    assert_raise(ActiveRecord::SubclassNotFound) { firm.build_company(:type => "Account") }
  end

283 284
  def test_build_and_create_should_not_happen_within_scope
    pirate = pirates(:blackbeard)
285
    scope = pirate.association(:foo_bulb).scope.where_values_hash
286

287
    bulb = pirate.build_foo_bulb
288
    assert_not_equal scope, bulb.scope_after_initialize.where_values_hash
289

290
    bulb = pirate.create_foo_bulb
291
    assert_not_equal scope, bulb.scope_after_initialize.where_values_hash
292

293
    bulb = pirate.create_foo_bulb!
294
    assert_not_equal scope, bulb.scope_after_initialize.where_values_hash
295 296
  end

297 298 299 300 301 302
  def test_create_association
    firm = Firm.create(:name => "GlobalMegaCorp")
    account = firm.create_account(:credit_limit => 1000)
    assert_equal account, firm.reload.account
  end

303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
  def test_create_association_with_bang
    firm = Firm.create(:name => "GlobalMegaCorp")
    account = firm.create_account!(:credit_limit => 1000)
    assert_equal account, firm.reload.account
  end

  def test_create_association_with_bang_failing
    firm = Firm.create(:name => "GlobalMegaCorp")
    assert_raise ActiveRecord::RecordInvalid do
      firm.create_account!
    end
    account = firm.account
    assert_not_nil account
    account.credit_limit = 5
    account.save
    assert_equal account, firm.reload.account
  end

321 322 323
  def test_create_with_inexistent_foreign_key_failing
    firm = Firm.create(name: 'GlobalMegaCorp')

R
Robin Dupret 已提交
324
    assert_raises(ActiveRecord::UnknownAttributeError) do
325 326 327 328
      firm.create_account_with_inexistent_foreign_key
    end
  end

329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
  def test_build
    firm = Firm.new("name" => "GlobalMegaCorp")
    firm.save

    firm.account = account = Account.new("credit_limit" => 1000)
    assert_equal account, firm.account
    assert account.save
    assert_equal account, firm.account
  end

  def test_create
    firm = Firm.new("name" => "GlobalMegaCorp")
    firm.save
    firm.account = account = Account.create("credit_limit" => 1000)
    assert_equal account, firm.account
  end

  def test_create_before_save
    firm = Firm.new("name" => "GlobalMegaCorp")
    firm.account = account = Account.create("credit_limit" => 1000)
    assert_equal account, firm.account
  end

  def test_dependence_with_missing_association
    Account.destroy_all
    firm = Firm.find(1)
355
    assert_nil firm.account
356 357 358 359 360
    firm.destroy
  end

  def test_dependence_with_missing_association_and_nullify
    Account.destroy_all
361
    firm = DependentFirm.first
362
    assert_nil firm.account
363 364 365
    firm.destroy
  end

366
  def test_finding_with_interpolated_condition
367
    firm = Firm.first
368 369 370 371 372 373
    superior = firm.clients.create(:name => 'SuperiorCo')
    superior.rating = 10
    superior.save
    assert_equal 10, firm.clients_with_interpolated_conditions.first.rating
  end

374 375 376
  def test_assignment_before_child_saved
    firm = Firm.find(1)
    firm.account = a = Account.new("credit_limit" => 1000)
377
    assert a.persisted?
378 379
    assert_equal a, firm.account
    assert_equal a, firm.account
380 381
    firm.association(:account).reload
    assert_equal a, firm.account
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
  end

  def test_save_still_works_after_accessing_nil_has_one
    jp = Company.new :name => 'Jaded Pixel'
    jp.dummy_account.nil?

    assert_nothing_raised do
      jp.save!
    end
  end

  def test_cant_save_readonly_association
    assert_raise(ActiveRecord::ReadOnlyRecord) { companies(:first_firm).readonly_account.save!  }
    assert companies(:first_firm).readonly_account.readonly?
  end

398
  def test_has_one_proxy_should_not_respond_to_private_methods
399 400
    assert_raise(NoMethodError) { accounts(:signals37).private_method }
    assert_raise(NoMethodError) { companies(:first_firm).account.private_method }
401 402 403 404 405 406 407
  end

  def test_has_one_proxy_should_respond_to_private_methods_via_send
    accounts(:signals37).send(:private_method)
    companies(:first_firm).account.send(:private_method)
  end

408 409 410 411 412 413
  def test_save_of_record_with_loaded_has_one
    @firm = companies(:first_firm)
    assert_not_nil @firm.account

    assert_nothing_raised do
      Firm.find(@firm.id).save!
414
      Firm.all.merge!(:includes => :account).find(@firm.id).save!
415 416 417 418 419 420
    end

    @firm.account.destroy

    assert_nothing_raised do
      Firm.find(@firm.id).save!
421
      Firm.all.merge!(:includes => :account).find(@firm.id).save!
422 423
    end
  end
424 425 426 427 428 429 430 431 432

  def test_build_respects_hash_condition
    account = companies(:first_firm).build_account_limit_500_with_hash_conditions
    assert account.save
    assert_equal 500, account.credit_limit
  end

  def test_create_respects_hash_condition
    account = companies(:first_firm).create_account_limit_500_with_hash_conditions
433
    assert       account.persisted?
434 435
    assert_equal 500, account.credit_limit
  end
436 437 438 439 440

  def test_attributes_are_being_set_when_initialized_from_has_one_association_with_where_clause
    new_account = companies(:first_firm).build_account(:firm_name => 'Account')
    assert_equal new_account.firm_name, "Account"
  end
441 442 443

  def test_creation_failure_without_dependent_option
    pirate = pirates(:blackbeard)
444
    orig_ship = pirate.ship
445 446 447 448 449 450 451 452 453 454 455 456

    assert_equal ships(:black_pearl), orig_ship
    new_ship = pirate.create_ship
    assert_not_equal ships(:black_pearl), new_ship
    assert_equal new_ship, pirate.ship
    assert new_ship.new_record?
    assert_nil orig_ship.pirate_id
    assert !orig_ship.changed? # check it was saved
  end

  def test_creation_failure_with_dependent_option
    pirate = pirates(:blackbeard).becomes(DestructivePirate)
457
    orig_ship = pirate.dependent_ship
458 459 460 461 462

    new_ship = pirate.create_dependent_ship
    assert new_ship.new_record?
    assert orig_ship.destroyed?
  end
463

464 465 466 467
  def test_creation_failure_due_to_new_record_should_raise_error
    pirate = pirates(:redbeard)
    new_ship = Ship.new

468
    error = assert_raise(ActiveRecord::RecordNotSaved) do
469 470
      pirate.ship = new_ship
    end
471 472

    assert_equal "Failed to save the new associated ship.", error.message
473 474 475 476
    assert_nil pirate.ship
    assert_nil new_ship.pirate_id
  end

477 478 479 480 481
  def test_replacement_failure_due_to_existing_record_should_raise_error
    pirate = pirates(:blackbeard)
    pirate.ship.name = nil

    assert !pirate.ship.valid?
482
    error = assert_raise(ActiveRecord::RecordNotSaved) do
483 484
      pirate.ship = ships(:interceptor)
    end
485

486 487
    assert_equal ships(:black_pearl), pirate.ship
    assert_equal pirate.id, pirate.ship.pirate_id
488 489
    assert_equal "Failed to remove the existing associated ship. " +
                 "The record failed to save after its foreign key was set to nil.", error.message
490
  end
491 492 493 494 495

  def test_replacement_failure_due_to_new_record_should_raise_error
    pirate = pirates(:blackbeard)
    new_ship = Ship.new

496
    error = assert_raise(ActiveRecord::RecordNotSaved) do
497 498
      pirate.ship = new_ship
    end
499 500

    assert_equal "Failed to save the new associated ship.", error.message
501 502 503 504
    assert_equal ships(:black_pearl), pirate.ship
    assert_equal pirate.id, pirate.ship.pirate_id
    assert_equal pirate.id, ships(:black_pearl).reload.pirate_id
    assert_nil new_ship.pirate_id
505
  end
506

507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
  def test_association_keys_bypass_attribute_protection
    car = Car.create(:name => 'honda')

    bulb = car.build_bulb
    assert_equal car.id, bulb.car_id

    bulb = car.build_bulb :car_id => car.id + 1
    assert_equal car.id, bulb.car_id

    bulb = car.create_bulb
    assert_equal car.id, bulb.car_id

    bulb = car.create_bulb :car_id => car.id + 1
    assert_equal car.id, bulb.car_id
  end

523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
  def test_association_protect_foreign_key
    pirate = Pirate.create!(:catchphrase => "Don' botharrr talkin' like one, savvy?")

    ship = pirate.build_ship
    assert_equal pirate.id, ship.pirate_id

    ship = pirate.build_ship :pirate_id => pirate.id + 1
    assert_equal pirate.id, ship.pirate_id

    ship = pirate.create_ship
    assert_equal pirate.id, ship.pirate_id

    ship = pirate.create_ship :pirate_id => pirate.id + 1
    assert_equal pirate.id, ship.pirate_id
  end

539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
  def test_build_with_block
    car = Car.create(:name => 'honda')

    bulb = car.build_bulb{ |b| b.color = 'Red' }
    assert_equal 'RED!', bulb.color
  end

  def test_create_with_block
    car = Car.create(:name => 'honda')

    bulb = car.create_bulb{ |b| b.color = 'Red' }
    assert_equal 'RED!', bulb.color
  end

  def test_create_bang_with_block
    car = Car.create(:name => 'honda')

    bulb = car.create_bulb!{ |b| b.color = 'Red' }
    assert_equal 'RED!', bulb.color
  end
559 560 561 562 563 564 565

  def test_association_attributes_are_available_to_after_initialize
    car = Car.create(:name => 'honda')
    bulb = car.create_bulb

    assert_equal car.id, bulb.attributes_after_initialize['car_id']
  end
566

567 568 569 570 571 572 573 574 575 576 577
  def test_has_one_transaction
    company = companies(:first_firm)
    account = Account.find(1)

    company.account # force loading
    assert_no_queries { company.account = account }

    company.account = nil
    assert_no_queries { company.account = nil }
    account = Account.find(2)
    assert_queries { company.account = account }
578 579

    assert_no_queries { Firm.new.account = account }
580
  end
581

C
Carlos Antonio da Silva 已提交
582
  def test_has_one_assignment_dont_trigger_save_on_change_of_same_object
583 584 585 586 587 588
    pirate = Pirate.create!(catchphrase: "Don' botharrr talkin' like one, savvy?")
    ship = pirate.build_ship(name: 'old name')
    ship.save!

    ship.name = 'new name'
    assert ship.changed?
589 590 591 592 593 594 595 596 597 598 599 600 601 602
    assert_queries(1) do
      # One query for updating name, not triggering query for updating pirate_id
      pirate.ship = ship
    end

    assert_equal 'new name', pirate.ship.reload.name
  end

  def test_has_one_assignment_triggers_save_on_change_on_replacing_object
    pirate = Pirate.create!(catchphrase: "Don' botharrr talkin' like one, savvy?")
    ship = pirate.build_ship(name: 'old name')
    ship.save!

    new_ship = Ship.create(name: 'new name')
603 604
    assert_queries(2) do
      # One query for updating name and second query for updating pirate_id
605
      pirate.ship = new_ship
606 607 608 609 610
    end

    assert_equal 'new name', pirate.ship.reload.name
  end

611 612 613 614 615 616 617 618 619 620 621
  def test_has_one_autosave_with_primary_key_manually_set
    post = Post.create(id: 1234, title: "Some title", body: 'Some content')
    author = Author.new(id: 33, name: 'Hank Moody')

    author.post = post
    author.save
    author.reload

    assert_not_nil author.post
    assert_equal author.post, post
  end
622

623 624 625
  def test_has_one_loading_for_new_record
    post = Post.create!(author_id: 42, title: 'foo', body: 'bar')
    author = Author.new(id: 42)
626
    assert_equal post, author.post
627 628
  end

629 630 631 632 633 634 635
  def test_has_one_relationship_cannot_have_a_counter_cache
    assert_raise(ArgumentError) do
      Class.new(ActiveRecord::Base) do
        has_one :thing, counter_cache: true
      end
    end
  end
636

637 638 639 640 641 642 643 644 645 646
  def test_with_polymorphic_has_one_with_custom_columns_name
    post = Post.create! :title => 'foo', :body => 'bar'
    image = Image.create!

    post.main_image = image
    post.reload

    assert_equal image, post.main_image
  end

647 648 649 650 651 652 653 654 655
  test 'dangerous association name raises ArgumentError' do
    [:errors, 'errors', :save, 'save'].each do |name|
      assert_raises(ArgumentError, "Association #{name} should not be allowed") do
        Class.new(ActiveRecord::Base) do
          has_one name
        end
      end
    end
  end
656 657 658 659 660 661

  def test_association_force_reload_with_only_true_is_deprecated
    firm = Firm.find(1)

    assert_deprecated { firm.account(true) }
  end
662
end