belongs_to_associations_test.rb 35.5 KB
Newer Older
1 2
# frozen_string_literal: true

3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
require "cases/helper"
require "models/developer"
require "models/project"
require "models/company"
require "models/topic"
require "models/reply"
require "models/computer"
require "models/post"
require "models/author"
require "models/tag"
require "models/tagging"
require "models/comment"
require "models/sponsor"
require "models/member"
require "models/essay"
require "models/toy"
require "models/invoice"
require "models/line_item"
require "models/column"
require "models/record"
require "models/admin"
require "models/admin/user"
require "models/ship"
require "models/treasure"
require "models/parrot"
28 29 30

class BelongsToAssociationsTest < ActiveRecord::TestCase
  fixtures :accounts, :companies, :developers, :projects, :topics,
31
           :developers_projects, :computers, :authors, :author_addresses,
32
           :posts, :tags, :taggings, :comments, :sponsors, :members
33 34

  def test_belongs_to
35 36 37
    firm = Client.find(3).firm
    assert_not_nil firm
    assert_equal companies(:first_firm).name, firm.name
38 39
  end

40 41 42 43
  def test_missing_attribute_error_is_raised_when_no_foreign_key_attribute
    assert_raises(ActiveModel::MissingAttributeError) { Client.select(:id).first.firm }
  end

44 45 46 47
  def test_belongs_to_does_not_use_order_by
    ActiveRecord::SQLCounter.clear_log
    Client.find(3).firm
  ensure
48
    assert ActiveRecord::SQLCounter.log_all.all? { |sql| /order by/i !~ sql }, "ORDER BY was used in the query"
49 50
  end

51
  def test_belongs_to_with_primary_key
52
    client = Client.create(name: "Primary key client", firm_name: companies(:first_firm).name)
53 54 55
    assert_equal companies(:first_firm).name, client.firm_with_primary_key.name
  end

56 57
  def test_belongs_to_with_primary_key_joins_on_correct_column
    sql = Client.joins(:firm_with_primary_key).to_sql
A
Abdelkader Boudih 已提交
58
    if current_adapter?(:Mysql2Adapter)
59 60
      assert_no_match(/`firm_with_primary_keys_companies`\.`id`/, sql)
      assert_match(/`firm_with_primary_keys_companies`\.`name`/, sql)
61 62 63 64
    elsif current_adapter?(:OracleAdapter)
      # on Oracle aliases are truncated to 30 characters and are quoted in uppercase
      assert_no_match(/"firm_with_primary_keys_compani"\."id"/i, sql)
      assert_match(/"firm_with_primary_keys_compani"\."name"/i, sql)
E
Emilio Tagua 已提交
65
    else
66 67
      assert_no_match(/"firm_with_primary_keys_companies"\."id"/, sql)
      assert_match(/"firm_with_primary_keys_companies"\."name"/, sql)
E
Emilio Tagua 已提交
68
    end
69 70
  end

71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
  def test_optional_relation
    original_value = ActiveRecord::Base.belongs_to_required_by_default
    ActiveRecord::Base.belongs_to_required_by_default = true

    model = Class.new(ActiveRecord::Base) do
      self.table_name = "accounts"
      def self.name; "Temp"; end
      belongs_to :company, optional: true
    end

    account = model.new
    assert account.valid?
  ensure
    ActiveRecord::Base.belongs_to_required_by_default = original_value
  end

  def test_not_optional_relation
    original_value = ActiveRecord::Base.belongs_to_required_by_default
    ActiveRecord::Base.belongs_to_required_by_default = true

    model = Class.new(ActiveRecord::Base) do
      self.table_name = "accounts"
      def self.name; "Temp"; end
      belongs_to :company, optional: false
    end

    account = model.new
98
    assert_not account.valid?
99
    assert_equal [{ error: :blank }], account.errors.details[:company]
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
  ensure
    ActiveRecord::Base.belongs_to_required_by_default = original_value
  end

  def test_required_belongs_to_config
    original_value = ActiveRecord::Base.belongs_to_required_by_default
    ActiveRecord::Base.belongs_to_required_by_default = true

    model = Class.new(ActiveRecord::Base) do
      self.table_name = "accounts"
      def self.name; "Temp"; end
      belongs_to :company
    end

    account = model.new
115
    assert_not account.valid?
116
    assert_equal [{ error: :blank }], account.errors.details[:company]
117 118 119 120
  ensure
    ActiveRecord::Base.belongs_to_required_by_default = original_value
  end

121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
  def test_default
    david = developers(:david)
    jamis = developers(:jamis)

    model = Class.new(ActiveRecord::Base) do
      self.table_name = "ships"
      def self.name; "Temp"; end
      belongs_to :developer, default: -> { david }
    end

    ship = model.create!
    assert_equal david, ship.developer

    ship = model.create!(developer: jamis)
    assert_equal jamis, ship.developer

    ship.update!(developer: nil)
    assert_equal david, ship.developer
  end

141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
  def test_default_with_lambda
    model = Class.new(ActiveRecord::Base) do
      self.table_name = "ships"
      def self.name; "Temp"; end
      belongs_to :developer, default: -> { default_developer }

      def default_developer
        Developer.first
      end
    end

    ship = model.create!
    assert_equal developers(:david), ship.developer

    ship = model.create!(developer: developers(:jamis))
    assert_equal developers(:jamis), ship.developer
  end

159 160 161 162
  def test_default_scope_on_relations_is_not_cached
    counter = 0

    comments = Class.new(ActiveRecord::Base) {
163 164
      self.table_name = "comments"
      self.inheritance_column = "not_there"
165 166

      posts = Class.new(ActiveRecord::Base) {
167 168
        self.table_name = "posts"
        self.inheritance_column = "not_there"
169 170 171

        default_scope -> {
          counter += 1
172
          where("id = :inc", inc: counter)
173 174
        }

175
        has_many :comments, anonymous_class: comments
176
      }
177
      belongs_to :post, anonymous_class: posts, inverse_of: false
178 179 180 181 182 183 184 185 186 187
    }

    assert_equal 0, counter
    comment = comments.first
    assert_equal 0, counter
    sql = capture_sql { comment.post }
    comment.reload
    assert_not_equal sql, capture_sql { comment.post }
  end

188 189 190 191 192 193 194 195 196 197
  def test_proxy_assignment
    account = Account.find(1)
    assert_nothing_raised { account.firm = account.firm }
  end

  def test_type_mismatch
    assert_raise(ActiveRecord::AssociationTypeMismatch) { Account.find(1).firm = 1 }
    assert_raise(ActiveRecord::AssociationTypeMismatch) { Account.find(1).firm = Project.find(1) }
  end

198 199 200 201 202 203 204
  def test_raises_type_mismatch_with_namespaced_class
    assert_nil defined?(Region), "This test requires that there is no top-level Region class"

    ActiveRecord::Base.connection.instance_eval do
      create_table(:admin_regions) { |t| t.string :name }
      add_column :admin_users, :region_id, :integer
    end
205 206
    Admin.const_set "RegionalUser", Class.new(Admin::User) { belongs_to(:region) }
    Admin.const_set "Region", Class.new(ActiveRecord::Base)
207 208

    e = assert_raise(ActiveRecord::AssociationTypeMismatch) {
209
      Admin::RegionalUser.new(region: "wrong value")
210
    }
211
    assert_match(/^Region\([^)]+\) expected, got "wrong value" which is an instance of String\([^)]+\)$/, e.message)
212 213 214
  ensure
    Admin.send :remove_const, "Region" if Admin.const_defined?("Region")
    Admin.send :remove_const, "RegionalUser" if Admin.const_defined?("RegionalUser")
215 216 217 218 219

    ActiveRecord::Base.connection.instance_eval do
      remove_column :admin_users, :region_id if column_exists?(:admin_users, :region_id)
      drop_table :admin_regions, if_exists: true
    end
220 221
  end

222 223 224 225 226 227 228
  def test_natural_assignment
    apple = Firm.create("name" => "Apple")
    citibank = Account.create("credit_limit" => 10)
    citibank.firm = apple
    assert_equal apple.id, citibank.firm_id
  end

229 230 231 232 233 234 235
  def test_id_assignment
    apple = Firm.create("name" => "Apple")
    citibank = Account.create("credit_limit" => 10)
    citibank.firm_id = apple
    assert_nil citibank.firm_id
  end

236 237 238 239 240 241 242
  def test_natural_assignment_with_primary_key
    apple = Firm.create("name" => "Apple")
    citibank = Client.create("name" => "Primary key client")
    citibank.firm_with_primary_key = apple
    assert_equal apple.name, citibank.firm_name
  end

243
  def test_eager_loading_with_primary_key
A
Aaron Patterson 已提交
244 245
    Firm.create("name" => "Apple")
    Client.create("name" => "Citibank", :firm_name => "Apple")
246
    citibank_result = Client.all.merge!(where: { name: "Citibank" }, includes: :firm_with_primary_key).first
247
    assert citibank_result.association(:firm_with_primary_key).loaded?
248 249
  end

250 251 252
  def test_eager_loading_with_primary_key_as_symbol
    Firm.create("name" => "Apple")
    Client.create("name" => "Citibank", :firm_name => "Apple")
253
    citibank_result = Client.all.merge!(where: { name: "Citibank" }, includes: :firm_with_primary_key_symbols).first
254
    assert citibank_result.association(:firm_with_primary_key_symbols).loaded?
255 256
  end

257 258 259 260 261 262 263 264 265
  def test_creating_the_belonging_object
    citibank = Account.create("credit_limit" => 10)
    apple    = citibank.create_firm("name" => "Apple")
    assert_equal apple, citibank.firm
    citibank.save
    citibank.reload
    assert_equal apple, citibank.firm
  end

266
  def test_creating_the_belonging_object_with_primary_key
267
    client = Client.create(name: "Primary key client")
268 269 270 271 272 273 274
    apple  = client.create_firm_with_primary_key("name" => "Apple")
    assert_equal apple, client.firm_with_primary_key
    client.save
    client.reload
    assert_equal apple, client.firm_with_primary_key
  end

275 276 277 278 279 280 281
  def test_building_the_belonging_object
    citibank = Account.create("credit_limit" => 10)
    apple    = citibank.build_firm("name" => "Apple")
    citibank.save
    assert_equal apple.id, citibank.firm_id
  end

282 283 284
  def test_building_the_belonging_object_with_implicit_sti_base_class
    account = Account.new
    company = account.build_firm
285
    assert_kind_of Company, company, "Expected #{company.class} to be a Company"
286 287 288 289
  end

  def test_building_the_belonging_object_with_explicit_sti_base_class
    account = Account.new
290
    company = account.build_firm(type: "Company")
291
    assert_kind_of Company, company, "Expected #{company.class} to be a Company"
292 293 294 295
  end

  def test_building_the_belonging_object_with_sti_subclass
    account = Account.new
296
    company = account.build_firm(type: "Firm")
297
    assert_kind_of Firm, company, "Expected #{company.class} to be a Firm"
298 299 300 301
  end

  def test_building_the_belonging_object_with_an_invalid_type
    account = Account.new
302
    assert_raise(ActiveRecord::SubclassNotFound) { account.build_firm(type: "InvalidType") }
303 304 305 306
  end

  def test_building_the_belonging_object_with_an_unrelated_type
    account = Account.new
307
    assert_raise(ActiveRecord::SubclassNotFound) { account.build_firm(type: "Account") }
308 309
  end

310
  def test_building_the_belonging_object_with_primary_key
311
    client = Client.create(name: "Primary key client")
312 313 314 315 316
    apple  = client.build_firm_with_primary_key("name" => "Apple")
    client.save
    assert_equal apple.name, client.firm_name
  end

317
  def test_create!
318 319
    client  = Client.create!(name: "Jimmy")
    account = client.create_account!(credit_limit: 10)
320 321 322 323 324 325 326 327
    assert_equal account, client.account
    assert account.persisted?
    client.save
    client.reload
    assert_equal account, client.account
  end

  def test_failing_create!
328
    client = Client.create!(name: "Jimmy")
329 330 331 332 333
    assert_raise(ActiveRecord::RecordInvalid) { client.create_account! }
    assert_not_nil client.account
    assert client.account.new_record?
  end

334 335 336 337 338 339 340 341 342 343
  def test_reloading_the_belonging_object
    odegy_account = accounts(:odegy_account)

    assert_equal "Odegy", odegy_account.firm.name
    Company.where(id: odegy_account.firm_id).update_all(name: "ODEGY")
    assert_equal "Odegy", odegy_account.firm.name

    assert_equal "ODEGY", odegy_account.reload_firm.name
  end

344 345 346 347
  def test_natural_assignment_to_nil
    client = Client.find(3)
    client.firm = nil
    client.save
348 349
    client.association(:firm).reload
    assert_nil client.firm
350 351 352
    assert_nil client.client_of
  end

353
  def test_natural_assignment_to_nil_with_primary_key
354
    client = Client.create(name: "Primary key client", firm_name: companies(:first_firm).name)
355 356
    client.firm_with_primary_key = nil
    client.save
357 358
    client.association(:firm_with_primary_key).reload
    assert_nil client.firm_with_primary_key
359 360 361
    assert_nil client.client_of
  end

362 363 364 365 366 367 368 369 370 371
  def test_with_different_class_name
    assert_equal Company.find(1).name, Company.find(3).firm_with_other_name.name
    assert_not_nil Company.find(3).firm_with_other_name, "Microsoft should have a firm"
  end

  def test_with_condition
    assert_equal Company.find(1).name, Company.find(3).firm_with_condition.name
    assert_not_nil Company.find(3).firm_with_condition, "Microsoft should have a firm"
  end

372 373 374
  def test_polymorphic_association_class
    sponsor = Sponsor.new
    assert_nil sponsor.association(:sponsorable).send(:klass)
375 376
    sponsor.association(:sponsorable).reload
    assert_nil sponsor.sponsorable
377

378
    sponsor.sponsorable_type = "" # the column doesn't have to be declared NOT NULL
379
    assert_nil sponsor.association(:sponsorable).send(:klass)
380 381
    sponsor.association(:sponsorable).reload
    assert_nil sponsor.sponsorable
382

383
    sponsor.sponsorable = Member.new name: "Bert"
384 385 386
    assert_equal Member, sponsor.association(:sponsorable).send(:klass)
  end

387 388
  def test_with_polymorphic_and_condition
    sponsor = Sponsor.create
389
    member = Member.create name: "Bert"
390 391 392 393 394 395
    sponsor.sponsorable = member

    assert_equal member, sponsor.sponsorable
    assert_nil sponsor.sponsorable_with_conditions
  end

396
  def test_with_select
J
Jon Leighton 已提交
397
    assert_equal 1, Company.find(2).firm_with_select.attributes.size
398
    assert_equal 1, Company.all.merge!(includes: :firm_with_select).find(2).firm_with_select.attributes.size
399 400
  end

401 402 403
  def test_belongs_to_without_counter_cache_option
    # Ship has a conventionally named `treasures_count` column, but the counter_cache
    # option is not given on the association.
404
    ship = Ship.create(name: "Countless")
405 406

    assert_no_difference lambda { ship.reload.treasures_count }, "treasures_count should not be changed unless counter_cache is given on the relation" do
407
      treasure = Treasure.new(name: "Gold", ship: ship)
408 409 410 411 412 413 414 415 416
      treasure.save
    end

    assert_no_difference lambda { ship.reload.treasures_count }, "treasures_count should not be changed unless counter_cache is given on the relation" do
      treasure = ship.treasures.first
      treasure.destroy
    end
  end

417 418
  def test_belongs_to_counter
    debate = Topic.create("title" => "debate")
419
    assert_equal 0, debate.read_attribute("replies_count"), "No replies yet"
420 421

    trash = debate.replies.create("title" => "blah!", "content" => "world around!")
422
    assert_equal 1, Topic.find(debate.id).read_attribute("replies_count"), "First reply created"
423 424

    trash.destroy
425
    assert_equal 0, Topic.find(debate.id).read_attribute("replies_count"), "First reply deleted"
426 427 428
  end

  def test_belongs_to_counter_with_assigning_nil
429 430
    post = Post.find(1)
    comment = Comment.find(1)
431

432 433
    assert_equal post.id, comment.post_id
    assert_equal 2, Post.find(post.id).comments.size
434

435
    comment.post = nil
436

437
    assert_equal 1, Post.find(post.id).comments.size
438 439
  end

440 441 442 443 444 445 446 447 448
  def test_belongs_to_with_primary_key_counter
    debate  = Topic.create("title" => "debate")
    debate2 = Topic.create("title" => "debate2")
    reply   = Reply.create("title" => "blah!", "content" => "world around!", "parent_title" => "debate")

    assert_equal 1, debate.reload.replies_count
    assert_equal 0, debate2.reload.replies_count

    reply.topic_with_primary_key = debate2
449

450 451
    assert_equal 0, debate.reload.replies_count
    assert_equal 1, debate2.reload.replies_count
452 453 454

    reply.topic_with_primary_key = nil

455 456
    assert_equal 0, debate.reload.replies_count
    assert_equal 0, debate2.reload.replies_count
457 458
  end

459
  def test_belongs_to_counter_with_reassigning
460 461 462 463
    topic1 = Topic.create("title" => "t1")
    topic2 = Topic.create("title" => "t2")
    reply1 = Reply.new("title" => "r1", "content" => "r1")
    reply1.topic = topic1
464

465 466 467
    assert reply1.save
    assert_equal 1, Topic.find(topic1.id).replies.size
    assert_equal 0, Topic.find(topic2.id).replies.size
468

469
    reply1.topic = Topic.find(topic2.id)
470

471
    assert_no_queries do
472
      reply1.topic = topic2
473 474
    end

475 476 477
    assert reply1.save
    assert_equal 0, Topic.find(topic1.id).replies.size
    assert_equal 1, Topic.find(topic2.id).replies.size
478

479
    reply1.topic = nil
480

481 482
    assert_equal 0, Topic.find(topic1.id).replies.size
    assert_equal 0, Topic.find(topic2.id).replies.size
483

484
    reply1.topic = topic1
485

486 487
    assert_equal 1, Topic.find(topic1.id).replies.size
    assert_equal 0, Topic.find(topic2.id).replies.size
488

489
    reply1.destroy
490

491 492
    assert_equal 0, Topic.find(topic1.id).replies.size
    assert_equal 0, Topic.find(topic2.id).replies.size
493 494
  end

495
  def test_belongs_to_reassign_with_namespaced_models_and_counters
496 497 498 499
    topic1 = Web::Topic.create("title" => "t1")
    topic2 = Web::Topic.create("title" => "t2")
    reply1 = Web::Reply.new("title" => "r1", "content" => "r1")
    reply1.topic = topic1
500

501 502 503
    assert reply1.save
    assert_equal 1, Web::Topic.find(topic1.id).replies.size
    assert_equal 0, Web::Topic.find(topic2.id).replies.size
504

505
    reply1.topic = Web::Topic.find(topic2.id)
506

507 508 509
    assert reply1.save
    assert_equal 0, Web::Topic.find(topic1.id).replies.size
    assert_equal 1, Web::Topic.find(topic2.id).replies.size
510 511
  end

512
  def test_belongs_to_counter_after_save
513 514
    topic = Topic.create!(title: "monday night")
    topic.replies.create!(title: "re: monday night", content: "football")
515 516 517 518 519 520
    assert_equal 1, Topic.find(topic.id)[:replies_count]

    topic.save!
    assert_equal 1, Topic.find(topic.id)[:replies_count]
  end

521 522 523 524 525 526 527
  def test_belongs_to_with_touch_option_on_touch
    line_item = LineItem.create!
    Invoice.create!(line_items: [line_item])

    assert_queries(1) { line_item.touch }
  end

A
Arthur Neves 已提交
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
  def test_belongs_to_with_touch_on_multiple_records
    line_item = LineItem.create!(amount: 1)
    line_item2 = LineItem.create!(amount: 2)
    Invoice.create!(line_items: [line_item, line_item2])

    assert_queries(1) do
      LineItem.transaction do
        line_item.touch
        line_item2.touch
      end
    end

    assert_queries(2) do
      line_item.touch
      line_item2.touch
    end
  end

546
  def test_belongs_to_with_touch_option_on_touch_without_updated_at_attributes
R
Rafael Mendonça França 已提交
547
    assert_not LineItem.column_names.include?("updated_at")
548 549 550 551

    line_item = LineItem.create!
    invoice = Invoice.create!(line_items: [line_item])
    initial = invoice.updated_at
552 553 554
    travel(1.second) do
      line_item.touch
    end
555

R
Rafael Mendonça França 已提交
556
    assert_not_equal initial, invoice.reload.updated_at
557 558
  end

559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
  def test_belongs_to_with_touch_option_on_touch_and_removed_parent
    line_item = LineItem.create!
    Invoice.create!(line_items: [line_item])

    line_item.invoice = nil

    assert_queries(2) { line_item.touch }
  end

  def test_belongs_to_with_touch_option_on_update
    line_item = LineItem.create!
    Invoice.create!(line_items: [line_item])

    assert_queries(2) { line_item.update amount: 10 }
  end

575 576 577 578 579 580 581
  def test_belongs_to_with_touch_option_on_empty_update
    line_item = LineItem.create!
    Invoice.create!(line_items: [line_item])

    assert_queries(0) { line_item.save }
  end

582 583 584 585 586 587 588
  def test_belongs_to_with_touch_option_on_destroy
    line_item = LineItem.create!
    Invoice.create!(line_items: [line_item])

    assert_queries(2) { line_item.destroy }
  end

589 590 591 592 593 594 595 596
  def test_belongs_to_with_touch_option_on_destroy_with_destroyed_parent
    line_item = LineItem.create!
    invoice   = Invoice.create!(line_items: [line_item])
    invoice.destroy

    assert_queries(1) { line_item.destroy }
  end

597 598 599 600 601 602 603 604 605
  def test_belongs_to_with_touch_option_on_touch_and_reassigned_parent
    line_item = LineItem.create!
    Invoice.create!(line_items: [line_item])

    line_item.invoice = Invoice.create!

    assert_queries(3) { line_item.touch }
  end

606 607 608
  def test_belongs_to_counter_after_update
    topic = Topic.create!(title: "37s")
    topic.replies.create!(title: "re: 37s", content: "rails")
609 610
    assert_equal 1, Topic.find(topic.id)[:replies_count]

611
    topic.update(title: "37signals")
612 613 614
    assert_equal 1, Topic.find(topic.id)[:replies_count]
  end

615
  def test_belongs_to_counter_when_update_columns
616 617
    topic = Topic.create!(title: "37s")
    topic.replies.create!(title: "re: 37s", content: "rails")
G
ganesh 已提交
618 619
    assert_equal 1, Topic.find(topic.id)[:replies_count]

V
Vipul A M 已提交
620
    topic.update_columns(content: "rails is wonderful")
G
ganesh 已提交
621 622 623
    assert_equal 1, Topic.find(topic.id)[:replies_count]
  end

624 625 626 627
  def test_assignment_before_child_saved
    final_cut = Client.new("name" => "Final Cut")
    firm = Firm.find(1)
    final_cut.firm = firm
628
    assert !final_cut.persisted?
629
    assert final_cut.save
630 631
    assert final_cut.persisted?
    assert firm.persisted?
632
    assert_equal firm, final_cut.firm
633 634
    final_cut.association(:firm).reload
    assert_equal firm, final_cut.firm
635 636
  end

637 638 639 640
  def test_assignment_before_child_saved_with_primary_key
    final_cut = Client.new("name" => "Final Cut")
    firm = Firm.find(1)
    final_cut.firm_with_primary_key = firm
641
    assert !final_cut.persisted?
642
    assert final_cut.save
643 644
    assert final_cut.persisted?
    assert firm.persisted?
645
    assert_equal firm, final_cut.firm_with_primary_key
646 647
    final_cut.association(:firm_with_primary_key).reload
    assert_equal firm, final_cut.firm_with_primary_key
648 649
  end

650
  def test_new_record_with_foreign_key_but_no_object
651
    client = Client.new("firm_id" => 1)
652
    assert_equal Firm.first, client.firm_with_basic_id
653 654
  end

655 656 657 658
  def test_setting_foreign_key_after_nil_target_loaded
    client = Client.new
    client.firm_with_basic_id
    client.firm_id = 1
659

660 661 662 663 664 665 666 667 668 669
    assert_equal companies(:first_firm), client.firm_with_basic_id
  end

  def test_polymorphic_setting_foreign_key_after_nil_target_loaded
    sponsor = Sponsor.new
    sponsor.sponsorable
    sponsor.sponsorable_id = 1
    sponsor.sponsorable_type = "Member"

    assert_equal members(:groucho), sponsor.sponsorable
670 671
  end

672 673
  def test_dont_find_target_when_foreign_key_is_null
    tagging = taggings(:thinking_general)
P
Paul Nikitochkin 已提交
674
    assert_queries(0) { tagging.super_tag }
675 676
  end

677 678 679 680 681 682
  def test_dont_find_target_when_saving_foreign_key_after_stale_association_loaded
    client = Client.create!(name: "Test client", firm_with_basic_id: Firm.find(1))
    client.firm_id = Firm.create!(name: "Test firm").id
    assert_queries(1) { client.save! }
  end

683 684 685 686 687 688
  def test_field_name_same_as_foreign_key
    computer = Computer.find(1)
    assert_not_nil computer.developer, ":foreign key == attribute didn't lock up" # '
  end

  def test_counter_cache
689
    topic = Topic.create title: "Zoom-zoom-zoom"
690 691
    assert_equal 0, topic[:replies_count]

692
    reply = Reply.create(title: "re: zoom", content: "speedy quick!")
693 694 695 696 697 698 699 700 701
    reply.topic = topic

    assert_equal 1, topic.reload[:replies_count]
    assert_equal 1, topic.replies.size

    topic[:replies_count] = 15
    assert_equal 15, topic.replies.size
  end

702
  def test_counter_cache_double_destroy
703
    topic = Topic.create title: "Zoom-zoom-zoom"
704 705

    5.times do
706
      topic.replies.create(title: "re: zoom", content: "speedy quick!")
707 708 709 710 711 712 713 714 715 716 717 718 719 720 721
    end

    assert_equal 5, topic.reload[:replies_count]
    assert_equal 5, topic.replies.size

    reply = topic.replies.first

    reply.destroy
    assert_equal 4, topic.reload[:replies_count]

    reply.destroy
    assert_equal 4, topic.reload[:replies_count]
    assert_equal 4, topic.replies.size
  end

722
  def test_concurrent_counter_cache_double_destroy
723
    topic = Topic.create title: "Zoom-zoom-zoom"
724 725

    5.times do
726
      topic.replies.create(title: "re: zoom", content: "speedy quick!")
727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742
    end

    assert_equal 5, topic.reload[:replies_count]
    assert_equal 5, topic.replies.size

    reply = topic.replies.first
    reply_clone = Reply.find(reply.id)

    reply.destroy
    assert_equal 4, topic.reload[:replies_count]

    reply_clone.destroy
    assert_equal 4, topic.reload[:replies_count]
    assert_equal 4, topic.replies.size
  end

743
  def test_custom_counter_cache
744
    reply = Reply.create(title: "re: zoom", content: "speedy quick!")
745 746
    assert_equal 0, reply[:replies_count]

747
    silly = SillyReply.create(title: "gaga", content: "boo-boo")
748 749 750 751 752 753 754 755 756
    silly.reply = reply

    assert_equal 1, reply.reload[:replies_count]
    assert_equal 1, reply.replies.size

    reply[:replies_count] = 17
    assert_equal 17, reply.replies.size
  end

757 758 759 760 761 762 763 764 765 766 767
  def test_replace_counter_cache
    topic = Topic.create(title: "Zoom-zoom-zoom")
    reply = Reply.create(title: "re: zoom", content: "speedy quick!")

    reply.topic = topic
    reply.save
    topic.reload

    assert_equal 1, topic.replies_count
  end

768
  def test_association_assignment_sticks
769
    post = Post.first
770

771
    author1, author2 = Author.all.merge!(limit: 2).to_a
772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792
    assert_not_nil author1
    assert_not_nil author2

    # make sure the association is loaded
    post.author

    # set the association by id, directly
    post.author_id = author2.id

    # save and reload
    post.save!
    post.reload

    # the author id of the post should be the id we set
    assert_equal post.author_id, author2.id
  end

  def test_cant_save_readonly_association
    assert_raise(ActiveRecord::ReadOnlyRecord) { companies(:first_client).readonly_firm.save! }
    assert companies(:first_client).readonly_firm.readonly?
  end
793

794
  def test_polymorphic_assignment_foreign_key_type_string
795 796 797 798 799 800 801 802 803 804 805 806
    comment = Comment.first
    comment.author   = Author.first
    comment.resource = Member.first
    comment.save

    assert_equal Comment.all.to_a,
      Comment.includes(:author).to_a

    assert_equal Comment.all.to_a,
      Comment.includes(:resource).to_a
  end

807 808 809 810 811 812
  def test_polymorphic_assignment_foreign_type_field_updating
    # should update when assigning a saved record
    sponsor = Sponsor.new
    member = Member.create
    sponsor.sponsorable = member
    assert_equal "Member", sponsor.sponsorable_type
813

814 815 816 817 818 819
    # should update when assigning a new record
    sponsor = Sponsor.new
    member = Member.new
    sponsor.sponsorable = member
    assert_equal "Member", sponsor.sponsorable_type
  end
820 821 822 823

  def test_polymorphic_assignment_with_primary_key_foreign_type_field_updating
    # should update when assigning a saved record
    essay = Essay.new
824
    writer = Author.create(name: "David")
825 826 827 828 829 830 831 832 833
    essay.writer = writer
    assert_equal "Author", essay.writer_type

    # should update when assigning a new record
    essay = Essay.new
    writer = Author.new
    essay.writer = writer
    assert_equal "Author", essay.writer_type
  end
834

835 836 837 838
  def test_polymorphic_assignment_updates_foreign_id_field_for_new_and_saved_records
    sponsor = Sponsor.new
    saved_member = Member.create
    new_member = Member.new
839

840 841
    sponsor.sponsorable = saved_member
    assert_equal saved_member.id, sponsor.sponsorable_id
842

843
    sponsor.sponsorable = new_member
844
    assert_nil sponsor.sponsorable_id
845
  end
846

847 848
  def test_assignment_updates_foreign_id_field_for_new_and_saved_records
    client = Client.new
849
    saved_firm = Firm.create name: "Saved"
850 851 852 853 854 855 856 857 858
    new_firm = Firm.new

    client.firm = saved_firm
    assert_equal saved_firm.id, client.client_of

    client.firm = new_firm
    assert_nil client.client_of
  end

859 860
  def test_polymorphic_assignment_with_primary_key_updates_foreign_id_field_for_new_and_saved_records
    essay = Essay.new
861
    saved_writer = Author.create(name: "David")
862 863 864 865 866 867
    new_writer = Author.new

    essay.writer = saved_writer
    assert_equal saved_writer.name, essay.writer_id

    essay.writer = new_writer
868
    assert_nil essay.writer_id
869 870
  end

871 872 873 874 875 876
  def test_polymorphic_assignment_with_nil
    essay = Essay.new
    assert_nil essay.writer_id
    assert_nil essay.writer_type

    essay.writer_id = 1
877
    essay.writer_type = "Author"
878 879 880 881 882 883

    essay.writer = nil
    assert_nil essay.writer_id
    assert_nil essay.writer_type
  end

884
  def test_belongs_to_proxy_should_not_respond_to_private_methods
885 886
    assert_raise(NoMethodError) { companies(:first_firm).private_method }
    assert_raise(NoMethodError) { companies(:second_client).firm.private_method }
887 888 889 890 891 892
  end

  def test_belongs_to_proxy_should_respond_to_private_methods_via_send
    companies(:first_firm).send(:private_method)
    companies(:second_client).firm.send(:private_method)
  end
893 894 895 896 897 898

  def test_save_of_record_with_loaded_belongs_to
    @account = companies(:first_firm).account

    assert_nothing_raised do
      Account.find(@account.id).save!
899
      Account.all.merge!(includes: :firm).find(@account.id).save!
900 901 902 903 904 905
    end

    @account.firm.delete

    assert_nothing_raised do
      Account.find(@account.id).save!
906
      Account.all.merge!(includes: :firm).find(@account.id).save!
907 908
    end
  end
909 910

  def test_dependent_delete_and_destroy_with_belongs_to
A
Akira Matsuda 已提交
911 912
    AuthorAddress.destroyed_author_address_ids.clear

913 914 915 916 917 918 919 920
    author_address = author_addresses(:david_address)
    author_address_extra = author_addresses(:david_address_extra)
    assert_equal [], AuthorAddress.destroyed_author_address_ids

    assert_difference "AuthorAddress.count", -2 do
      authors(:david).destroy
    end

J
Jon Leighton 已提交
921
    assert_equal [], AuthorAddress.where(id: [author_address.id, author_address_extra.id])
922 923 924
    assert_equal [author_address.id], AuthorAddress.destroyed_author_address_ids
  end

925 926
  def test_belongs_to_invalid_dependent_option_raises_exception
    error = assert_raise ArgumentError do
927
      Class.new(Author).belongs_to :special_author_address, dependent: :nullify
928
    end
929
    assert_equal error.message, "The :dependent option must be one of [:destroy, :delete], but is :nullify"
930
  end
931 932

  def test_attributes_are_being_set_when_initialized_from_belongs_to_association_with_where_clause
933
    new_firm = accounts(:signals37).build_firm(name: "Apple")
934 935
    assert_equal new_firm.name, "Apple"
  end
936

937
  def test_attributes_are_set_without_error_when_initialized_from_belongs_to_association_with_array_in_where_clause
938
    new_account = Account.where(credit_limit: [ 50, 60 ]).new
939 940 941
    assert_nil new_account.credit_limit
  end

942
  def test_reassigning_the_parent_id_updates_the_object
943
    client = companies(:second_client)
944

945 946 947 948
    client.firm
    client.firm_with_condition
    firm_proxy                = client.send(:association_instance_get, :firm)
    firm_with_condition_proxy = client.send(:association_instance_get, :firm_with_condition)
949

950 951 952 953 954 955 956 957 958 959 960
    assert !firm_proxy.stale_target?
    assert !firm_with_condition_proxy.stale_target?
    assert_equal companies(:first_firm), client.firm
    assert_equal companies(:first_firm), client.firm_with_condition

    client.client_of = companies(:another_firm).id

    assert firm_proxy.stale_target?
    assert firm_with_condition_proxy.stale_target?
    assert_equal companies(:another_firm), client.firm
    assert_equal companies(:another_firm), client.firm_with_condition
961 962 963
  end

  def test_polymorphic_reassignment_of_associated_id_updates_the_object
964 965 966 967 968 969 970
    sponsor = sponsors(:moustache_club_sponsor_for_groucho)

    sponsor.sponsorable
    proxy = sponsor.send(:association_instance_get, :sponsorable)

    assert !proxy.stale_target?
    assert_equal members(:groucho), sponsor.sponsorable
971

972
    sponsor.sponsorable_id = members(:some_other_guy).id
973

974 975
    assert proxy.stale_target?
    assert_equal members(:some_other_guy), sponsor.sponsorable
976 977 978
  end

  def test_polymorphic_reassignment_of_associated_type_updates_the_object
979
    sponsor = sponsors(:moustache_club_sponsor_for_groucho)
980

981 982
    sponsor.sponsorable
    proxy = sponsor.send(:association_instance_get, :sponsorable)
983

984 985 986
    assert !proxy.stale_target?
    assert_equal members(:groucho), sponsor.sponsorable

987
    sponsor.sponsorable_type = "Firm"
988

989 990 991
    assert proxy.stale_target?
    assert_equal companies(:first_firm), sponsor.sponsorable
  end
992 993 994

  def test_reloading_association_with_key_change
    client = companies(:second_client)
995
    firm = client.association(:firm)
996 997

    client.firm = companies(:another_firm)
998 999
    firm.reload
    assert_equal companies(:another_firm), firm.target
1000 1001

    client.client_of = companies(:first_firm).id
1002 1003
    firm.reload
    assert_equal companies(:first_firm), firm.target
1004
  end
1005 1006

  def test_polymorphic_counter_cache
1007 1008 1009
    tagging = taggings(:welcome_general)
    post    = posts(:welcome)
    comment = comments(:greetings)
1010

1011
    assert_difference lambda { post.reload.tags_count }, -1 do
1012
      assert_difference "comment.reload.tags_count", +1 do
1013 1014 1015 1016
        tagging.taggable = comment
      end
    end
  end
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035

  def test_polymorphic_with_custom_foreign_type
    sponsor = sponsors(:moustache_club_sponsor_for_groucho)
    groucho = members(:groucho)
    other   = members(:some_other_guy)

    assert_equal groucho, sponsor.sponsorable
    assert_equal groucho, sponsor.thing

    sponsor.thing = other

    assert_equal other, sponsor.sponsorable
    assert_equal other, sponsor.thing

    sponsor.sponsorable = groucho

    assert_equal groucho, sponsor.sponsorable
    assert_equal groucho, sponsor.thing
  end
1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056

  def test_build_with_conditions
    client = companies(:second_client)
    firm   = client.build_bob_firm

    assert_equal "Bob", firm.name
  end

  def test_create_with_conditions
    client = companies(:second_client)
    firm   = client.create_bob_firm

    assert_equal "Bob", firm.name
  end

  def test_create_bang_with_conditions
    client = companies(:second_client)
    firm   = client.create_bob_firm!

    assert_equal "Bob", firm.name
  end
1057 1058

  def test_build_with_block
1059
    client = Client.create(name: "Client Company")
1060

1061
    firm = client.build_firm { |f| f.name = "Agency Company" }
1062
    assert_equal "Agency Company", firm.name
1063 1064 1065
  end

  def test_create_with_block
1066
    client = Client.create(name: "Client Company")
1067

1068
    firm = client.create_firm { |f| f.name = "Agency Company" }
1069
    assert_equal "Agency Company", firm.name
1070 1071 1072
  end

  def test_create_bang_with_block
1073
    client = Client.create(name: "Client Company")
1074

1075
    firm = client.create_firm! { |f| f.name = "Agency Company" }
1076
    assert_equal "Agency Company", firm.name
1077
  end
1078 1079

  def test_should_set_foreign_key_on_create_association
1080
    client = Client.create! name: "fuu"
1081

1082
    firm = client.create_firm name: "baa"
1083 1084 1085 1086
    assert_equal firm.id, client.client_of
  end

  def test_should_set_foreign_key_on_create_association!
1087
    client = Client.create! name: "fuu"
1088

1089
    firm = client.create_firm! name: "baa"
1090 1091
    assert_equal firm.id, client.client_of
  end
1092 1093

  def test_self_referential_belongs_to_with_counter_cache_assigning_nil
1094
    comment = Comment.create! post: posts(:thinking), body: "fuu"
1095 1096 1097
    comment.parent = nil
    comment.save!

1098
    assert_nil comment.reload.parent
1099 1100
    assert_equal 0, comments(:greetings).reload.children_count
  end
1101

1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
  def test_belongs_to_with_id_assigning
    post = posts(:welcome)
    comment = Comment.create! body: "foo", post: post
    parent = comments(:greetings)
    assert_equal 0, parent.reload.children_count
    comment.parent_id = parent.id

    comment.save!
    assert_equal 1, parent.reload.children_count
  end

1113 1114 1115 1116 1117 1118 1119
  def test_belongs_to_with_out_of_range_value_assigning
    model = Class.new(Comment) do
      def self.name; "Temp"; end
      validates :post, presence: true
    end

    comment = model.new
1120
    comment.post_id = 9223372036854775808 # out of range in the bigint
1121 1122 1123 1124 1125 1126

    assert_nil comment.post
    assert_not comment.valid?
    assert_equal [{ error: :blank }], comment.errors.details[:post]
  end

1127 1128
  def test_polymorphic_with_custom_primary_key
    toy = Toy.create!
1129
    sponsor = Sponsor.create!(sponsorable: toy)
1130 1131 1132

    assert_equal toy, sponsor.reload.sponsorable
  end
J
Jon Leighton 已提交
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144

  test "stale tracking doesn't care about the type" do
    apple = Firm.create("name" => "Apple")
    citibank = Account.create("credit_limit" => 10)

    citibank.firm_id = apple.id
    citibank.firm # load it

    citibank.firm_id = apple.id.to_s

    assert !citibank.association(:firm).stale_target?
  end
1145

1146 1147
  def test_reflect_the_most_recent_change
    author1, author2 = Author.limit(2)
1148
    post = Post.new(title: "foo", body: "bar")
1149 1150 1151 1152 1153 1154 1155

    post.author    = author1
    post.author_id = author2.id

    assert post.save
    assert_equal post.author_id, author2.id
  end
1156

1157 1158
  test "dangerous association name raises ArgumentError" do
    [:errors, "errors", :save, "save"].each do |name|
1159 1160 1161 1162 1163 1164 1165
      assert_raises(ArgumentError, "Association #{name} should not be allowed") do
        Class.new(ActiveRecord::Base) do
          belongs_to name
        end
      end
    end
  end
1166

1167
  test "belongs_to works with model called Record" do
1168
    record = Record.create!
1169 1170
    Column.create! record: record
    assert_equal 1, Column.count
1171
  end
1172
end
1173 1174

class BelongsToWithForeignKeyTest < ActiveRecord::TestCase
1175 1176
  fixtures :authors, :author_addresses

1177 1178
  def test_destroy_linked_models
    address = AuthorAddress.create!
1179
    author = Author.create! name: "Author", author_address_id: address.id
1180 1181 1182 1183

    author.destroy!
  end
end